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
15114fc8bcc315fd2655b1b52a0b3472
train_001.jsonl
1604228700
You are given two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ positive integers, and an integer $$$x$$$. Please determine if one can rearrange the elements of $$$b$$$ so that $$$a_i + b_i \leq x$$$ holds for each $$$i$$$ ($$$1 \le i \le n$$$).
512 megabytes
import java.io.PrintWriter; import java.lang.reflect.Array; import java.util.*; /** * @author hypnos * @date 2020/11/2 */ public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int test = sc.nextInt(); PrintWriter writer = new PrintWriter(System.out); LinkedList<Integer> set = new LinkedList<>(); for (int i = 0; i < test; i++) { int n = sc.nextInt(); int x = sc.nextInt(); int[] a = new int[n]; int[] b = new int[n]; for (int j = 0; j < n; j++) { a[j] = sc.nextInt(); } for (int j = 0; j < n; j++) { b[j] = sc.nextInt(); } Arrays.sort(b); Arrays.sort(a); for (int j = n-1; j >= 0; j--) { for (int k = n-1; k >= 0; k--) { if (a[j]+b[k]<=x && !set.contains(k)){ set.add(k); break; } } } if (set.size()<b.length){ writer.println("No"); }else { writer.println("Yes"); } set.clear(); } writer.flush(); } }
Java
["4\n3 4\n1 2 3\n1 1 2\n\n2 6\n1 4\n2 5\n\n4 4\n1 2 3 4\n1 2 3 4\n\n1 5\n5\n5"]
1 second
["Yes\nYes\nNo\nNo"]
NoteIn the first test case, one can rearrange $$$b$$$ so it'll look like $$$[1, 2, 1]$$$. In this case, $$$1 + 1 \leq 4$$$; $$$2 + 2 \leq 4$$$; $$$3 + 1 \leq 4$$$.In the second test case, one can set $$$b$$$ to $$$[5, 2]$$$, then $$$1 + 5 \leq 6$$$; $$$4 + 2 \leq 6$$$.In the third test case, no matter how one shuffles array $$$b$$$, $$$a_4 + b_4 = 4 + b_4 &gt; 4$$$.In the fourth test case, there is only one rearrangement of array $$$b$$$ and it doesn't satisfy the condition since $$$5 + 5 &gt; 5$$$.
Java 8
standard input
[ "sortings", "greedy" ]
7e765c1b0e3f3e9c44de825a79bc1da2
The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. $$$t$$$ blocks follow, each describing an individual test case. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \leq n \leq 50$$$; $$$1 \leq x \leq 1000$$$) — the length of arrays $$$a$$$ and $$$b$$$, and the parameter $$$x$$$, described in the problem statement. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_1 \le a_2 \le \dots \le a_n \leq x$$$) — the elements of array $$$a$$$ in non-descending order. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_1 \le b_2 \le \dots \le b_n \leq x$$$) — the elements of array $$$b$$$ in non-descending order. Test cases are separated by a blank line.
800
For each test case print Yes if one can rearrange the corresponding array $$$b$$$ so that $$$a_i + b_i \leq x$$$ holds for each $$$i$$$ ($$$1 \le i \le n$$$) or No otherwise. Each character can be printed in any case.
standard output
PASSED
a1023822195a5b91e5bb9caf15aa7ee2
train_001.jsonl
1604228700
You are given two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ positive integers, and an integer $$$x$$$. Please determine if one can rearrange the elements of $$$b$$$ so that $$$a_i + b_i \leq x$$$ holds for each $$$i$$$ ($$$1 \le i \le n$$$).
512 megabytes
import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int T = scanner.nextInt(); while (T-- > 0) { int n = scanner.nextInt(); int x = scanner.nextInt(); Integer a[] = new Integer[n]; Integer b[] = new Integer[n]; for (int i = 0; i < n; i++) { a[i] = scanner.nextInt(); } for (int i = 0; i < n; i++) { b[i] = scanner.nextInt(); } Comparator<Integer> comparator = new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o2 - o1; } }; Arrays.sort(b, comparator); boolean yes = true; for (int i = 0; i < n; i++) { if (a[i] + b[i] > x) { yes = false; break; } } System.out.println(yes ? "Yes" : "No"); } } }
Java
["4\n3 4\n1 2 3\n1 1 2\n\n2 6\n1 4\n2 5\n\n4 4\n1 2 3 4\n1 2 3 4\n\n1 5\n5\n5"]
1 second
["Yes\nYes\nNo\nNo"]
NoteIn the first test case, one can rearrange $$$b$$$ so it'll look like $$$[1, 2, 1]$$$. In this case, $$$1 + 1 \leq 4$$$; $$$2 + 2 \leq 4$$$; $$$3 + 1 \leq 4$$$.In the second test case, one can set $$$b$$$ to $$$[5, 2]$$$, then $$$1 + 5 \leq 6$$$; $$$4 + 2 \leq 6$$$.In the third test case, no matter how one shuffles array $$$b$$$, $$$a_4 + b_4 = 4 + b_4 &gt; 4$$$.In the fourth test case, there is only one rearrangement of array $$$b$$$ and it doesn't satisfy the condition since $$$5 + 5 &gt; 5$$$.
Java 8
standard input
[ "sortings", "greedy" ]
7e765c1b0e3f3e9c44de825a79bc1da2
The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. $$$t$$$ blocks follow, each describing an individual test case. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \leq n \leq 50$$$; $$$1 \leq x \leq 1000$$$) — the length of arrays $$$a$$$ and $$$b$$$, and the parameter $$$x$$$, described in the problem statement. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_1 \le a_2 \le \dots \le a_n \leq x$$$) — the elements of array $$$a$$$ in non-descending order. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_1 \le b_2 \le \dots \le b_n \leq x$$$) — the elements of array $$$b$$$ in non-descending order. Test cases are separated by a blank line.
800
For each test case print Yes if one can rearrange the corresponding array $$$b$$$ so that $$$a_i + b_i \leq x$$$ holds for each $$$i$$$ ($$$1 \le i \le n$$$) or No otherwise. Each character can be printed in any case.
standard output
PASSED
03fe97622816d6d7e1e44a2b1c1d8ab6
train_001.jsonl
1604228700
You are given two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ positive integers, and an integer $$$x$$$. Please determine if one can rearrange the elements of $$$b$$$ so that $$$a_i + b_i \leq x$$$ holds for each $$$i$$$ ($$$1 \le i \le n$$$).
512 megabytes
import java.io.*; import java.util.*; /** * * @author Aaryan(AV) * AV */ public class Test { public static void main(String[] args) throws Exception { Scanner input = new Scanner(System.in); // BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); int tc = input.nextInt(); while(tc-->0){ // String str [] = br.readLine().split(" "); int n = input.nextInt(); int x = input.nextInt(); int a [] = new int[n]; int b [] =new int[n]; for(int i=0; i<a.length; i++){ a[i]=input.nextInt(); } for(int i=0; i<b.length; i++){ b[i]=input.nextInt(); } int flag=0; for(int i=0;i<a.length; i++){ if(a[i]+b[n-1-i]>x){ out.println("No"); out.flush(); flag=1; break; } } if(flag!=1){ out.println("Yes"); out.flush(); } } } }
Java
["4\n3 4\n1 2 3\n1 1 2\n\n2 6\n1 4\n2 5\n\n4 4\n1 2 3 4\n1 2 3 4\n\n1 5\n5\n5"]
1 second
["Yes\nYes\nNo\nNo"]
NoteIn the first test case, one can rearrange $$$b$$$ so it'll look like $$$[1, 2, 1]$$$. In this case, $$$1 + 1 \leq 4$$$; $$$2 + 2 \leq 4$$$; $$$3 + 1 \leq 4$$$.In the second test case, one can set $$$b$$$ to $$$[5, 2]$$$, then $$$1 + 5 \leq 6$$$; $$$4 + 2 \leq 6$$$.In the third test case, no matter how one shuffles array $$$b$$$, $$$a_4 + b_4 = 4 + b_4 &gt; 4$$$.In the fourth test case, there is only one rearrangement of array $$$b$$$ and it doesn't satisfy the condition since $$$5 + 5 &gt; 5$$$.
Java 8
standard input
[ "sortings", "greedy" ]
7e765c1b0e3f3e9c44de825a79bc1da2
The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. $$$t$$$ blocks follow, each describing an individual test case. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \leq n \leq 50$$$; $$$1 \leq x \leq 1000$$$) — the length of arrays $$$a$$$ and $$$b$$$, and the parameter $$$x$$$, described in the problem statement. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_1 \le a_2 \le \dots \le a_n \leq x$$$) — the elements of array $$$a$$$ in non-descending order. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_1 \le b_2 \le \dots \le b_n \leq x$$$) — the elements of array $$$b$$$ in non-descending order. Test cases are separated by a blank line.
800
For each test case print Yes if one can rearrange the corresponding array $$$b$$$ so that $$$a_i + b_i \leq x$$$ holds for each $$$i$$$ ($$$1 \le i \le n$$$) or No otherwise. Each character can be printed in any case.
standard output
PASSED
458b6436a481beb0786bcef9ea9ce3e5
train_001.jsonl
1604228700
You are given two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ positive integers, and an integer $$$x$$$. Please determine if one can rearrange the elements of $$$b$$$ so that $$$a_i + b_i \leq x$$$ holds for each $$$i$$$ ($$$1 \le i \le n$$$).
512 megabytes
import java.util.*; public class A { public static void main(String args[]){ Scanner sc=new Scanner(System.in); int tt=sc.nextInt(); while(tt-->0){ int n=sc.nextInt(); int x=sc.nextInt(); Integer a[]=new Integer[n];Integer b[]=new Integer[n]; for(int i=0;i<n;i++){ a[i]=sc.nextInt(); } for(int i=0;i<n;i++){ b[i]=sc.nextInt(); } int i=0; Arrays.sort(b,Collections.reverseOrder()); for(i=0;i<n;i++){ if(a[i]+b[i]>x){ System.out.println("No"); break; } } if(i==n)System.out.println("Yes"); } } }
Java
["4\n3 4\n1 2 3\n1 1 2\n\n2 6\n1 4\n2 5\n\n4 4\n1 2 3 4\n1 2 3 4\n\n1 5\n5\n5"]
1 second
["Yes\nYes\nNo\nNo"]
NoteIn the first test case, one can rearrange $$$b$$$ so it'll look like $$$[1, 2, 1]$$$. In this case, $$$1 + 1 \leq 4$$$; $$$2 + 2 \leq 4$$$; $$$3 + 1 \leq 4$$$.In the second test case, one can set $$$b$$$ to $$$[5, 2]$$$, then $$$1 + 5 \leq 6$$$; $$$4 + 2 \leq 6$$$.In the third test case, no matter how one shuffles array $$$b$$$, $$$a_4 + b_4 = 4 + b_4 &gt; 4$$$.In the fourth test case, there is only one rearrangement of array $$$b$$$ and it doesn't satisfy the condition since $$$5 + 5 &gt; 5$$$.
Java 8
standard input
[ "sortings", "greedy" ]
7e765c1b0e3f3e9c44de825a79bc1da2
The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. $$$t$$$ blocks follow, each describing an individual test case. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \leq n \leq 50$$$; $$$1 \leq x \leq 1000$$$) — the length of arrays $$$a$$$ and $$$b$$$, and the parameter $$$x$$$, described in the problem statement. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_1 \le a_2 \le \dots \le a_n \leq x$$$) — the elements of array $$$a$$$ in non-descending order. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_1 \le b_2 \le \dots \le b_n \leq x$$$) — the elements of array $$$b$$$ in non-descending order. Test cases are separated by a blank line.
800
For each test case print Yes if one can rearrange the corresponding array $$$b$$$ so that $$$a_i + b_i \leq x$$$ holds for each $$$i$$$ ($$$1 \le i \le n$$$) or No otherwise. Each character can be printed in any case.
standard output
PASSED
d3c833d056e78f60775b9d3a1ff9f507
train_001.jsonl
1604228700
You are given two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ positive integers, and an integer $$$x$$$. Please determine if one can rearrange the elements of $$$b$$$ so that $$$a_i + b_i \leq x$$$ holds for each $$$i$$$ ($$$1 \le i \le n$$$).
512 megabytes
import java.io.*; import java.util.*; public class A { public static void main(String[] args) throws IOException { FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); int t = in.nextInt(); for (int g = 0; g < t; g++) { int n = in.nextInt(); int x = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } Integer[] b = new Integer[n]; for (int i = 0; i < n; i++) { b[i] = in.nextInt(); } Arrays.sort(a); Arrays.sort(b, Collections.reverseOrder()); boolean f = true; for (int i = 0; i < n; i++) { if(a[i] + b[i] > x){ f = false; break; } } if(f){ out.println("Yes"); } else { out.println("No"); } } out.flush(); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String next() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } boolean hasMoreTokens() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return false; st = new StringTokenizer(s); } return true; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } static void debug(Object... o) { System.err.println(Arrays.deepToString(o)); } }
Java
["4\n3 4\n1 2 3\n1 1 2\n\n2 6\n1 4\n2 5\n\n4 4\n1 2 3 4\n1 2 3 4\n\n1 5\n5\n5"]
1 second
["Yes\nYes\nNo\nNo"]
NoteIn the first test case, one can rearrange $$$b$$$ so it'll look like $$$[1, 2, 1]$$$. In this case, $$$1 + 1 \leq 4$$$; $$$2 + 2 \leq 4$$$; $$$3 + 1 \leq 4$$$.In the second test case, one can set $$$b$$$ to $$$[5, 2]$$$, then $$$1 + 5 \leq 6$$$; $$$4 + 2 \leq 6$$$.In the third test case, no matter how one shuffles array $$$b$$$, $$$a_4 + b_4 = 4 + b_4 &gt; 4$$$.In the fourth test case, there is only one rearrangement of array $$$b$$$ and it doesn't satisfy the condition since $$$5 + 5 &gt; 5$$$.
Java 8
standard input
[ "sortings", "greedy" ]
7e765c1b0e3f3e9c44de825a79bc1da2
The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. $$$t$$$ blocks follow, each describing an individual test case. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \leq n \leq 50$$$; $$$1 \leq x \leq 1000$$$) — the length of arrays $$$a$$$ and $$$b$$$, and the parameter $$$x$$$, described in the problem statement. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_1 \le a_2 \le \dots \le a_n \leq x$$$) — the elements of array $$$a$$$ in non-descending order. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_1 \le b_2 \le \dots \le b_n \leq x$$$) — the elements of array $$$b$$$ in non-descending order. Test cases are separated by a blank line.
800
For each test case print Yes if one can rearrange the corresponding array $$$b$$$ so that $$$a_i + b_i \leq x$$$ holds for each $$$i$$$ ($$$1 \le i \le n$$$) or No otherwise. Each character can be printed in any case.
standard output
PASSED
d3ff758ebcf76c92228ce8bcf20923e8
train_001.jsonl
1604228700
You are given two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ positive integers, and an integer $$$x$$$. Please determine if one can rearrange the elements of $$$b$$$ so that $$$a_i + b_i \leq x$$$ holds for each $$$i$$$ ($$$1 \le i \le n$$$).
512 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws Exception{ Scanner scan = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int iter = scan.nextInt(); for (int i = 0; i < iter; i++) { int sz = scan.nextInt(); int x = scan.nextInt(); int[] arrA = new int[sz]; int[] arrB = new int[sz]; for (int j = 0; j < sz; j++) { arrA[j] = scan.nextInt(); } for (int j = 0; j < sz; j++) { arrB[j] = scan.nextInt(); } boolean f = true; for (int j = 0; j < sz; j++) { if(arrA[j] + arrB[sz - 1 - j] > x){ f = false; break; } } if(f) pw.println("Yes"); else pw.println("No"); if(i != iter -1) scan.nextLine(); } pw.flush(); pw.close(); } 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();} } }
Java
["4\n3 4\n1 2 3\n1 1 2\n\n2 6\n1 4\n2 5\n\n4 4\n1 2 3 4\n1 2 3 4\n\n1 5\n5\n5"]
1 second
["Yes\nYes\nNo\nNo"]
NoteIn the first test case, one can rearrange $$$b$$$ so it'll look like $$$[1, 2, 1]$$$. In this case, $$$1 + 1 \leq 4$$$; $$$2 + 2 \leq 4$$$; $$$3 + 1 \leq 4$$$.In the second test case, one can set $$$b$$$ to $$$[5, 2]$$$, then $$$1 + 5 \leq 6$$$; $$$4 + 2 \leq 6$$$.In the third test case, no matter how one shuffles array $$$b$$$, $$$a_4 + b_4 = 4 + b_4 &gt; 4$$$.In the fourth test case, there is only one rearrangement of array $$$b$$$ and it doesn't satisfy the condition since $$$5 + 5 &gt; 5$$$.
Java 8
standard input
[ "sortings", "greedy" ]
7e765c1b0e3f3e9c44de825a79bc1da2
The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. $$$t$$$ blocks follow, each describing an individual test case. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \leq n \leq 50$$$; $$$1 \leq x \leq 1000$$$) — the length of arrays $$$a$$$ and $$$b$$$, and the parameter $$$x$$$, described in the problem statement. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_1 \le a_2 \le \dots \le a_n \leq x$$$) — the elements of array $$$a$$$ in non-descending order. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_1 \le b_2 \le \dots \le b_n \leq x$$$) — the elements of array $$$b$$$ in non-descending order. Test cases are separated by a blank line.
800
For each test case print Yes if one can rearrange the corresponding array $$$b$$$ so that $$$a_i + b_i \leq x$$$ holds for each $$$i$$$ ($$$1 \le i \le n$$$) or No otherwise. Each character can be printed in any case.
standard output
PASSED
e9374f88bc52e26b569d42d2403f14f2
train_001.jsonl
1604228700
You are given two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ positive integers, and an integer $$$x$$$. Please determine if one can rearrange the elements of $$$b$$$ so that $$$a_i + b_i \leq x$$$ holds for each $$$i$$$ ($$$1 \le i \le n$$$).
512 megabytes
import java.util.*; import java.io.*; public class B { public static void main(String args[]) { Scanner in=new Scanner(System.in); int t=in.nextInt(); L: while(--t>=0) { int n=in.nextInt(); int x=in.nextInt(); int a[]=new int[n]; int b[]=new int[n]; for(int i=0;i<n;i++) a[i]=in.nextInt(); for(int j=0;j<n;j++) b[j]=in.nextInt(); in.nextLine(); Arrays.sort(a); Arrays.sort(b); for(int i=0;i<n;i++) { if(a[i]+b[n-i-1]>x) { System.out.println("NO"); continue L; } } System.out.println("YES"); } } /////////////////////////// static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] nextArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["4\n3 4\n1 2 3\n1 1 2\n\n2 6\n1 4\n2 5\n\n4 4\n1 2 3 4\n1 2 3 4\n\n1 5\n5\n5"]
1 second
["Yes\nYes\nNo\nNo"]
NoteIn the first test case, one can rearrange $$$b$$$ so it'll look like $$$[1, 2, 1]$$$. In this case, $$$1 + 1 \leq 4$$$; $$$2 + 2 \leq 4$$$; $$$3 + 1 \leq 4$$$.In the second test case, one can set $$$b$$$ to $$$[5, 2]$$$, then $$$1 + 5 \leq 6$$$; $$$4 + 2 \leq 6$$$.In the third test case, no matter how one shuffles array $$$b$$$, $$$a_4 + b_4 = 4 + b_4 &gt; 4$$$.In the fourth test case, there is only one rearrangement of array $$$b$$$ and it doesn't satisfy the condition since $$$5 + 5 &gt; 5$$$.
Java 8
standard input
[ "sortings", "greedy" ]
7e765c1b0e3f3e9c44de825a79bc1da2
The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. $$$t$$$ blocks follow, each describing an individual test case. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \leq n \leq 50$$$; $$$1 \leq x \leq 1000$$$) — the length of arrays $$$a$$$ and $$$b$$$, and the parameter $$$x$$$, described in the problem statement. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_1 \le a_2 \le \dots \le a_n \leq x$$$) — the elements of array $$$a$$$ in non-descending order. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_1 \le b_2 \le \dots \le b_n \leq x$$$) — the elements of array $$$b$$$ in non-descending order. Test cases are separated by a blank line.
800
For each test case print Yes if one can rearrange the corresponding array $$$b$$$ so that $$$a_i + b_i \leq x$$$ holds for each $$$i$$$ ($$$1 \le i \le n$$$) or No otherwise. Each character can be printed in any case.
standard output
PASSED
28766c42d9ddd37cd8a2f38c96bfaf89
train_001.jsonl
1604228700
You are given two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ positive integers, and an integer $$$x$$$. Please determine if one can rearrange the elements of $$$b$$$ so that $$$a_i + b_i \leq x$$$ holds for each $$$i$$$ ($$$1 \le i \le n$$$).
512 megabytes
import java.util.*; import java.io.*; public class A { public static void main(String args[]) { Scanner in=new Scanner(System.in); int t=in.nextInt(); L: while(--t>=0) { int n=in.nextInt(); int x=in.nextInt(); int a[]=new int[n]; int b[]=new int[n]; for(int i=0;i<n;i++) a[i]=in.nextInt(); for(int j=0;j<n;j++) b[j]=in.nextInt(); in.nextLine(); Arrays.sort(a); Arrays.sort(b); for(int i=0;i<n;i++) { if(a[i]+b[n-i-1]>x) { System.out.println("NO"); continue L; } } System.out.println("YES"); } } /////////////////////////// static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] nextArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["4\n3 4\n1 2 3\n1 1 2\n\n2 6\n1 4\n2 5\n\n4 4\n1 2 3 4\n1 2 3 4\n\n1 5\n5\n5"]
1 second
["Yes\nYes\nNo\nNo"]
NoteIn the first test case, one can rearrange $$$b$$$ so it'll look like $$$[1, 2, 1]$$$. In this case, $$$1 + 1 \leq 4$$$; $$$2 + 2 \leq 4$$$; $$$3 + 1 \leq 4$$$.In the second test case, one can set $$$b$$$ to $$$[5, 2]$$$, then $$$1 + 5 \leq 6$$$; $$$4 + 2 \leq 6$$$.In the third test case, no matter how one shuffles array $$$b$$$, $$$a_4 + b_4 = 4 + b_4 &gt; 4$$$.In the fourth test case, there is only one rearrangement of array $$$b$$$ and it doesn't satisfy the condition since $$$5 + 5 &gt; 5$$$.
Java 8
standard input
[ "sortings", "greedy" ]
7e765c1b0e3f3e9c44de825a79bc1da2
The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. $$$t$$$ blocks follow, each describing an individual test case. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \leq n \leq 50$$$; $$$1 \leq x \leq 1000$$$) — the length of arrays $$$a$$$ and $$$b$$$, and the parameter $$$x$$$, described in the problem statement. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_1 \le a_2 \le \dots \le a_n \leq x$$$) — the elements of array $$$a$$$ in non-descending order. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_1 \le b_2 \le \dots \le b_n \leq x$$$) — the elements of array $$$b$$$ in non-descending order. Test cases are separated by a blank line.
800
For each test case print Yes if one can rearrange the corresponding array $$$b$$$ so that $$$a_i + b_i \leq x$$$ holds for each $$$i$$$ ($$$1 \le i \le n$$$) or No otherwise. Each character can be printed in any case.
standard output
PASSED
54683464a12de85d00b3cf5c81f6d67c
train_001.jsonl
1604228700
You are given two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ positive integers, and an integer $$$x$$$. Please determine if one can rearrange the elements of $$$b$$$ so that $$$a_i + b_i \leq x$$$ holds for each $$$i$$$ ($$$1 \le i \le n$$$).
512 megabytes
import java.util.*; import java.io.*; public class C { public static void main(String args[]) { Scanner in=new Scanner(System.in); int t=in.nextInt(); L: while(--t>=0) { int n=in.nextInt(); int x=in.nextInt(); int a[]=new int[n]; int b[]=new int[n]; for(int i=0;i<n;i++) a[i]=in.nextInt(); for(int j=0;j<n;j++) b[j]=in.nextInt(); in.nextLine(); Arrays.sort(a); Arrays.sort(b); for(int i=0;i<n;i++) { if(a[i]+b[n-i-1]>x) { System.out.println("NO"); continue L; } } System.out.println("YES"); } } /////////////////////////// static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] nextArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["4\n3 4\n1 2 3\n1 1 2\n\n2 6\n1 4\n2 5\n\n4 4\n1 2 3 4\n1 2 3 4\n\n1 5\n5\n5"]
1 second
["Yes\nYes\nNo\nNo"]
NoteIn the first test case, one can rearrange $$$b$$$ so it'll look like $$$[1, 2, 1]$$$. In this case, $$$1 + 1 \leq 4$$$; $$$2 + 2 \leq 4$$$; $$$3 + 1 \leq 4$$$.In the second test case, one can set $$$b$$$ to $$$[5, 2]$$$, then $$$1 + 5 \leq 6$$$; $$$4 + 2 \leq 6$$$.In the third test case, no matter how one shuffles array $$$b$$$, $$$a_4 + b_4 = 4 + b_4 &gt; 4$$$.In the fourth test case, there is only one rearrangement of array $$$b$$$ and it doesn't satisfy the condition since $$$5 + 5 &gt; 5$$$.
Java 8
standard input
[ "sortings", "greedy" ]
7e765c1b0e3f3e9c44de825a79bc1da2
The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. $$$t$$$ blocks follow, each describing an individual test case. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \leq n \leq 50$$$; $$$1 \leq x \leq 1000$$$) — the length of arrays $$$a$$$ and $$$b$$$, and the parameter $$$x$$$, described in the problem statement. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_1 \le a_2 \le \dots \le a_n \leq x$$$) — the elements of array $$$a$$$ in non-descending order. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_1 \le b_2 \le \dots \le b_n \leq x$$$) — the elements of array $$$b$$$ in non-descending order. Test cases are separated by a blank line.
800
For each test case print Yes if one can rearrange the corresponding array $$$b$$$ so that $$$a_i + b_i \leq x$$$ holds for each $$$i$$$ ($$$1 \le i \le n$$$) or No otherwise. Each character can be printed in any case.
standard output
PASSED
7192413c99aed0a0d732abb107975368
train_001.jsonl
1537707900
Vasya owns a cornfield which can be defined with two integers $$$n$$$ and $$$d$$$. The cornfield can be represented as rectangle with vertices having Cartesian coordinates $$$(0, d), (d, 0), (n, n - d)$$$ and $$$(n - d, n)$$$. An example of a cornfield with $$$n = 7$$$ and $$$d = 2$$$. Vasya also knows that there are $$$m$$$ grasshoppers near the field (maybe even inside it). The $$$i$$$-th grasshopper is at the point $$$(x_i, y_i)$$$. Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside.Help Vasya! For each grasshopper determine if it is inside the field (including the border).
256 megabytes
import java.io.*; import java.math.*; import java.util.*; import static java.util.Arrays.fill; import static java.lang.Math.*; import static java.util.Arrays.sort; import static java.util.Collections.sort; public class VasyaandCornfield { static int mod = 1000000007; static InputReader in = new InputReader(System.in); static PrintWriter out = new PrintWriter(System.out); static float area(int x1, int y1, int x2, int y2, int x3, int y3) { return (float)Math.abs((x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0); } static boolean check(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4, int x, int y) { /* Calculate area of rectangle ABCD */ float A = area(x1, y1, x2, y2, x3, y3)+ area(x1, y1, x4, y4, x3, y3); /* Calculate area of triangle PAB */ float A1 = area(x, y, x1, y1, x2, y2); /* Calculate area of triangle PBC */ float A2 = area(x, y, x2, y2, x3, y3); /* Calculate area of triangle PCD */ float A3 = area(x, y, x3, y3, x4, y4); /* Calculate area of triangle PAD */ float A4 = area(x, y, x1, y1, x4, y4); /* Check if sum of A1, A2, A3 and A4 is same as A */ // tr(A+" "+A1+" "+A2+" "+A3+" "+A4); return (A == A1 + A2 + A3 + A4); } public static void main(String[] args) { int n=in.nextInt(); int d=in.nextInt(); int q=in.nextInt(); while(q-->0) { int x=in.nextInt(); int y=in.nextInt(); if(check(0, d, d, 0, n, n-d, n-d, n, x, y)) out.println("YES"); else out.println("NO"); } out.close(); } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream st) { this.stream = st; } public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public 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; } } private static void tr(Object... o) { if (!(System.getProperty("ONLINE_JUDGE") != null)) System.out.println(Arrays.deepToString(o)); } }
Java
["7 2\n4\n2 4\n4 1\n6 3\n4 5", "8 7\n4\n4 4\n2 8\n8 1\n6 1"]
1 second
["YES\nNO\nNO\nYES", "YES\nNO\nYES\nYES"]
NoteThe cornfield from the first example is pictured above. Grasshoppers with indices $$$1$$$ (coordinates $$$(2, 4)$$$) and $$$4$$$ (coordinates $$$(4, 5)$$$) are inside the cornfield.The cornfield from the second example is pictured below. Grasshoppers with indices $$$1$$$ (coordinates $$$(4, 4)$$$), $$$3$$$ (coordinates $$$(8, 1)$$$) and $$$4$$$ (coordinates $$$(6, 1)$$$) are inside the cornfield.
Java 8
standard input
[ "geometry" ]
9c84eb518c273942650c7262e5d8b45f
The first line contains two integers $$$n$$$ and $$$d$$$ ($$$1 \le d &lt; n \le 100$$$). The second line contains a single integer $$$m$$$ ($$$1 \le m \le 100$$$) — the number of grasshoppers. The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le n$$$) — position of the $$$i$$$-th grasshopper.
1,100
Print $$$m$$$ lines. The $$$i$$$-th line should contain "YES" if the position of the $$$i$$$-th grasshopper lies inside or on the border of the cornfield. Otherwise the $$$i$$$-th line should contain "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
58363dd5d3ed82a87156b2f016b267d2
train_001.jsonl
1537707900
Vasya owns a cornfield which can be defined with two integers $$$n$$$ and $$$d$$$. The cornfield can be represented as rectangle with vertices having Cartesian coordinates $$$(0, d), (d, 0), (n, n - d)$$$ and $$$(n - d, n)$$$. An example of a cornfield with $$$n = 7$$$ and $$$d = 2$$$. Vasya also knows that there are $$$m$$$ grasshoppers near the field (maybe even inside it). The $$$i$$$-th grasshopper is at the point $$$(x_i, y_i)$$$. Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside.Help Vasya! For each grasshopper determine if it is inside the field (including the border).
256 megabytes
import java.io.*; public class Main { private Reader r; private StreamTokenizer tk; public Main() { r = new BufferedReader(new InputStreamReader(System.in)); tk = new StreamTokenizer(r); } public void exit() throws IOException { r.close(); } public String readLine() throws IOException { tk.nextToken(); return tk.sval; } public int nextInt() throws IOException { tk.nextToken(); return (int) tk.nval; } public long nextLong() throws IOException { tk.nextToken(); return (long) tk.nval; } public static double distance(double x1, double y1, double x2, double y2) { return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)); } public static double square(double a, double b, double c) { double p = (a + b + c) / 2; return Math.sqrt(p * (p - a) * (p - b) * (p - c)); } public int vectorMultiply(int x, int y, int x1, int y1, int x2, int y2) { return (x2 - x1) * (y - y1) - (y2 - y1) * (x - x1); } public void run() throws IOException { int n = nextInt(); int d = nextInt(); int m = nextInt(); int x4 = d; int y4 = 0; int x3 = n; int y3 = n - d; int x1 = 0; int y1 = d; int x2 = n - d; int y2 = n; for(int i = 0; i < m; i++) { int x = nextInt(); int y = nextInt(); int m1 = vectorMultiply(x, y, x1, y1, x2, y2); int m2 = vectorMultiply(x, y, x2, y2, x3, y3); int m3 = vectorMultiply(x, y, x3, y3, x4, y4); int m4 = vectorMultiply(x, y, x4, y4, x1, y1); if (((m1 > 0 || (m1 == 0)) && (m2 > 0 || (m2 == 0)) && (m3 > 0 || (m3 == 0)) && (m4 > 0 || (m4 == 0))) || ((m1 < 0|| (m1 == 0)) && (m2 < 0 || (m2 == 0)) && (m3 < 0 || (m3 == 0)) && (m4 < 0 || (m4 == 0)))) { System.out.println("YES"); } else System.out.println("NO"); } } public static void main(String[] args) throws IOException { Main main = new Main(); main.run(); main.exit(); } }
Java
["7 2\n4\n2 4\n4 1\n6 3\n4 5", "8 7\n4\n4 4\n2 8\n8 1\n6 1"]
1 second
["YES\nNO\nNO\nYES", "YES\nNO\nYES\nYES"]
NoteThe cornfield from the first example is pictured above. Grasshoppers with indices $$$1$$$ (coordinates $$$(2, 4)$$$) and $$$4$$$ (coordinates $$$(4, 5)$$$) are inside the cornfield.The cornfield from the second example is pictured below. Grasshoppers with indices $$$1$$$ (coordinates $$$(4, 4)$$$), $$$3$$$ (coordinates $$$(8, 1)$$$) and $$$4$$$ (coordinates $$$(6, 1)$$$) are inside the cornfield.
Java 8
standard input
[ "geometry" ]
9c84eb518c273942650c7262e5d8b45f
The first line contains two integers $$$n$$$ and $$$d$$$ ($$$1 \le d &lt; n \le 100$$$). The second line contains a single integer $$$m$$$ ($$$1 \le m \le 100$$$) — the number of grasshoppers. The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le n$$$) — position of the $$$i$$$-th grasshopper.
1,100
Print $$$m$$$ lines. The $$$i$$$-th line should contain "YES" if the position of the $$$i$$$-th grasshopper lies inside or on the border of the cornfield. Otherwise the $$$i$$$-th line should contain "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
6c10941e1e512e57279bc18abcb5a309
train_001.jsonl
1537707900
Vasya owns a cornfield which can be defined with two integers $$$n$$$ and $$$d$$$. The cornfield can be represented as rectangle with vertices having Cartesian coordinates $$$(0, d), (d, 0), (n, n - d)$$$ and $$$(n - d, n)$$$. An example of a cornfield with $$$n = 7$$$ and $$$d = 2$$$. Vasya also knows that there are $$$m$$$ grasshoppers near the field (maybe even inside it). The $$$i$$$-th grasshopper is at the point $$$(x_i, y_i)$$$. Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside.Help Vasya! For each grasshopper determine if it is inside the field (including the border).
256 megabytes
import java.util.*; public class Solution { /* A utility function to calculate area of triangle formed by (x1, y1), (x2, y2) and (x3, y3) */ static float area(int x1, int y1, int x2, int y2, int x3, int y3) { return (float)Math.abs((x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0); } /* A function to check whether point P(x, y) lies inside the rectangle formed by A(x1, y1), B(x2, y2), C(x3, y3) and D(x4, y4) */ static boolean check(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4, int x, int y) { /* Calculate area of rectangle ABCD */ float A = area(x1, y1, x2, y2, x3, y3)+ area(x1, y1, x4, y4, x3, y3); /* Calculate area of triangle PAB */ float A1 = area(x, y, x1, y1, x2, y2); /* Calculate area of triangle PBC */ float A2 = area(x, y, x2, y2, x3, y3); /* Calculate area of triangle PCD */ float A3 = area(x, y, x3, y3, x4, y4); /* Calculate area of triangle PAD */ float A4 = area(x, y, x1, y1, x4, y4); /* Check if sum of A1, A2, A3 and A4 is same as A */ return (A == A1 + A2 + A3 + A4); } // Driver code public static void main (String[] args) { Scanner input = new Scanner(System.in); int n = input.nextInt(); int d = input.nextInt(); int cases = input.nextInt(); for(int index=0; index < cases; index++) { int newPx = input.nextInt(); int newPy = input.nextInt(); if(check(0,d,d,0,n,n-d,n-d,n,newPx,newPy)) { System.out.println("YES"); } else { System.out.println("NO"); } } } }
Java
["7 2\n4\n2 4\n4 1\n6 3\n4 5", "8 7\n4\n4 4\n2 8\n8 1\n6 1"]
1 second
["YES\nNO\nNO\nYES", "YES\nNO\nYES\nYES"]
NoteThe cornfield from the first example is pictured above. Grasshoppers with indices $$$1$$$ (coordinates $$$(2, 4)$$$) and $$$4$$$ (coordinates $$$(4, 5)$$$) are inside the cornfield.The cornfield from the second example is pictured below. Grasshoppers with indices $$$1$$$ (coordinates $$$(4, 4)$$$), $$$3$$$ (coordinates $$$(8, 1)$$$) and $$$4$$$ (coordinates $$$(6, 1)$$$) are inside the cornfield.
Java 8
standard input
[ "geometry" ]
9c84eb518c273942650c7262e5d8b45f
The first line contains two integers $$$n$$$ and $$$d$$$ ($$$1 \le d &lt; n \le 100$$$). The second line contains a single integer $$$m$$$ ($$$1 \le m \le 100$$$) — the number of grasshoppers. The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le n$$$) — position of the $$$i$$$-th grasshopper.
1,100
Print $$$m$$$ lines. The $$$i$$$-th line should contain "YES" if the position of the $$$i$$$-th grasshopper lies inside or on the border of the cornfield. Otherwise the $$$i$$$-th line should contain "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
3f098808a2439f1038587a5ea0a2f9a2
train_001.jsonl
1537707900
Vasya owns a cornfield which can be defined with two integers $$$n$$$ and $$$d$$$. The cornfield can be represented as rectangle with vertices having Cartesian coordinates $$$(0, d), (d, 0), (n, n - d)$$$ and $$$(n - d, n)$$$. An example of a cornfield with $$$n = 7$$$ and $$$d = 2$$$. Vasya also knows that there are $$$m$$$ grasshoppers near the field (maybe even inside it). The $$$i$$$-th grasshopper is at the point $$$(x_i, y_i)$$$. Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside.Help Vasya! For each grasshopper determine if it is inside the field (including the border).
256 megabytes
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { public static void main (String[] args) throws java.lang.Exception { Scanner sc = new Scanner(System.in); int n=sc.nextInt(); int d=sc.nextInt(); int q = sc.nextInt(); for(int i=0; i<q; i++) { int x = sc.nextInt(); int y = sc.nextInt(); if(x+y-d>=0 && x+y+d-2*n<=0 && y-x-d<=0 && y-x+d>=0 ) { System.out.println("YES"); } else { System.out.println("NO"); } } } }
Java
["7 2\n4\n2 4\n4 1\n6 3\n4 5", "8 7\n4\n4 4\n2 8\n8 1\n6 1"]
1 second
["YES\nNO\nNO\nYES", "YES\nNO\nYES\nYES"]
NoteThe cornfield from the first example is pictured above. Grasshoppers with indices $$$1$$$ (coordinates $$$(2, 4)$$$) and $$$4$$$ (coordinates $$$(4, 5)$$$) are inside the cornfield.The cornfield from the second example is pictured below. Grasshoppers with indices $$$1$$$ (coordinates $$$(4, 4)$$$), $$$3$$$ (coordinates $$$(8, 1)$$$) and $$$4$$$ (coordinates $$$(6, 1)$$$) are inside the cornfield.
Java 8
standard input
[ "geometry" ]
9c84eb518c273942650c7262e5d8b45f
The first line contains two integers $$$n$$$ and $$$d$$$ ($$$1 \le d &lt; n \le 100$$$). The second line contains a single integer $$$m$$$ ($$$1 \le m \le 100$$$) — the number of grasshoppers. The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le n$$$) — position of the $$$i$$$-th grasshopper.
1,100
Print $$$m$$$ lines. The $$$i$$$-th line should contain "YES" if the position of the $$$i$$$-th grasshopper lies inside or on the border of the cornfield. Otherwise the $$$i$$$-th line should contain "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
47d8dbaa5165d359d0c406f94c66d3ee
train_001.jsonl
1537707900
Vasya owns a cornfield which can be defined with two integers $$$n$$$ and $$$d$$$. The cornfield can be represented as rectangle with vertices having Cartesian coordinates $$$(0, d), (d, 0), (n, n - d)$$$ and $$$(n - d, n)$$$. An example of a cornfield with $$$n = 7$$$ and $$$d = 2$$$. Vasya also knows that there are $$$m$$$ grasshoppers near the field (maybe even inside it). The $$$i$$$-th grasshopper is at the point $$$(x_i, y_i)$$$. Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside.Help Vasya! For each grasshopper determine if it is inside the field (including the border).
256 megabytes
import java.util.Scanner; public class An2 { public boolean check(point p1, point p2, point pp) { int A = p1.y-p2.y; int B = p2.x-p1.x; int C = -(A*p1.x + B*p1.y); int D = A*pp.x + B*pp.y + C; if (D>=0) { return true; } else { return false; } } public static void main(String[] args) { An2 oj = new An2(); Scanner jk = new Scanner(System.in); int n = jk.nextInt(); int d = jk.nextInt(); int po = jk.nextInt(); point p1 = new point(0,d); point p2 = new point(d,0); point p3 = new point(n,n-d); point p4 = new point(n-d,n); //System.out.println(po); for (int i=0; i<po; i++) { point p = new point(jk.nextInt(),jk.nextInt()); if (oj.check(p1, p2, p) && oj.check(p2, p3, p) && oj.check(p3, p4, p) && oj.check(p4, p1, p)) { System.out.println("YES"); } else { System.out.println("NO"); } } } } class point { int x; int y; public point(int x, int y) { this.x = x; this.y = y; } }
Java
["7 2\n4\n2 4\n4 1\n6 3\n4 5", "8 7\n4\n4 4\n2 8\n8 1\n6 1"]
1 second
["YES\nNO\nNO\nYES", "YES\nNO\nYES\nYES"]
NoteThe cornfield from the first example is pictured above. Grasshoppers with indices $$$1$$$ (coordinates $$$(2, 4)$$$) and $$$4$$$ (coordinates $$$(4, 5)$$$) are inside the cornfield.The cornfield from the second example is pictured below. Grasshoppers with indices $$$1$$$ (coordinates $$$(4, 4)$$$), $$$3$$$ (coordinates $$$(8, 1)$$$) and $$$4$$$ (coordinates $$$(6, 1)$$$) are inside the cornfield.
Java 8
standard input
[ "geometry" ]
9c84eb518c273942650c7262e5d8b45f
The first line contains two integers $$$n$$$ and $$$d$$$ ($$$1 \le d &lt; n \le 100$$$). The second line contains a single integer $$$m$$$ ($$$1 \le m \le 100$$$) — the number of grasshoppers. The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le n$$$) — position of the $$$i$$$-th grasshopper.
1,100
Print $$$m$$$ lines. The $$$i$$$-th line should contain "YES" if the position of the $$$i$$$-th grasshopper lies inside or on the border of the cornfield. Otherwise the $$$i$$$-th line should contain "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
f128a377282c7e3e1c6d2855e9d0b21f
train_001.jsonl
1537707900
Vasya owns a cornfield which can be defined with two integers $$$n$$$ and $$$d$$$. The cornfield can be represented as rectangle with vertices having Cartesian coordinates $$$(0, d), (d, 0), (n, n - d)$$$ and $$$(n - d, n)$$$. An example of a cornfield with $$$n = 7$$$ and $$$d = 2$$$. Vasya also knows that there are $$$m$$$ grasshoppers near the field (maybe even inside it). The $$$i$$$-th grasshopper is at the point $$$(x_i, y_i)$$$. Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside.Help Vasya! For each grasshopper determine if it is inside the field (including the border).
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 Sol2 { public static void main (String[] args) throws java.lang.Exception { int x,y,sum,diff; Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int d=sc.nextInt(); int q=sc.nextInt(); for(int i=0;i<q;i++) { x=sc.nextInt(); y=sc.nextInt(); sum=x+y; diff=x-y; if(sum>=d&&sum<=(2*n-d)&&diff<=d&&diff>=-d) System.out.println("YES"); else System.out.println("NO"); } } }
Java
["7 2\n4\n2 4\n4 1\n6 3\n4 5", "8 7\n4\n4 4\n2 8\n8 1\n6 1"]
1 second
["YES\nNO\nNO\nYES", "YES\nNO\nYES\nYES"]
NoteThe cornfield from the first example is pictured above. Grasshoppers with indices $$$1$$$ (coordinates $$$(2, 4)$$$) and $$$4$$$ (coordinates $$$(4, 5)$$$) are inside the cornfield.The cornfield from the second example is pictured below. Grasshoppers with indices $$$1$$$ (coordinates $$$(4, 4)$$$), $$$3$$$ (coordinates $$$(8, 1)$$$) and $$$4$$$ (coordinates $$$(6, 1)$$$) are inside the cornfield.
Java 8
standard input
[ "geometry" ]
9c84eb518c273942650c7262e5d8b45f
The first line contains two integers $$$n$$$ and $$$d$$$ ($$$1 \le d &lt; n \le 100$$$). The second line contains a single integer $$$m$$$ ($$$1 \le m \le 100$$$) — the number of grasshoppers. The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le n$$$) — position of the $$$i$$$-th grasshopper.
1,100
Print $$$m$$$ lines. The $$$i$$$-th line should contain "YES" if the position of the $$$i$$$-th grasshopper lies inside or on the border of the cornfield. Otherwise the $$$i$$$-th line should contain "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
048f8b560a5a570671d140f9247469d4
train_001.jsonl
1537707900
Vasya owns a cornfield which can be defined with two integers $$$n$$$ and $$$d$$$. The cornfield can be represented as rectangle with vertices having Cartesian coordinates $$$(0, d), (d, 0), (n, n - d)$$$ and $$$(n - d, n)$$$. An example of a cornfield with $$$n = 7$$$ and $$$d = 2$$$. Vasya also knows that there are $$$m$$$ grasshoppers near the field (maybe even inside it). The $$$i$$$-th grasshopper is at the point $$$(x_i, y_i)$$$. Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside.Help Vasya! For each grasshopper determine if it is inside the field (including the border).
256 megabytes
import java.io.*; import java.util.*; public class VasyaandCornfield { public static void main(String[] t) { int m,n,d,i,x,y,c1,c2,c3,c4; Scanner sc=new Scanner(System.in); n=sc.nextInt(); d=sc.nextInt(); m=sc.nextInt(); for(i=0;i<m;i++) { x=sc.nextInt(); y=sc.nextInt(); c1=(x-y+d); c2=(x+y+d-(2*n)); c3=(x+y-d); c4=(x-y-d); if(c1>=0 && c2<=0 && c3>=0 && c4<=0) System.out.println("YES"); else System.out.println("NO"); } } }
Java
["7 2\n4\n2 4\n4 1\n6 3\n4 5", "8 7\n4\n4 4\n2 8\n8 1\n6 1"]
1 second
["YES\nNO\nNO\nYES", "YES\nNO\nYES\nYES"]
NoteThe cornfield from the first example is pictured above. Grasshoppers with indices $$$1$$$ (coordinates $$$(2, 4)$$$) and $$$4$$$ (coordinates $$$(4, 5)$$$) are inside the cornfield.The cornfield from the second example is pictured below. Grasshoppers with indices $$$1$$$ (coordinates $$$(4, 4)$$$), $$$3$$$ (coordinates $$$(8, 1)$$$) and $$$4$$$ (coordinates $$$(6, 1)$$$) are inside the cornfield.
Java 8
standard input
[ "geometry" ]
9c84eb518c273942650c7262e5d8b45f
The first line contains two integers $$$n$$$ and $$$d$$$ ($$$1 \le d &lt; n \le 100$$$). The second line contains a single integer $$$m$$$ ($$$1 \le m \le 100$$$) — the number of grasshoppers. The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le n$$$) — position of the $$$i$$$-th grasshopper.
1,100
Print $$$m$$$ lines. The $$$i$$$-th line should contain "YES" if the position of the $$$i$$$-th grasshopper lies inside or on the border of the cornfield. Otherwise the $$$i$$$-th line should contain "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
eedde231f54ba4b3e0d5c8c5ae4890c3
train_001.jsonl
1537707900
Vasya owns a cornfield which can be defined with two integers $$$n$$$ and $$$d$$$. The cornfield can be represented as rectangle with vertices having Cartesian coordinates $$$(0, d), (d, 0), (n, n - d)$$$ and $$$(n - d, n)$$$. An example of a cornfield with $$$n = 7$$$ and $$$d = 2$$$. Vasya also knows that there are $$$m$$$ grasshoppers near the field (maybe even inside it). The $$$i$$$-th grasshopper is at the point $$$(x_i, y_i)$$$. Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside.Help Vasya! For each grasshopper determine if it is inside the field (including the border).
256 megabytes
import java.io.*; import java.util.*; public class Main { static InputReader in = new InputReader(System.in); static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) throws IOException { int n = in.nextInt(); int d = in.nextInt(); int m = in.nextInt(); for(int i=0; i<m; ++i) { int x = in.nextInt(); int y = in.nextInt(); if(-d <= x-y && x-y <= d && d <= x+y && x+y <= 2 * n - d) { System.out.println("YES"); } else System.out.println("NO"); } out.close(); } } class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream st) { this.stream = st; } public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } }
Java
["7 2\n4\n2 4\n4 1\n6 3\n4 5", "8 7\n4\n4 4\n2 8\n8 1\n6 1"]
1 second
["YES\nNO\nNO\nYES", "YES\nNO\nYES\nYES"]
NoteThe cornfield from the first example is pictured above. Grasshoppers with indices $$$1$$$ (coordinates $$$(2, 4)$$$) and $$$4$$$ (coordinates $$$(4, 5)$$$) are inside the cornfield.The cornfield from the second example is pictured below. Grasshoppers with indices $$$1$$$ (coordinates $$$(4, 4)$$$), $$$3$$$ (coordinates $$$(8, 1)$$$) and $$$4$$$ (coordinates $$$(6, 1)$$$) are inside the cornfield.
Java 8
standard input
[ "geometry" ]
9c84eb518c273942650c7262e5d8b45f
The first line contains two integers $$$n$$$ and $$$d$$$ ($$$1 \le d &lt; n \le 100$$$). The second line contains a single integer $$$m$$$ ($$$1 \le m \le 100$$$) — the number of grasshoppers. The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le n$$$) — position of the $$$i$$$-th grasshopper.
1,100
Print $$$m$$$ lines. The $$$i$$$-th line should contain "YES" if the position of the $$$i$$$-th grasshopper lies inside or on the border of the cornfield. Otherwise the $$$i$$$-th line should contain "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
a7e8343e48ad1a55268f45b3c0eccf1a
train_001.jsonl
1537707900
Vasya owns a cornfield which can be defined with two integers $$$n$$$ and $$$d$$$. The cornfield can be represented as rectangle with vertices having Cartesian coordinates $$$(0, d), (d, 0), (n, n - d)$$$ and $$$(n - d, n)$$$. An example of a cornfield with $$$n = 7$$$ and $$$d = 2$$$. Vasya also knows that there are $$$m$$$ grasshoppers near the field (maybe even inside it). The $$$i$$$-th grasshopper is at the point $$$(x_i, y_i)$$$. Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside.Help Vasya! For each grasshopper determine if it is inside the field (including the border).
256 megabytes
import java.io.*; import java.util.*; import java.lang.*; public class Main { public static void main(String[] args) { FastReader in = new FastReader(); int n = in.nextInt(); int d = in.nextInt(); int m = in.nextInt(); int x1,x2,x3,x4,y1,y2,y3,y4; x1 = 0; y1 = d; x2 = d; y2 = 0; x3 = n; y3 = n-d; x4 = n-d; y4 = n; int position; for(int i=0 ;i<m ;i++){ int x = in.nextInt(); int y = in.nextInt(); boolean flag = true; position = (x3-x2)*(y-y2)-(y3-y2)*(x-x2); if(position<0) flag = false; position = (x2-x1)*(y-y1)-(y2-y1)*(x-x1); if(position<0) flag = false; position = (x4-x3)*(y-y3)-(y4-y3)*(x-x3); if(position<0) flag = false; position = (x4-x1)*(y-y1)-(y4-y1)*(x-x1); if(position>0) flag = false; if(flag) System.out.println("YES"); else System.out.println("NO"); } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["7 2\n4\n2 4\n4 1\n6 3\n4 5", "8 7\n4\n4 4\n2 8\n8 1\n6 1"]
1 second
["YES\nNO\nNO\nYES", "YES\nNO\nYES\nYES"]
NoteThe cornfield from the first example is pictured above. Grasshoppers with indices $$$1$$$ (coordinates $$$(2, 4)$$$) and $$$4$$$ (coordinates $$$(4, 5)$$$) are inside the cornfield.The cornfield from the second example is pictured below. Grasshoppers with indices $$$1$$$ (coordinates $$$(4, 4)$$$), $$$3$$$ (coordinates $$$(8, 1)$$$) and $$$4$$$ (coordinates $$$(6, 1)$$$) are inside the cornfield.
Java 8
standard input
[ "geometry" ]
9c84eb518c273942650c7262e5d8b45f
The first line contains two integers $$$n$$$ and $$$d$$$ ($$$1 \le d &lt; n \le 100$$$). The second line contains a single integer $$$m$$$ ($$$1 \le m \le 100$$$) — the number of grasshoppers. The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le n$$$) — position of the $$$i$$$-th grasshopper.
1,100
Print $$$m$$$ lines. The $$$i$$$-th line should contain "YES" if the position of the $$$i$$$-th grasshopper lies inside or on the border of the cornfield. Otherwise the $$$i$$$-th line should contain "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
da2abffddec24b98a499998bc5f3255f
train_001.jsonl
1537707900
Vasya owns a cornfield which can be defined with two integers $$$n$$$ and $$$d$$$. The cornfield can be represented as rectangle with vertices having Cartesian coordinates $$$(0, d), (d, 0), (n, n - d)$$$ and $$$(n - d, n)$$$. An example of a cornfield with $$$n = 7$$$ and $$$d = 2$$$. Vasya also knows that there are $$$m$$$ grasshoppers near the field (maybe even inside it). The $$$i$$$-th grasshopper is at the point $$$(x_i, y_i)$$$. Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside.Help Vasya! For each grasshopper determine if it is inside the field (including the border).
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Main { public static int N, D, Q; public static int x1, y1, x2, y2, x3, y3, x4, y4; public static void main(String[] args) throws IOException { BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(f.readLine()); N = Integer.parseInt(st.nextToken()); D = Integer.parseInt(st.nextToken()); x1 = 0; y1 = D; x2 = D; y2 = 0; x3 = N; y3 = N - D; x4 = N - D; y4 = N; Q = Integer.parseInt(f.readLine()); for (; Q > 0; Q--) { st = new StringTokenizer(f.readLine()); int x = Integer.parseInt(st.nextToken()); int y = Integer.parseInt(st.nextToken()); if (check(x1, y1, x2, y2, x3, y3, x4, y4, x, y)) { System.out.println("YES"); } else { System.out.println("NO"); } } } public static boolean check(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4, int x, int y) { double A = area(x1, y1, x2, y2, x3, y3) + area(x1, y1, x4, y4, x3, y3); double A1 = area(x, y, x1, y1, x2, y2); double A2 = area(x, y, x2, y2, x3, y3); double A3 = area(x, y, x3, y3, x4, y4); double A4 = area(x, y, x1, y1, x4, y4); return (A == A1 + A2 + A3 + A4); } public static double area(int x1, int y1, int x2, int y2, int x3, int y3) { return Math.abs((x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0); } }
Java
["7 2\n4\n2 4\n4 1\n6 3\n4 5", "8 7\n4\n4 4\n2 8\n8 1\n6 1"]
1 second
["YES\nNO\nNO\nYES", "YES\nNO\nYES\nYES"]
NoteThe cornfield from the first example is pictured above. Grasshoppers with indices $$$1$$$ (coordinates $$$(2, 4)$$$) and $$$4$$$ (coordinates $$$(4, 5)$$$) are inside the cornfield.The cornfield from the second example is pictured below. Grasshoppers with indices $$$1$$$ (coordinates $$$(4, 4)$$$), $$$3$$$ (coordinates $$$(8, 1)$$$) and $$$4$$$ (coordinates $$$(6, 1)$$$) are inside the cornfield.
Java 8
standard input
[ "geometry" ]
9c84eb518c273942650c7262e5d8b45f
The first line contains two integers $$$n$$$ and $$$d$$$ ($$$1 \le d &lt; n \le 100$$$). The second line contains a single integer $$$m$$$ ($$$1 \le m \le 100$$$) — the number of grasshoppers. The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le n$$$) — position of the $$$i$$$-th grasshopper.
1,100
Print $$$m$$$ lines. The $$$i$$$-th line should contain "YES" if the position of the $$$i$$$-th grasshopper lies inside or on the border of the cornfield. Otherwise the $$$i$$$-th line should contain "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
80fcb4e52874ac2044ba7640f712769b
train_001.jsonl
1537707900
Vasya owns a cornfield which can be defined with two integers $$$n$$$ and $$$d$$$. The cornfield can be represented as rectangle with vertices having Cartesian coordinates $$$(0, d), (d, 0), (n, n - d)$$$ and $$$(n - d, n)$$$. An example of a cornfield with $$$n = 7$$$ and $$$d = 2$$$. Vasya also knows that there are $$$m$$$ grasshoppers near the field (maybe even inside it). The $$$i$$$-th grasshopper is at the point $$$(x_i, y_i)$$$. Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside.Help Vasya! For each grasshopper determine if it is inside the field (including the border).
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.LongStream; import java.util.stream.Stream; public class Main2 { static long mod = 1000000007L; static FastScanner scanner; public static void main(String[] args) { scanner = new FastScanner(); int n = scanner.nextInt(); int d = scanner.nextInt(); int m = scanner.nextInt(); double x1 = d / Math.sqrt(2); double y1 = -d / Math.sqrt(2); double x2 = (n + n - d) / Math.sqrt(2); double y2 = d / Math.sqrt(2); for (int i = 0; i < m; i++) { int x = scanner.nextInt(); int y = scanner.nextInt(); double xx = (double)(x + y) / Math.sqrt(2); double yy = (double)(y - x) / Math.sqrt(2); if (xx >= x1 && xx <= x2 && yy >= y1 && yy <= y2) { System.out.println("YES"); } else { System.out.println("NO"); } } } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } String nextLine() { try { return br.readLine(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(); } } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } int[] nextIntArray(int n) { int[] res = new int[n]; for (int i = 0; i < n; i++) res[i] = nextInt(); return res; } long[] nextLongArray(int n) { long[] res = new long[n]; for (int i = 0; i < n; i++) res[i] = nextLong(); return res; } String[] nextStringArray(int n) { String[] res = new String[n]; for (int i = 0; i < n; i++) res[i] = nextToken(); return res; } } static class PrefixSums { long[] sums; public PrefixSums(long[] sums) { this.sums = sums; } public long sum(int fromInclusive, int toExclusive) { if (fromInclusive > toExclusive) throw new IllegalArgumentException("Wrong value"); return sums[toExclusive] - sums[fromInclusive]; } public static PrefixSums of(int[] ar) { long[] sums = new long[ar.length + 1]; for (int i = 1; i <= ar.length; i++) { sums[i] = sums[i - 1] + ar[i - 1]; } return new PrefixSums(sums); } public static PrefixSums of(long[] ar) { long[] sums = new long[ar.length + 1]; for (int i = 1; i <= ar.length; i++) { sums[i] = sums[i - 1] + ar[i - 1]; } return new PrefixSums(sums); } } static class ADUtils { static void sort(int[] ar) { Random rnd = ThreadLocalRandom.current(); for (int i = ar.length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); // Simple swap int a = ar[index]; ar[index] = ar[i]; ar[i] = a; } Arrays.sort(ar); } static void reverse(int[] arr) { int last = arr.length / 2; for (int i = 0; i < last; i++) { int tmp = arr[i]; arr[i] = arr[arr.length - 1 - i]; arr[arr.length - 1 - i] = tmp; } } static void sort(long[] ar) { Random rnd = ThreadLocalRandom.current(); for (int i = ar.length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); // Simple swap long a = ar[index]; ar[index] = ar[i]; ar[i] = a; } Arrays.sort(ar); } } static class MathUtils { static long[] FIRST_PRIMES = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89 , 97 , 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051}; static long[] primes(int to) { long[] all = new long[to + 1]; long[] primes = new long[to + 1]; all[1] = 1; int primesLength = 0; for (int i = 2; i <= to; i ++) { if (all[i] == 0) { primes[primesLength++] = i; all[i] = i; } for (int j = 0; j < primesLength && i * primes[j] <= to && all[i] >= primes[j]; j++) { all[(int) (i * primes[j])] = primes[j]; } } return Arrays.copyOf(primes, primesLength); } static long modpow(long b, long e, long m) { long result = 1; while (e > 0) { if ((e & 1) == 1) { /* multiply in this bit's contribution while using modulus to keep * result small */ result = (result * b) % m; } b = (b * b) % m; e >>= 1; } return result; } static long submod(long x, long y, long m) { return (x - y + m) % m; } } } //4 - 1 * 6 * 2 = 12 //5 - 4 * 6 * 2 = 48 //5(2) - 4 * 1 * 6 * 1 = 24 //3 - 2 * 2 = 4 //4(1) - 3 * 2 * 2 = 12 //4(2) - 3 * 2 = 6 //-------------------- // 7 3 // 4 - 1 * 6 * 6 = 36 C(3,3) // 5 - 1 * c(4,3) // c(5,3) // 1 // 1
Java
["7 2\n4\n2 4\n4 1\n6 3\n4 5", "8 7\n4\n4 4\n2 8\n8 1\n6 1"]
1 second
["YES\nNO\nNO\nYES", "YES\nNO\nYES\nYES"]
NoteThe cornfield from the first example is pictured above. Grasshoppers with indices $$$1$$$ (coordinates $$$(2, 4)$$$) and $$$4$$$ (coordinates $$$(4, 5)$$$) are inside the cornfield.The cornfield from the second example is pictured below. Grasshoppers with indices $$$1$$$ (coordinates $$$(4, 4)$$$), $$$3$$$ (coordinates $$$(8, 1)$$$) and $$$4$$$ (coordinates $$$(6, 1)$$$) are inside the cornfield.
Java 8
standard input
[ "geometry" ]
9c84eb518c273942650c7262e5d8b45f
The first line contains two integers $$$n$$$ and $$$d$$$ ($$$1 \le d &lt; n \le 100$$$). The second line contains a single integer $$$m$$$ ($$$1 \le m \le 100$$$) — the number of grasshoppers. The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le n$$$) — position of the $$$i$$$-th grasshopper.
1,100
Print $$$m$$$ lines. The $$$i$$$-th line should contain "YES" if the position of the $$$i$$$-th grasshopper lies inside or on the border of the cornfield. Otherwise the $$$i$$$-th line should contain "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
033f692788be93e138f497abd10e1f76
train_001.jsonl
1537707900
Vasya owns a cornfield which can be defined with two integers $$$n$$$ and $$$d$$$. The cornfield can be represented as rectangle with vertices having Cartesian coordinates $$$(0, d), (d, 0), (n, n - d)$$$ and $$$(n - d, n)$$$. An example of a cornfield with $$$n = 7$$$ and $$$d = 2$$$. Vasya also knows that there are $$$m$$$ grasshoppers near the field (maybe even inside it). The $$$i$$$-th grasshopper is at the point $$$(x_i, y_i)$$$. Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside.Help Vasya! For each grasshopper determine if it is inside the field (including the border).
256 megabytes
import java.util.*; import java.io.*; public class Main{ public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader inp = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Solver solver = new Solver(); solver.solve(inp, out); out.close(); } static class Solver { private void solve(InputReader inp, PrintWriter out1) { int n = inp.nextInt(); int d = inp.nextInt(); int m = inp.nextInt(); for(int i=0;i<m;i++) { int x = inp.nextInt(); int out = inp.nextInt(); if((-x+d)<=out&&(x-d)<=out&&(x+d)>=out&&(-x+(2*n)-d)>=out) System.out.println("YES"); else System.out.println("NO"); } } } static class InputReader { BufferedReader reader; StringTokenizer tokenizer; InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } 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()); } } } class ele{ long value; int i; boolean flag; public ele(long value,int i) { this.value = value; this.i=i; this.flag = false; } }
Java
["7 2\n4\n2 4\n4 1\n6 3\n4 5", "8 7\n4\n4 4\n2 8\n8 1\n6 1"]
1 second
["YES\nNO\nNO\nYES", "YES\nNO\nYES\nYES"]
NoteThe cornfield from the first example is pictured above. Grasshoppers with indices $$$1$$$ (coordinates $$$(2, 4)$$$) and $$$4$$$ (coordinates $$$(4, 5)$$$) are inside the cornfield.The cornfield from the second example is pictured below. Grasshoppers with indices $$$1$$$ (coordinates $$$(4, 4)$$$), $$$3$$$ (coordinates $$$(8, 1)$$$) and $$$4$$$ (coordinates $$$(6, 1)$$$) are inside the cornfield.
Java 8
standard input
[ "geometry" ]
9c84eb518c273942650c7262e5d8b45f
The first line contains two integers $$$n$$$ and $$$d$$$ ($$$1 \le d &lt; n \le 100$$$). The second line contains a single integer $$$m$$$ ($$$1 \le m \le 100$$$) — the number of grasshoppers. The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le n$$$) — position of the $$$i$$$-th grasshopper.
1,100
Print $$$m$$$ lines. The $$$i$$$-th line should contain "YES" if the position of the $$$i$$$-th grasshopper lies inside or on the border of the cornfield. Otherwise the $$$i$$$-th line should contain "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
4f130656421e97a3dc576bcfb57fda02
train_001.jsonl
1537707900
Vasya owns a cornfield which can be defined with two integers $$$n$$$ and $$$d$$$. The cornfield can be represented as rectangle with vertices having Cartesian coordinates $$$(0, d), (d, 0), (n, n - d)$$$ and $$$(n - d, n)$$$. An example of a cornfield with $$$n = 7$$$ and $$$d = 2$$$. Vasya also knows that there are $$$m$$$ grasshoppers near the field (maybe even inside it). The $$$i$$$-th grasshopper is at the point $$$(x_i, y_i)$$$. Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside.Help Vasya! For each grasshopper determine if it is inside the field (including the border).
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args){ Scanner in=new Scanner(System.in); int n=in.nextInt(),m=in.nextInt(),k=in.nextInt(); for (int i=0; i<k; i++) { int a=in.nextInt(),b=in.nextInt(); if (Math.abs(a-b)<=m&&a+b>=m&&a+b<=n+n-m) System.out.println("YES"); else System.out.println("NO"); } } }
Java
["7 2\n4\n2 4\n4 1\n6 3\n4 5", "8 7\n4\n4 4\n2 8\n8 1\n6 1"]
1 second
["YES\nNO\nNO\nYES", "YES\nNO\nYES\nYES"]
NoteThe cornfield from the first example is pictured above. Grasshoppers with indices $$$1$$$ (coordinates $$$(2, 4)$$$) and $$$4$$$ (coordinates $$$(4, 5)$$$) are inside the cornfield.The cornfield from the second example is pictured below. Grasshoppers with indices $$$1$$$ (coordinates $$$(4, 4)$$$), $$$3$$$ (coordinates $$$(8, 1)$$$) and $$$4$$$ (coordinates $$$(6, 1)$$$) are inside the cornfield.
Java 8
standard input
[ "geometry" ]
9c84eb518c273942650c7262e5d8b45f
The first line contains two integers $$$n$$$ and $$$d$$$ ($$$1 \le d &lt; n \le 100$$$). The second line contains a single integer $$$m$$$ ($$$1 \le m \le 100$$$) — the number of grasshoppers. The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le n$$$) — position of the $$$i$$$-th grasshopper.
1,100
Print $$$m$$$ lines. The $$$i$$$-th line should contain "YES" if the position of the $$$i$$$-th grasshopper lies inside or on the border of the cornfield. Otherwise the $$$i$$$-th line should contain "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
fcc7cbf909677d5bab74f8ed46780a4e
train_001.jsonl
1537707900
Vasya owns a cornfield which can be defined with two integers $$$n$$$ and $$$d$$$. The cornfield can be represented as rectangle with vertices having Cartesian coordinates $$$(0, d), (d, 0), (n, n - d)$$$ and $$$(n - d, n)$$$. An example of a cornfield with $$$n = 7$$$ and $$$d = 2$$$. Vasya also knows that there are $$$m$$$ grasshoppers near the field (maybe even inside it). The $$$i$$$-th grasshopper is at the point $$$(x_i, y_i)$$$. Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside.Help Vasya! For each grasshopper determine if it is inside the field (including the border).
256 megabytes
import java.util.Scanner; public class SolutionB { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n, d, m; n = input.nextInt(); d = input.nextInt(); m = input.nextInt(); int i = 0; while(i < m) { int x = input.nextInt(); int y = input.nextInt(); //System.out.println("x equals" + x + " y equals " + y); if (lieInRectangle(n , d , x , y)) { System.out.println("YES"); } else { System.out.println("NO"); } i = i +1; } input.close(); } public static Boolean lieInRectangle(int n , int d, int x , int y) { int x1 = 0; int x2 = d; int x3 = n; int x4 = n - d; int y1 = d; int y2 = 0; int y3 = n - d; int y4 = n; float A = area(x1, y1, x2, y2, x3, y3) + area(x1, y1, x4, y4, x3, y3); float A1 = area(x, y, x1, y1, x2, y2); float A2 = area(x, y, x2, y2, x3, y3); float A3 = area(x, y, x3, y3, x4, y4); float A4 = area(x, y, x1, y1, x4, y4); return (A == A1 + A2 + A3 + A4); } static float area(int x1, int y1, int x2, int y2, int x3, int y3) { return (float)Math.abs((x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0); } }
Java
["7 2\n4\n2 4\n4 1\n6 3\n4 5", "8 7\n4\n4 4\n2 8\n8 1\n6 1"]
1 second
["YES\nNO\nNO\nYES", "YES\nNO\nYES\nYES"]
NoteThe cornfield from the first example is pictured above. Grasshoppers with indices $$$1$$$ (coordinates $$$(2, 4)$$$) and $$$4$$$ (coordinates $$$(4, 5)$$$) are inside the cornfield.The cornfield from the second example is pictured below. Grasshoppers with indices $$$1$$$ (coordinates $$$(4, 4)$$$), $$$3$$$ (coordinates $$$(8, 1)$$$) and $$$4$$$ (coordinates $$$(6, 1)$$$) are inside the cornfield.
Java 8
standard input
[ "geometry" ]
9c84eb518c273942650c7262e5d8b45f
The first line contains two integers $$$n$$$ and $$$d$$$ ($$$1 \le d &lt; n \le 100$$$). The second line contains a single integer $$$m$$$ ($$$1 \le m \le 100$$$) — the number of grasshoppers. The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le n$$$) — position of the $$$i$$$-th grasshopper.
1,100
Print $$$m$$$ lines. The $$$i$$$-th line should contain "YES" if the position of the $$$i$$$-th grasshopper lies inside or on the border of the cornfield. Otherwise the $$$i$$$-th line should contain "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
97125b49fca82054f30d96f812c98bf9
train_001.jsonl
1537707900
Vasya owns a cornfield which can be defined with two integers $$$n$$$ and $$$d$$$. The cornfield can be represented as rectangle with vertices having Cartesian coordinates $$$(0, d), (d, 0), (n, n - d)$$$ and $$$(n - d, n)$$$. An example of a cornfield with $$$n = 7$$$ and $$$d = 2$$$. Vasya also knows that there are $$$m$$$ grasshoppers near the field (maybe even inside it). The $$$i$$$-th grasshopper is at the point $$$(x_i, y_i)$$$. Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside.Help Vasya! For each grasshopper determine if it is inside the field (including the border).
256 megabytes
import java.util.*; import java.io.*; public class Codeforces1058B { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int d = scanner.nextInt(); int m = scanner.nextInt(); for(int iM = 0; iM < m; iM++) { int x = scanner.nextInt(); int y = scanner.nextInt(); if(x + y >= d && x + y <= n * 2 - d && x - y >= -d && x - y <= d) { System.out.println("YES"); } else { System.out.println("NO"); } } } }
Java
["7 2\n4\n2 4\n4 1\n6 3\n4 5", "8 7\n4\n4 4\n2 8\n8 1\n6 1"]
1 second
["YES\nNO\nNO\nYES", "YES\nNO\nYES\nYES"]
NoteThe cornfield from the first example is pictured above. Grasshoppers with indices $$$1$$$ (coordinates $$$(2, 4)$$$) and $$$4$$$ (coordinates $$$(4, 5)$$$) are inside the cornfield.The cornfield from the second example is pictured below. Grasshoppers with indices $$$1$$$ (coordinates $$$(4, 4)$$$), $$$3$$$ (coordinates $$$(8, 1)$$$) and $$$4$$$ (coordinates $$$(6, 1)$$$) are inside the cornfield.
Java 8
standard input
[ "geometry" ]
9c84eb518c273942650c7262e5d8b45f
The first line contains two integers $$$n$$$ and $$$d$$$ ($$$1 \le d &lt; n \le 100$$$). The second line contains a single integer $$$m$$$ ($$$1 \le m \le 100$$$) — the number of grasshoppers. The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le n$$$) — position of the $$$i$$$-th grasshopper.
1,100
Print $$$m$$$ lines. The $$$i$$$-th line should contain "YES" if the position of the $$$i$$$-th grasshopper lies inside or on the border of the cornfield. Otherwise the $$$i$$$-th line should contain "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
980a3c5f4f9b0e660b8226fc051c8ecf
train_001.jsonl
1537707900
Vasya owns a cornfield which can be defined with two integers $$$n$$$ and $$$d$$$. The cornfield can be represented as rectangle with vertices having Cartesian coordinates $$$(0, d), (d, 0), (n, n - d)$$$ and $$$(n - d, n)$$$. An example of a cornfield with $$$n = 7$$$ and $$$d = 2$$$. Vasya also knows that there are $$$m$$$ grasshoppers near the field (maybe even inside it). The $$$i$$$-th grasshopper is at the point $$$(x_i, y_i)$$$. Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside.Help Vasya! For each grasshopper determine if it is inside the field (including the border).
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; /** * @author Don Li */ public class VasyaAndCornfield { void solve() { int n = in.nextInt(), d = in.nextInt(), Q = in.nextInt(); while (Q-- > 0) { int x = in.nextInt(), y = in.nextInt(); if (x + y >= d && x + y <= 2 * n - d && x - y >= -d && x - y <= d) out.println("YES"); else out.println("NO"); } } public static void main(String[] args) { in = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); new VasyaAndCornfield().solve(); out.close(); } static FastScanner in; static PrintWriter out; static class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["7 2\n4\n2 4\n4 1\n6 3\n4 5", "8 7\n4\n4 4\n2 8\n8 1\n6 1"]
1 second
["YES\nNO\nNO\nYES", "YES\nNO\nYES\nYES"]
NoteThe cornfield from the first example is pictured above. Grasshoppers with indices $$$1$$$ (coordinates $$$(2, 4)$$$) and $$$4$$$ (coordinates $$$(4, 5)$$$) are inside the cornfield.The cornfield from the second example is pictured below. Grasshoppers with indices $$$1$$$ (coordinates $$$(4, 4)$$$), $$$3$$$ (coordinates $$$(8, 1)$$$) and $$$4$$$ (coordinates $$$(6, 1)$$$) are inside the cornfield.
Java 8
standard input
[ "geometry" ]
9c84eb518c273942650c7262e5d8b45f
The first line contains two integers $$$n$$$ and $$$d$$$ ($$$1 \le d &lt; n \le 100$$$). The second line contains a single integer $$$m$$$ ($$$1 \le m \le 100$$$) — the number of grasshoppers. The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le n$$$) — position of the $$$i$$$-th grasshopper.
1,100
Print $$$m$$$ lines. The $$$i$$$-th line should contain "YES" if the position of the $$$i$$$-th grasshopper lies inside or on the border of the cornfield. Otherwise the $$$i$$$-th line should contain "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
f453ff79bba4fdb1b72dc3c58c490882
train_001.jsonl
1537707900
Vasya owns a cornfield which can be defined with two integers $$$n$$$ and $$$d$$$. The cornfield can be represented as rectangle with vertices having Cartesian coordinates $$$(0, d), (d, 0), (n, n - d)$$$ and $$$(n - d, n)$$$. An example of a cornfield with $$$n = 7$$$ and $$$d = 2$$$. Vasya also knows that there are $$$m$$$ grasshoppers near the field (maybe even inside it). The $$$i$$$-th grasshopper is at the point $$$(x_i, y_i)$$$. Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside.Help Vasya! For each grasshopper determine if it is inside the field (including the border).
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Scanner; /** * Built using CHelper plug-in * Actual solution is at the top * * @author llamaoo7 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); BVasyaAndCornfield solver = new BVasyaAndCornfield(); solver.solve(1, in, out); out.close(); } static class BVasyaAndCornfield { public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(); int d = in.nextInt(); int m = in.nextInt(); for (int i = 0; i < m; i++) { int x = in.nextInt(); int y = in.nextInt(); if (y >= -1 * x + d && y <= -1 * x + 2 * n - d && y <= x + d && y >= x - d) { out.println("YES"); } else { out.println("NO"); } } } } }
Java
["7 2\n4\n2 4\n4 1\n6 3\n4 5", "8 7\n4\n4 4\n2 8\n8 1\n6 1"]
1 second
["YES\nNO\nNO\nYES", "YES\nNO\nYES\nYES"]
NoteThe cornfield from the first example is pictured above. Grasshoppers with indices $$$1$$$ (coordinates $$$(2, 4)$$$) and $$$4$$$ (coordinates $$$(4, 5)$$$) are inside the cornfield.The cornfield from the second example is pictured below. Grasshoppers with indices $$$1$$$ (coordinates $$$(4, 4)$$$), $$$3$$$ (coordinates $$$(8, 1)$$$) and $$$4$$$ (coordinates $$$(6, 1)$$$) are inside the cornfield.
Java 8
standard input
[ "geometry" ]
9c84eb518c273942650c7262e5d8b45f
The first line contains two integers $$$n$$$ and $$$d$$$ ($$$1 \le d &lt; n \le 100$$$). The second line contains a single integer $$$m$$$ ($$$1 \le m \le 100$$$) — the number of grasshoppers. The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le n$$$) — position of the $$$i$$$-th grasshopper.
1,100
Print $$$m$$$ lines. The $$$i$$$-th line should contain "YES" if the position of the $$$i$$$-th grasshopper lies inside or on the border of the cornfield. Otherwise the $$$i$$$-th line should contain "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
cbfe4c98d2b84878eb8a3da673bea8d1
train_001.jsonl
1537707900
Vasya owns a cornfield which can be defined with two integers $$$n$$$ and $$$d$$$. The cornfield can be represented as rectangle with vertices having Cartesian coordinates $$$(0, d), (d, 0), (n, n - d)$$$ and $$$(n - d, n)$$$. An example of a cornfield with $$$n = 7$$$ and $$$d = 2$$$. Vasya also knows that there are $$$m$$$ grasshoppers near the field (maybe even inside it). The $$$i$$$-th grasshopper is at the point $$$(x_i, y_i)$$$. Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside.Help Vasya! For each grasshopper determine if it is inside the field (including the border).
256 megabytes
/* Solution to http://codeforces.com/contest/1058/problem/B * using geometry library. * * Test for insideness (including boundaries) in convex polygon * @author godmar */ import java.util.*; import java.util.stream.*; import static java.lang.Math.*; public class BCCW { public static void main(String []av) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int d = s.nextInt(); P [] poly = new P[] { new P(0, d), new P(n-d, n), new P(n, n-d), new P(d, 0) }; int m = s.nextInt(); for (int i = 0; i < m; i++) { final P test = P.read(s); if (IntStream.range(0, 4).noneMatch((j) -> poly[j].isCCW(poly[(j+1)%4], test))) System.out.println("YES"); else System.out.println("NO"); } } static class P { final double x, y; P(double x, double y) { this.x = x; this.y = y; } P sub(P that) { return new P(x - that.x, y - that.y); } static P read(Scanner s) { return new P(s.nextDouble(), s.nextDouble()); } double det(P that) { return this.x * that.y - this.y * that.x; } double crossproduct(P that) { return this.det(that); } double signedParallelogramArea(P b, P c) { return (b.sub(this).crossproduct(c.sub(this))); } // is going from this to b to c a CCW turn? Do not use if points may be collinear boolean isCCW(P b, P c) { return signedParallelogramArea(b, c) > 0; } } }
Java
["7 2\n4\n2 4\n4 1\n6 3\n4 5", "8 7\n4\n4 4\n2 8\n8 1\n6 1"]
1 second
["YES\nNO\nNO\nYES", "YES\nNO\nYES\nYES"]
NoteThe cornfield from the first example is pictured above. Grasshoppers with indices $$$1$$$ (coordinates $$$(2, 4)$$$) and $$$4$$$ (coordinates $$$(4, 5)$$$) are inside the cornfield.The cornfield from the second example is pictured below. Grasshoppers with indices $$$1$$$ (coordinates $$$(4, 4)$$$), $$$3$$$ (coordinates $$$(8, 1)$$$) and $$$4$$$ (coordinates $$$(6, 1)$$$) are inside the cornfield.
Java 8
standard input
[ "geometry" ]
9c84eb518c273942650c7262e5d8b45f
The first line contains two integers $$$n$$$ and $$$d$$$ ($$$1 \le d &lt; n \le 100$$$). The second line contains a single integer $$$m$$$ ($$$1 \le m \le 100$$$) — the number of grasshoppers. The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le n$$$) — position of the $$$i$$$-th grasshopper.
1,100
Print $$$m$$$ lines. The $$$i$$$-th line should contain "YES" if the position of the $$$i$$$-th grasshopper lies inside or on the border of the cornfield. Otherwise the $$$i$$$-th line should contain "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
f17d85b751bfaf1a13345949046367b4
train_001.jsonl
1537707900
Vasya owns a cornfield which can be defined with two integers $$$n$$$ and $$$d$$$. The cornfield can be represented as rectangle with vertices having Cartesian coordinates $$$(0, d), (d, 0), (n, n - d)$$$ and $$$(n - d, n)$$$. An example of a cornfield with $$$n = 7$$$ and $$$d = 2$$$. Vasya also knows that there are $$$m$$$ grasshoppers near the field (maybe even inside it). The $$$i$$$-th grasshopper is at the point $$$(x_i, y_i)$$$. Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside.Help Vasya! For each grasshopper determine if it is inside the field (including the border).
256 megabytes
import java.util.*; public class shashwat{ static Scanner in=new Scanner(System.in); public static void main(String args[]){ int n=in.nextInt(); int d=in.nextInt(); int a=in.nextInt(); for(int i=0;i<a;i++){ int x=in.nextInt(); int y=in.nextInt(); if(x+y>=d && x-y<=d && x+y<=(2*n-d) && x-y>=-d){ System.out.println("YES"); } else System.out.println("NO"); } } }
Java
["7 2\n4\n2 4\n4 1\n6 3\n4 5", "8 7\n4\n4 4\n2 8\n8 1\n6 1"]
1 second
["YES\nNO\nNO\nYES", "YES\nNO\nYES\nYES"]
NoteThe cornfield from the first example is pictured above. Grasshoppers with indices $$$1$$$ (coordinates $$$(2, 4)$$$) and $$$4$$$ (coordinates $$$(4, 5)$$$) are inside the cornfield.The cornfield from the second example is pictured below. Grasshoppers with indices $$$1$$$ (coordinates $$$(4, 4)$$$), $$$3$$$ (coordinates $$$(8, 1)$$$) and $$$4$$$ (coordinates $$$(6, 1)$$$) are inside the cornfield.
Java 8
standard input
[ "geometry" ]
9c84eb518c273942650c7262e5d8b45f
The first line contains two integers $$$n$$$ and $$$d$$$ ($$$1 \le d &lt; n \le 100$$$). The second line contains a single integer $$$m$$$ ($$$1 \le m \le 100$$$) — the number of grasshoppers. The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le n$$$) — position of the $$$i$$$-th grasshopper.
1,100
Print $$$m$$$ lines. The $$$i$$$-th line should contain "YES" if the position of the $$$i$$$-th grasshopper lies inside or on the border of the cornfield. Otherwise the $$$i$$$-th line should contain "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
6b3c4f70966ddcf1e5e0822614e0cc04
train_001.jsonl
1537707900
Vasya owns a cornfield which can be defined with two integers $$$n$$$ and $$$d$$$. The cornfield can be represented as rectangle with vertices having Cartesian coordinates $$$(0, d), (d, 0), (n, n - d)$$$ and $$$(n - d, n)$$$. An example of a cornfield with $$$n = 7$$$ and $$$d = 2$$$. Vasya also knows that there are $$$m$$$ grasshoppers near the field (maybe even inside it). The $$$i$$$-th grasshopper is at the point $$$(x_i, y_i)$$$. Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside.Help Vasya! For each grasshopper determine if it is inside the field (including the border).
256 megabytes
import java.util.*; public class shashwat{ static Scanner in=new Scanner(System.in); public static void main(String args[]){ int n=in.nextInt(); int d=in.nextInt(); int a=in.nextInt(); for(int i=0;i<a;i++){ int x=in.nextInt(); int y=in.nextInt(); if(x+y>=d && x-y<=d && x+y<=(2*n-d) && x-y>=-d){ System.out.println("YES"); } else System.out.println("NO"); } } }
Java
["7 2\n4\n2 4\n4 1\n6 3\n4 5", "8 7\n4\n4 4\n2 8\n8 1\n6 1"]
1 second
["YES\nNO\nNO\nYES", "YES\nNO\nYES\nYES"]
NoteThe cornfield from the first example is pictured above. Grasshoppers with indices $$$1$$$ (coordinates $$$(2, 4)$$$) and $$$4$$$ (coordinates $$$(4, 5)$$$) are inside the cornfield.The cornfield from the second example is pictured below. Grasshoppers with indices $$$1$$$ (coordinates $$$(4, 4)$$$), $$$3$$$ (coordinates $$$(8, 1)$$$) and $$$4$$$ (coordinates $$$(6, 1)$$$) are inside the cornfield.
Java 8
standard input
[ "geometry" ]
9c84eb518c273942650c7262e5d8b45f
The first line contains two integers $$$n$$$ and $$$d$$$ ($$$1 \le d &lt; n \le 100$$$). The second line contains a single integer $$$m$$$ ($$$1 \le m \le 100$$$) — the number of grasshoppers. The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le n$$$) — position of the $$$i$$$-th grasshopper.
1,100
Print $$$m$$$ lines. The $$$i$$$-th line should contain "YES" if the position of the $$$i$$$-th grasshopper lies inside or on the border of the cornfield. Otherwise the $$$i$$$-th line should contain "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
bb10c50799f4371bdd3e8dbff368b2ee
train_001.jsonl
1537707900
Vasya owns a cornfield which can be defined with two integers $$$n$$$ and $$$d$$$. The cornfield can be represented as rectangle with vertices having Cartesian coordinates $$$(0, d), (d, 0), (n, n - d)$$$ and $$$(n - d, n)$$$. An example of a cornfield with $$$n = 7$$$ and $$$d = 2$$$. Vasya also knows that there are $$$m$$$ grasshoppers near the field (maybe even inside it). The $$$i$$$-th grasshopper is at the point $$$(x_i, y_i)$$$. Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside.Help Vasya! For each grasshopper determine if it is inside the field (including the border).
256 megabytes
import java.util.Scanner; /** * * @author CHAGO */ public class B { public static void main(String[] args) { Scanner sc = new Scanner (System.in); int n= sc.nextInt(); int d=sc.nextInt(); int m=sc.nextInt(); for (int i = 0; i < m; i++) { int a=sc.nextInt(); int b=sc.nextInt(); if (b+a>=d&&b<=2*n-a-d&&b>=a-d&&b<=a+d) { System.out.println("YES"); }else{ System.out.println("NO"); } } } }
Java
["7 2\n4\n2 4\n4 1\n6 3\n4 5", "8 7\n4\n4 4\n2 8\n8 1\n6 1"]
1 second
["YES\nNO\nNO\nYES", "YES\nNO\nYES\nYES"]
NoteThe cornfield from the first example is pictured above. Grasshoppers with indices $$$1$$$ (coordinates $$$(2, 4)$$$) and $$$4$$$ (coordinates $$$(4, 5)$$$) are inside the cornfield.The cornfield from the second example is pictured below. Grasshoppers with indices $$$1$$$ (coordinates $$$(4, 4)$$$), $$$3$$$ (coordinates $$$(8, 1)$$$) and $$$4$$$ (coordinates $$$(6, 1)$$$) are inside the cornfield.
Java 8
standard input
[ "geometry" ]
9c84eb518c273942650c7262e5d8b45f
The first line contains two integers $$$n$$$ and $$$d$$$ ($$$1 \le d &lt; n \le 100$$$). The second line contains a single integer $$$m$$$ ($$$1 \le m \le 100$$$) — the number of grasshoppers. The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le n$$$) — position of the $$$i$$$-th grasshopper.
1,100
Print $$$m$$$ lines. The $$$i$$$-th line should contain "YES" if the position of the $$$i$$$-th grasshopper lies inside or on the border of the cornfield. Otherwise the $$$i$$$-th line should contain "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
348bea5220eb93c26078e49050b79304
train_001.jsonl
1550917200
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review  — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer.Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes.The gourmet tasted a set of $$$n$$$ dishes on the first day and a set of $$$m$$$ dishes on the second day. He made a table $$$a$$$ of size $$$n \times m$$$, in which he described his impressions. If, according to the expert, dish $$$i$$$ from the first set was better than dish $$$j$$$ from the second set, then $$$a_{ij}$$$ is equal to "&gt;", in the opposite case $$$a_{ij}$$$ is equal to "&lt;". Dishes also may be equally good, in this case $$$a_{ij}$$$ is "=".Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if $$$a_{ij}$$$ is "&lt;", then the number assigned to dish $$$i$$$ from the first set should be less than the number of dish $$$j$$$ from the second set, if $$$a_{ij}$$$ is "&gt;", then it should be greater, and finally if $$$a_{ij}$$$ is "=", then the numbers should be the same.Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible.
256 megabytes
import java.lang.reflect.Array; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; public class D541 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(), m = scanner.nextInt(); List<List<Integer>> lt = new ArrayList<>(); List<List<Integer>> eq = new ArrayList<>(); List<List<Integer>> gt = new ArrayList<>(); for (int i = 0; i < m; i++){ lt.add(new ArrayList<>()); gt.add(new ArrayList<>()); eq.add(new ArrayList<>()); } scanner.nextLine(); for (int i = 0; i < n;i++){ String s = scanner.nextLine(); for (int j = 0; j < m; j++){ char c = s.charAt(j); if ( c == '<'){ lt.get(j).add(i); }else if (c == '>'){ gt.get(j).add(i); }else eq.get(j).add(i); } } PriorityQueue<Pair> pairs = new PriorityQueue<>( (o1, o2) -> o1.size == o2.size ? o1.eq - o2.eq : o1.size - o2.size); for (int i = 0; i < lt.size(); i++) { pairs.add(new Pair(lt.get(i).size(), eq.get(i).size(), i)); } Integer[] first = new Integer[n]; Integer[] second = new Integer[m]; int value = 0; int prevIdx = -1; while (pairs.size() > 0){ Pair poll = pairs.poll(); if (prevIdx != -1 && poll.size == lt.get(prevIdx).size()){ boolean flag = true; for (Integer integer : lt.get(poll.idx)) { if (!lt.get(prevIdx).contains(integer)) flag =false; } if (eq.get(prevIdx).size() > 0){ if (eq.get(poll.idx).size() != eq.get(prevIdx).size()){ System.out.println("No"); return; } for (Integer integer : eq.get(poll.idx)) { if (!eq.get(prevIdx).contains(integer)) flag =false; } } if (flag){ if (eq.get(prevIdx).size() == 0 && eq.get(poll.idx).size() > 0){ value += 1; for (Integer integer : eq.get(poll.idx)) { first[integer] = value; } } second[poll.idx] = value; prevIdx = poll.idx; continue; } System.out.println("No"); return; } value +=1; boolean flag = false; for (Integer integer : lt.get(poll.idx)) { if (first[integer] == null) { first[integer] = value; flag = true; } } if (flag) value +=1; second[poll.idx] = value; for (Integer integer : eq.get(poll.idx)) { if (first[integer] != null){ System.out.println("No"); return; } first[integer] = value; } for (Integer integer : gt.get(poll.idx)) { if (first[integer] != null){ System.out.println("No"); return; } } prevIdx = poll.idx; } value += 1; for (int i = 0; i < n; i++){ if (first[i] == null) first[i] = value; } System.out.println("Yes"); String firsrAns = Stream.of(first) .map(Objects::toString) .collect(Collectors.joining(" ")); String secondAns = Stream.of(second) .map(Objects::toString) .collect(Collectors.joining(" ")); System.out.println(firsrAns); System.out.println(secondAns); } } class Pair{ int size; int idx; int eq; public Pair(int size, int eq, int idx) { this.size = size; this.idx = idx; this.eq = eq; } }
Java
["3 4\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;", "3 3\n&gt;&gt;&gt;\n&lt;&lt;&lt;\n&gt;&gt;&gt;", "3 2\n==\n=&lt;\n=="]
2 seconds
["Yes\n2 2 2 \n1 1 1 1", "Yes\n3 1 3 \n2 2 2", "No"]
NoteIn the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be $$$2$$$, for all dishes of the first day.In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
Java 8
standard input
[ "dp", "greedy", "graphs", "dsu", "dfs and similar" ]
016bf7989ba58fdc3894a4cf3e0ac302
The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 1000$$$) — the number of dishes in both days. Each of the next $$$n$$$ lines contains a string of $$$m$$$ symbols. The $$$j$$$-th symbol on $$$i$$$-th line is $$$a_{ij}$$$. All strings consist only of "&lt;", "&gt;" and "=".
2,000
The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print $$$n$$$ integers — evaluations of dishes from the first set, and on the third line print $$$m$$$ integers — evaluations of dishes from the second set.
standard output
PASSED
029814a15a0cf9daf964aa57a8580977
train_001.jsonl
1550917200
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review  — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer.Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes.The gourmet tasted a set of $$$n$$$ dishes on the first day and a set of $$$m$$$ dishes on the second day. He made a table $$$a$$$ of size $$$n \times m$$$, in which he described his impressions. If, according to the expert, dish $$$i$$$ from the first set was better than dish $$$j$$$ from the second set, then $$$a_{ij}$$$ is equal to "&gt;", in the opposite case $$$a_{ij}$$$ is equal to "&lt;". Dishes also may be equally good, in this case $$$a_{ij}$$$ is "=".Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if $$$a_{ij}$$$ is "&lt;", then the number assigned to dish $$$i$$$ from the first set should be less than the number of dish $$$j$$$ from the second set, if $$$a_{ij}$$$ is "&gt;", then it should be greater, and finally if $$$a_{ij}$$$ is "=", then the numbers should be the same.Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.FileInputStream; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); DGourmetChoice solver = new DGourmetChoice(); solver.solve(1, in, out); out.close(); } static class DGourmetChoice { private int n; private int m; private ArrayList<Integer>[] graph; private char[][] arr; private int WHITE = 0; private int GRAY = 1; private int BLACK = 2; private int[] colour; private int[] val; private boolean[] vis; public void solve(int testNumber, InputReader in, PrintWriter out) { n = in.nextInt(); m = in.nextInt(); arr = new char[n][m]; DGourmetChoice.DisjointSet ds = new DGourmetChoice.DisjointSet(n + m); for (int i = 0; i < n; i++) { String str = in.nextLine(); for (int j = 0; j < m; j++) { arr[i][j] = str.charAt(j); if (arr[i][j] == '=') ds.union(i, j + n); } } graph = new ArrayList[n + m]; for (int i = 0; i < n + m; i++) graph[i] = new ArrayList<>(); int par_i, par_j; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { par_i = ds.root(i); par_j = ds.root(j + n); if (arr[i][j] == '<') graph[par_j].add(par_i); else if (arr[i][j] == '>') graph[par_i].add(par_j); else continue; } } colour = new int[n + m]; for (int i = 0; i < n + m; i++) { if (colour[ds.root(i)] == WHITE && isCyclic(ds.root(i))) { out.println("No"); return; } } val = new int[n + m]; vis = new boolean[n + m]; for (int i = 0; i < n + m; i++) { if (!vis[ds.root(i)]) dfs(ds.root(i)); } out.println("Yes"); for (int i = 0; i < n; i++) { out.printf("%d ", val[ds.root(i)]); } out.println(); for (int j = 0; j < m; j++) { out.printf("%d ", val[ds.root(j + n)]); } } private boolean isCyclic(int start) { colour[start] = GRAY; for (int x : graph[start]) { if (colour[x] == GRAY) return true; if (colour[x] == WHITE && isCyclic(x)) return true; } colour[start] = BLACK; return false; } private int dfs(int start) { int max = 0; vis[start] = true; for (int x : graph[start]) { if (vis[x]) max = Math.max(max, val[x]); else max = Math.max(max, dfs(x)); } val[start] = max + 1; return val[start]; } static class DisjointSet { private int[] parent; private int[] setSize; private int numOfSets; private DisjointSet(int n) { parent = new int[n]; setSize = new int[n]; for (int i = 0; i < n; i++) { parent[i] = i; setSize[i] = 1; } numOfSets = n; } private int root(int x) { if (x == parent[x]) return x; return parent[x] = root(parent[x]); } private boolean union(int n1, int n2) { return _union(root(n1), root(n2)); } private boolean _union(int n1, int n2) { if (n1 == n2) return false; if (setSize[n1] > setSize[n2]) { parent[n2] = parent[n1]; setSize[n1] += setSize[n2]; } else { parent[n1] = parent[n2]; setSize[n2] += setSize[n1]; } numOfSets--; return true; } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public InputReader(FileInputStream file) { this.stream = file; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res = (res << 3) + (res << 1) + c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } 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(); } 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
["3 4\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;", "3 3\n&gt;&gt;&gt;\n&lt;&lt;&lt;\n&gt;&gt;&gt;", "3 2\n==\n=&lt;\n=="]
2 seconds
["Yes\n2 2 2 \n1 1 1 1", "Yes\n3 1 3 \n2 2 2", "No"]
NoteIn the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be $$$2$$$, for all dishes of the first day.In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
Java 8
standard input
[ "dp", "greedy", "graphs", "dsu", "dfs and similar" ]
016bf7989ba58fdc3894a4cf3e0ac302
The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 1000$$$) — the number of dishes in both days. Each of the next $$$n$$$ lines contains a string of $$$m$$$ symbols. The $$$j$$$-th symbol on $$$i$$$-th line is $$$a_{ij}$$$. All strings consist only of "&lt;", "&gt;" and "=".
2,000
The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print $$$n$$$ integers — evaluations of dishes from the first set, and on the third line print $$$m$$$ integers — evaluations of dishes from the second set.
standard output
PASSED
370b08de50be964147af6c1b801c5dd3
train_001.jsonl
1550917200
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review  — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer.Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes.The gourmet tasted a set of $$$n$$$ dishes on the first day and a set of $$$m$$$ dishes on the second day. He made a table $$$a$$$ of size $$$n \times m$$$, in which he described his impressions. If, according to the expert, dish $$$i$$$ from the first set was better than dish $$$j$$$ from the second set, then $$$a_{ij}$$$ is equal to "&gt;", in the opposite case $$$a_{ij}$$$ is equal to "&lt;". Dishes also may be equally good, in this case $$$a_{ij}$$$ is "=".Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if $$$a_{ij}$$$ is "&lt;", then the number assigned to dish $$$i$$$ from the first set should be less than the number of dish $$$j$$$ from the second set, if $$$a_{ij}$$$ is "&gt;", then it should be greater, and finally if $$$a_{ij}$$$ is "=", then the numbers should be the same.Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.*; import java.util.*; import java.util.LinkedList; import java.math.*; import java.lang.*; import java.util.PriorityQueue; import static java.lang.Math.*; @SuppressWarnings("unchecked") public class Solution 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 long min(long a,long b) { if(a>b) { return b; } return a; } public static int min(int a,int b) { if(a>b) { return b; } return a; } public static long max(long a,long b) { if(a>b) { return a; } return b; } public static int max(int a,int b) { if(a>b) { return a; } return b; } static class pair { long x; long y; pair(long x,long y) { this.x = x; this.y = y; } } public static int gcd(int a,int b) { if(a==0) return b; if(b==0) return a; while((a%=b)!=0&&(b%=a)!=0); return a^b; } public static long mod(long x) { if(x>0) { return x; } return -x; } static int mod = (int)1e9+7; public static long[][] mult(long[][] a,long[][] b) { int n = a.length; int m = b[0].length; long[][] res = new long[n][m]; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { for(int k=0;k<a[0].length;k++) { res[i][j] = (res[i][j]+a[i][k]*b[k][j])%mod; } } } return res; } static int[] height; static int[] parent; public static int parent(int u) { if(u==parent[u]) { return u; } return parent[u] = parent(parent[u]); } public static void join(int u,int v) { int pu = parent(u); int pv = parent(v); if(pu==pv){ return; } if(height[pu]>height[pv]) { parent[pv] = pu; } else if(height[pu]<height[pv]) { parent[pu] = pv; } else { parent[pu] = pv; height[pu]++; } } public static boolean cycle1(int u,boolean[] visit,boolean[] stck) { visit[u] = true; stck[u] = true; for(Integer v:list[u]) { if(visit[v]&&stck[v]) { return true; } if(!visit[v]) { if(cycle1(v,visit,stck)){ return true; } } } stck[u] = false; return false; } public static boolean cycle(boolean[] visit,boolean[] stck) { for(int i=0;i<visit.length;i++) { if(!visit[i]&&cycle1(i,visit,stck)) { return true; } } return false; } public static void dfs(int u,boolean[] visit,int[] ans) { visit[u] = true; int max = 0; for(Integer v:list[u]) { if(!visit[v]) { dfs(v,visit,ans); } max = max(max,ans[v]); } ans[u] = max+1; } static ArrayList<Integer>[] list; public static int random(int min,int max) { return min+(int)((max-min)*Math.random()); } public static void main(String args[]) throws Exception { new Thread(null, new Solution(),"Main",1<<26).start(); } public void run() { InputReader sc = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int t1 = 1; while(t1-->0) { int n = sc.nextInt(); int m = sc.nextInt(); char[][] c = new char[n][]; for(int i=0;i<n;i++) { c[i] = sc.readString().toCharArray(); } height = new int[n+m]; parent = new int[n+m]; for(int i=0;i<n+m;i++) { parent[i] = i; } for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(c[i][j]=='=') { join(i,n+j); } } } int[] hash = new int[n+m]; int ind = 0; for(int i=0;i<n+m;i++) { if(parent[i]==i) { hash[i] = ind++; } } list = new ArrayList[ind]; for(int i=0;i<ind;i++) { list[i] = new ArrayList<>(); } for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { int pi = parent(i); int pj = parent(n+j); if(c[i][j]=='>') { list[hash[pi]].add(hash[pj]); } else if(c[i][j]=='<') { list[hash[pj]].add(hash[pi]); } } } boolean[] visit = new boolean[ind]; boolean[] stack1 = new boolean[ind]; if(cycle(visit,stack1)) { out.println("NO"); } else { out.println("YES"); Arrays.fill(visit,false); int[] ans = new int[ind]; for(int i=0;i<ind;i++) { if(!visit[i]) { dfs(i,visit,ans); } } for(int i=0;i<n;i++) { out.print(ans[hash[parent(i)]]+" "); } out.println(); for(int j=0;j<m;j++) { out.print(ans[hash[parent(n+j)]]+" "); } out.println(); } } out.close(); } }
Java
["3 4\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;", "3 3\n&gt;&gt;&gt;\n&lt;&lt;&lt;\n&gt;&gt;&gt;", "3 2\n==\n=&lt;\n=="]
2 seconds
["Yes\n2 2 2 \n1 1 1 1", "Yes\n3 1 3 \n2 2 2", "No"]
NoteIn the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be $$$2$$$, for all dishes of the first day.In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
Java 8
standard input
[ "dp", "greedy", "graphs", "dsu", "dfs and similar" ]
016bf7989ba58fdc3894a4cf3e0ac302
The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 1000$$$) — the number of dishes in both days. Each of the next $$$n$$$ lines contains a string of $$$m$$$ symbols. The $$$j$$$-th symbol on $$$i$$$-th line is $$$a_{ij}$$$. All strings consist only of "&lt;", "&gt;" and "=".
2,000
The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print $$$n$$$ integers — evaluations of dishes from the first set, and on the third line print $$$m$$$ integers — evaluations of dishes from the second set.
standard output
PASSED
0e731db80413e9618ddadbbe85acec14
train_001.jsonl
1550917200
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review  — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer.Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes.The gourmet tasted a set of $$$n$$$ dishes on the first day and a set of $$$m$$$ dishes on the second day. He made a table $$$a$$$ of size $$$n \times m$$$, in which he described his impressions. If, according to the expert, dish $$$i$$$ from the first set was better than dish $$$j$$$ from the second set, then $$$a_{ij}$$$ is equal to "&gt;", in the opposite case $$$a_{ij}$$$ is equal to "&lt;". Dishes also may be equally good, in this case $$$a_{ij}$$$ is "=".Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if $$$a_{ij}$$$ is "&lt;", then the number assigned to dish $$$i$$$ from the first set should be less than the number of dish $$$j$$$ from the second set, if $$$a_{ij}$$$ is "&gt;", then it should be greater, and finally if $$$a_{ij}$$$ is "=", then the numbers should be the same.Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible.
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 yizheng */ 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); D solver = new D(); solver.solve(1, in, out); out.close(); } static class D { public static int[] topologicalSort(Graph graph) { int count = graph.vertexCount(); int[] order = new int[count]; int[] degree = new int[count]; int[] score = new int[count]; int size = 0; for (int i = 0; i < graph.edgeCount(); i++) { if (!graph.isRemoved(i)) { degree[graph.destination(i)]++; } } for (int i = 0; i < count; i++) { if (degree[i] == 0) { order[size++] = i; score[i] = 1; } } for (int i = 0; i < size; i++) { int current = order[i]; int curScore = score[order[i]]; for (int j = graph.firstOutbound(current); j != -1; j = graph.nextOutbound(j)) { int next = graph.destination(j); if (--degree[next] == 0) { score[next] = curScore + 1; order[size++] = next; } } } if (size != count) { return null; } return score; } public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); int m = in.readInt(); char[][] table = in.readTable(n, m); RecursiveIndependentSetSystem iss = new RecursiveIndependentSetSystem(n + m); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (table[i][j] == '=') { if (iss.get(i) != iss.get(n + j)) { iss.join(i, n + j); } } else { if (iss.get(i) == iss.get(n + j)) { out.print("No"); return; } } } } Graph graph = new Graph(n + m); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (table[i][j] == '<') { graph.addEdge(iss.get(i), iss.get(n + j), 0, 0, -1); } else if (table[i][j] == '>') { graph.addEdge(iss.get(n + j), iss.get(i), 0, 0, -1); } } } int[] res = topologicalSort(graph); if (res == null) { out.print("No"); return; } out.printLine("Yes"); for (int i = 0; i < n; i++) { out.print(res[iss.get(i)]); out.print(" "); } out.printLine(); for (int i = 0; i < m; i++) { out.print(res[iss.get(n + i)]); out.print(" "); } out.printLine(); } } static class RecursiveIndependentSetSystem implements IndependentSetSystem { private final int[] color; private final int[] rank; private int setCount; private IndependentSetSystem.Listener listener; public RecursiveIndependentSetSystem(int size) { color = new int[size]; rank = new int[size]; for (int i = 0; i < size; i++) { color[i] = i; } setCount = size; } public RecursiveIndependentSetSystem(RecursiveIndependentSetSystem other) { color = other.color.clone(); rank = other.rank.clone(); setCount = other.setCount; } public boolean join(int first, int second) { first = get(first); second = get(second); if (first == second) { return false; } if (rank[first] < rank[second]) { int temp = first; first = second; second = temp; } else if (rank[first] == rank[second]) { rank[first]++; } setCount--; color[second] = first; if (listener != null) { listener.joined(second, first); } return true; } public int get(int index) { int start = index; while (color[index] != index) { index = color[index]; } while (start != index) { int next = color[start]; color[start] = index; start = next; } return index; } } 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 char[] readCharArray(int size) { char[] array = new char[size]; for (int i = 0; i < size; i++) { array[i] = readCharacter(); } return array; } public char[][] readTable(int rowCount, int columnCount) { char[][] table = new char[rowCount][]; for (int i = 0; i < rowCount; i++) { table[i] = this.readCharArray(columnCount); } return table; } public int 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 char readCharacter() { int c = read(); while (isSpaceChar(c)) { c = read(); } return (char) c; } 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() { writer.println(); } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void print(int i) { writer.print(i); } } static interface Edge { } static class Graph { public static final int REMOVED_BIT = 0; protected int vertexCount; protected int edgeCount; private int[] firstOutbound; private int[] firstInbound; private Edge[] edges; private int[] nextInbound; private int[] nextOutbound; private int[] from; private int[] to; private long[] weight; public long[] capacity; private int[] reverseEdge; private int[] flags; public Graph(int vertexCount) { this(vertexCount, vertexCount); } public Graph(int vertexCount, int edgeCapacity) { this.vertexCount = vertexCount; firstOutbound = new int[vertexCount]; Arrays.fill(firstOutbound, -1); from = new int[edgeCapacity]; to = new int[edgeCapacity]; nextOutbound = new int[edgeCapacity]; flags = new int[edgeCapacity]; } public int addEdge(int fromID, int toID, long weight, long capacity, int reverseEdge) { ensureEdgeCapacity(edgeCount + 1); if (firstOutbound[fromID] != -1) { nextOutbound[edgeCount] = firstOutbound[fromID]; } else { nextOutbound[edgeCount] = -1; } firstOutbound[fromID] = edgeCount; if (firstInbound != null) { if (firstInbound[toID] != -1) { nextInbound[edgeCount] = firstInbound[toID]; } else { nextInbound[edgeCount] = -1; } firstInbound[toID] = edgeCount; } this.from[edgeCount] = fromID; this.to[edgeCount] = toID; if (capacity != 0) { if (this.capacity == null) { this.capacity = new long[from.length]; } this.capacity[edgeCount] = capacity; } if (weight != 0) { if (this.weight == null) { this.weight = new long[from.length]; } this.weight[edgeCount] = weight; } if (reverseEdge != -1) { if (this.reverseEdge == null) { this.reverseEdge = new int[from.length]; Arrays.fill(this.reverseEdge, 0, edgeCount, -1); } this.reverseEdge[edgeCount] = reverseEdge; } if (edges != null) { edges[edgeCount] = createEdge(edgeCount); } return edgeCount++; } protected final GraphEdge createEdge(int id) { return new GraphEdge(id); } public final int vertexCount() { return vertexCount; } public final int edgeCount() { return edgeCount; } public final int firstOutbound(int vertex) { int id = firstOutbound[vertex]; while (id != -1 && isRemoved(id)) { id = nextOutbound[id]; } return id; } public final int nextOutbound(int id) { id = nextOutbound[id]; while (id != -1 && isRemoved(id)) { id = nextOutbound[id]; } return id; } public final int destination(int id) { return to[id]; } public final boolean flag(int id, int bit) { return (flags[id] >> bit & 1) != 0; } public final boolean isRemoved(int id) { return flag(id, REMOVED_BIT); } protected void ensureEdgeCapacity(int size) { if (from.length < size) { int newSize = Math.max(size, 2 * from.length); if (edges != null) { edges = resize(edges, newSize); } from = resize(from, newSize); to = resize(to, newSize); nextOutbound = resize(nextOutbound, newSize); if (nextInbound != null) { nextInbound = resize(nextInbound, newSize); } if (weight != null) { weight = resize(weight, newSize); } if (capacity != null) { capacity = resize(capacity, newSize); } if (reverseEdge != null) { reverseEdge = resize(reverseEdge, newSize); } flags = resize(flags, newSize); } } protected final int[] resize(int[] array, int size) { int[] newArray = new int[size]; System.arraycopy(array, 0, newArray, 0, array.length); return newArray; } private long[] resize(long[] array, int size) { long[] newArray = new long[size]; System.arraycopy(array, 0, newArray, 0, array.length); return newArray; } private Edge[] resize(Edge[] array, int size) { Edge[] newArray = new Edge[size]; System.arraycopy(array, 0, newArray, 0, array.length); return newArray; } protected class GraphEdge implements Edge { protected int id; protected GraphEdge(int id) { this.id = id; } } } static interface IndependentSetSystem { public static interface Listener { public void joined(int joinedRoot, int root); } } }
Java
["3 4\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;", "3 3\n&gt;&gt;&gt;\n&lt;&lt;&lt;\n&gt;&gt;&gt;", "3 2\n==\n=&lt;\n=="]
2 seconds
["Yes\n2 2 2 \n1 1 1 1", "Yes\n3 1 3 \n2 2 2", "No"]
NoteIn the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be $$$2$$$, for all dishes of the first day.In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
Java 8
standard input
[ "dp", "greedy", "graphs", "dsu", "dfs and similar" ]
016bf7989ba58fdc3894a4cf3e0ac302
The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 1000$$$) — the number of dishes in both days. Each of the next $$$n$$$ lines contains a string of $$$m$$$ symbols. The $$$j$$$-th symbol on $$$i$$$-th line is $$$a_{ij}$$$. All strings consist only of "&lt;", "&gt;" and "=".
2,000
The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print $$$n$$$ integers — evaluations of dishes from the first set, and on the third line print $$$m$$$ integers — evaluations of dishes from the second set.
standard output
PASSED
a85ad600a36dd2fd8ff2178afabe7aec
train_001.jsonl
1550917200
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review  — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer.Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes.The gourmet tasted a set of $$$n$$$ dishes on the first day and a set of $$$m$$$ dishes on the second day. He made a table $$$a$$$ of size $$$n \times m$$$, in which he described his impressions. If, according to the expert, dish $$$i$$$ from the first set was better than dish $$$j$$$ from the second set, then $$$a_{ij}$$$ is equal to "&gt;", in the opposite case $$$a_{ij}$$$ is equal to "&lt;". Dishes also may be equally good, in this case $$$a_{ij}$$$ is "=".Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if $$$a_{ij}$$$ is "&lt;", then the number assigned to dish $$$i$$$ from the first set should be less than the number of dish $$$j$$$ from the second set, if $$$a_{ij}$$$ is "&gt;", then it should be greater, and finally if $$$a_{ij}$$$ is "=", then the numbers should be the same.Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible.
256 megabytes
import java.util.*; import java.lang.*; public class draw{ public static void main(String[] args) { solveGourmet(); } public static void solveGourmet(){ Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int m = scan.nextInt(); scan.nextLine(); String[] strs = new String[n]; for(int i=0;i<n;i++){ strs[i] = scan.nextLine(); } int[] parent = new int[n+m]; for(int i=0;i<m+n;i++){ parent[i] = i; } int group_size = m+n; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ char c = strs[i].charAt(j); if(c=='='){ int parent_i = findParent(parent, i); int parent_j = findParent(parent, n+j); if(parent_i!=parent_j){ parent[parent_i] = parent[parent_j]; group_size--; } } } } Map<Integer,Set<Integer>> map = new HashMap<>(); int[] indegree = new int[n+m]; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ char c=strs[i].charAt(j); if(c=='='){ continue; } int parent_i = findParent(parent, i); int parent_j = findParent(parent, n+j); if(parent_i==parent_j){ System.out.println("NO"); return; } if(c=='>'){ if(map.containsKey(parent_i) && map.get(parent_i).contains(parent_j)){ System.out.println("NO"); return; } if(map.containsKey(parent_j)==false){ map.put(parent_j, new HashSet<>()); }else if(map.get(parent_j).contains(parent_i)){ continue; } map.get(parent_j).add(parent_i); indegree[parent_i]++; }else if(c=='<'){ if(map.containsKey(parent_j) && map.get(parent_j).contains(parent_i)){ System.out.println("NO"); return; } if(map.containsKey(parent_i)==false){ map.put(parent_i, new HashSet<>()); }else if(map.get(parent_i).contains(parent_j)){ continue; } map.get(parent_i).add(parent_j); indegree[parent_j]++; } } } Map<Integer, Integer> affine = new HashMap<>(); Queue<Integer> queue = new LinkedList<>(); boolean[] visited = new boolean[m+n]; for(int i=0;i<m+n;i++){ int parent_id = findParent(parent, i); //System.out.println("prent " + parent_id +" 's indegree is :" + indegree[parent_id]); if(indegree[parent_id]==0 && visited[parent_id]==false){ visited[parent_id] = true; queue.offer(parent_id); } } int count = 0; while(queue.size()!=0){ int size = queue.size(); //System.out.println("size: "+size); count++; while(size--!=0){ int cur_id = queue.poll(); //System.out.println(cur_id); affine.put(cur_id, count); if(map.containsKey(cur_id)==false){ continue; } for(int ele: map.get(cur_id)){ int parent_ele = findParent(parent, ele); indegree[parent_ele]--; if(indegree[parent_ele] == 0 && visited[parent_ele]==false){ visited[parent_ele] = true; queue.offer(parent_ele); } } } } if(affine.size()!=group_size){ System.out.println("NO"); return; } int[] res = new int[m+n]; //System.out.println("check"); for(int i=0;i<m+n;i++){ int parent_id = findParent(parent, i); //System.out.println(parent_id); int val = affine.get(parent_id); res[i] = val; } System.out.println("YES"); for(int i=0;i<n;i++){ System.out.print(res[i]+" "); } System.out.println(); for(int i=0;i<m;i++){ System.out.print(res[n+i]+" "); } System.out.println(); } public static int findParent(int[] parent, int index){ while(index!=parent[index]){ parent[index] = parent[parent[index]]; index = parent[index]; } return index; } public static void solveCycle(){ Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int[] array = new int[n]; for(int i=0;i<n;i++){ array[i] = scan.nextInt(); } Arrays.sort(array); List<Integer> list = new ArrayList<>(); for(int i=0;i<array.length;i+=2){ list.add(array[i]); } int i=(array.length%2==0)?array.length-1:array.length-2; for(;i>=1;i-=2){ list.add(array[i]); } for(int ele: list){ System.out.print(ele+" "); } } public static void solveDraw(){ Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int[] arrayA = new int[n+1]; int[] arrayB = new int[n+1]; for(int i=0;i<n;i++){ arrayA[i+1] = scan.nextInt(); arrayB[i+1] = scan.nextInt(); } int count = 0; for(int i=0;i<arrayA.length-1;i++){ int min = Math.max(arrayA[i], arrayB[i]); int max = Math.min(arrayA[i+1], arrayB[i+1]); if(max<min){ continue; } int len = max-min+1; if(arrayA[i]==arrayB[i]){ len--; } count += len; } System.out.println(count+1); } }
Java
["3 4\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;", "3 3\n&gt;&gt;&gt;\n&lt;&lt;&lt;\n&gt;&gt;&gt;", "3 2\n==\n=&lt;\n=="]
2 seconds
["Yes\n2 2 2 \n1 1 1 1", "Yes\n3 1 3 \n2 2 2", "No"]
NoteIn the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be $$$2$$$, for all dishes of the first day.In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
Java 8
standard input
[ "dp", "greedy", "graphs", "dsu", "dfs and similar" ]
016bf7989ba58fdc3894a4cf3e0ac302
The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 1000$$$) — the number of dishes in both days. Each of the next $$$n$$$ lines contains a string of $$$m$$$ symbols. The $$$j$$$-th symbol on $$$i$$$-th line is $$$a_{ij}$$$. All strings consist only of "&lt;", "&gt;" and "=".
2,000
The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print $$$n$$$ integers — evaluations of dishes from the first set, and on the third line print $$$m$$$ integers — evaluations of dishes from the second set.
standard output
PASSED
ecbf239daf3317e645147560b3b63676
train_001.jsonl
1550917200
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review  — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer.Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes.The gourmet tasted a set of $$$n$$$ dishes on the first day and a set of $$$m$$$ dishes on the second day. He made a table $$$a$$$ of size $$$n \times m$$$, in which he described his impressions. If, according to the expert, dish $$$i$$$ from the first set was better than dish $$$j$$$ from the second set, then $$$a_{ij}$$$ is equal to "&gt;", in the opposite case $$$a_{ij}$$$ is equal to "&lt;". Dishes also may be equally good, in this case $$$a_{ij}$$$ is "=".Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if $$$a_{ij}$$$ is "&lt;", then the number assigned to dish $$$i$$$ from the first set should be less than the number of dish $$$j$$$ from the second set, if $$$a_{ij}$$$ is "&gt;", then it should be greater, and finally if $$$a_{ij}$$$ is "=", then the numbers should be the same.Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible.
256 megabytes
import java.io.*; import java.util.*; import java.util.function.Function; public class MainD { static int N, M; static char[][] C; public static void main(String[] args) { FastScanner sc = new FastScanner(System.in); N = sc.nextInt(); M = sc.nextInt(); C = new char[N][]; for (int i = 0; i < N; i++) { C[i] = sc.next().toCharArray(); } boolean ans = solve(); System.out.println(ans ? "Yes" : "No"); if( ans ) { StringJoiner j = new StringJoiner(" "); for (int n : NC) { j.add(String.valueOf(n)); } System.out.println( j.toString() ); j = new StringJoiner(" "); for (int m : MC) { j.add(String.valueOf(m)); } System.out.println( j.toString() ); } } static int[] NC; static int[] MC; static boolean solve() { UnionFind uf = new UnionFind(N+M); for (int n = 0; n < N; n++) { for (int m = 0; m < M; m++) { if( C[n][m] == '=' ) { uf.unite(n, N+m); } } } List<int[]> E = new ArrayList<>(); for (int n = 0; n < N; n++) { for (int m = 0; m < M; m++) { char c = C[n][m]; if( c == '>' ) { if( uf.isSame(N+m, n) ) { return false; } E.add( new int[]{uf.root(N+m), uf.root(n)} ); } else if( c == '<' ) { if( uf.isSame(n, N+m) ) { return false; } E.add( new int[]{uf.root(n), uf.root(N+m)} ); } } } int[][] G = adjD(N+M, E); int[][] topo = khan(N+M, G); if( topo == null ) return false; // debug(topo); // 多分分けないほうが楽だがもう動いたし... NC = new int[N]; MC = new int[M]; for (int[] vr : topo) { int v = vr[0]; int rank = vr[1]; if( uf.isRoot(v) ) { if( vr[0] < N ) { NC[vr[0]] = rank; } else { MC[vr[0]-N] = rank; } } } for (int i = 0; i < N+M; i++) { if( !uf.isRoot(i) ) { int r = uf.root(i); (i < N ? NC:MC)[i < N ? i : i-N] = (r < N ? NC:MC)[r < N ? r : r-N]; } } return true; } static int[][] khan(int V, int[][] G) { int[] deg = new int[V]; for (int[] tos : G) { for (int to : tos) { deg[to]++; } } int[][] q = new int[V][2]; int a = 0, b = 0; for (int v = 0; v < V; v++) { if( deg[v] == 0 ) { q[b][0] = v; q[b][1] = 1; b++; } } int[][] ret = new int[V][2]; int idx = 0; while( a != b ) { int[] vr = q[a++]; ret[idx++] = vr; int v = vr[0]; int r = vr[1]; for (int to : G[v]) { deg[to]--; if( deg[to] == 0 ) { q[b][0] = to; q[b][1] = r+1; b++; } } } for (int v = 0; v < V; v++) { if( deg[v] != 0 ) return null; } return ret; } static int[][] adjD(int n, List<int[]> es) { int[][] adj = new int[n][]; int[] cnt = new int[n]; for (int[] e : es) { cnt[e[0]]++; } for (int i = 0; i < n; i++) { adj[i] = new int[cnt[i]]; } for (int[] e : es) { adj[e[0]][--cnt[e[0]]] = e[1]; } return adj; } static boolean useThisEdge(int[] e, UnionFind uf) { return uf.isRoot(e[0]) && uf.isRoot(e[1]); } static class UnionFind { private final int[] parent; private final int[] rank; public UnionFind(int n) { parent = new int[n]; rank = new int[n]; for (int i = 0; i < n; i++) { parent[i] = i; rank[i] = 0; } } public int root(int i) { if( parent[i] == i ) { return i; } else { return parent[i] = root(parent[i]); } } public boolean isRoot(int i) { return root(i) == i; } public void unite(int i, int j) { int ri = root(i); int rj = root(j); if( ri == rj ) return; if( rank[ri] < rank[rj] ) { parent[ri] = rj; } else { parent[rj] = ri; if( rank[ri] == rank[rj] ) { rank[ri]++; } } } public boolean isSame(int a, int b) { return root(a) == root(b); } } @SuppressWarnings("unused") static class FastScanner { private BufferedReader reader; private StringTokenizer tokenizer; FastScanner(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); tokenizer = null; } String next() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } String nextLine() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken("\n"); } long nextLong() { return Long.parseLong(next()); } int nextInt() { return Integer.parseInt(next()); } int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArray(int n, int delta) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt() + delta; return a; } long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } } static <A> void writeLines(A[] as, Function<A, String> f) { PrintWriter pw = new PrintWriter(System.out); for (A a : as) { pw.println(f.apply(a)); } pw.flush(); } static void writeLines(int[] as) { PrintWriter pw = new PrintWriter(System.out); for (int a : as) pw.println(a); pw.flush(); } static void writeLines(long[] as) { PrintWriter pw = new PrintWriter(System.out); for (long a : as) pw.println(a); pw.flush(); } static int max(int... as) { int max = Integer.MIN_VALUE; for (int a : as) max = Math.max(a, max); return max; } static int min(int... as) { int min = Integer.MAX_VALUE; for (int a : as) min = Math.min(a, min); return min; } static void debug(Object... args) { StringJoiner j = new StringJoiner(" "); for (Object arg : args) { if (arg instanceof int[]) j.add(Arrays.toString((int[]) arg)); else if (arg instanceof long[]) j.add(Arrays.toString((long[]) arg)); else if (arg instanceof double[]) j.add(Arrays.toString((double[]) arg)); else if (arg instanceof Object[]) j.add(Arrays.toString((Object[]) arg)); else j.add(arg.toString()); } System.err.println(j.toString()); } }
Java
["3 4\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;", "3 3\n&gt;&gt;&gt;\n&lt;&lt;&lt;\n&gt;&gt;&gt;", "3 2\n==\n=&lt;\n=="]
2 seconds
["Yes\n2 2 2 \n1 1 1 1", "Yes\n3 1 3 \n2 2 2", "No"]
NoteIn the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be $$$2$$$, for all dishes of the first day.In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
Java 8
standard input
[ "dp", "greedy", "graphs", "dsu", "dfs and similar" ]
016bf7989ba58fdc3894a4cf3e0ac302
The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 1000$$$) — the number of dishes in both days. Each of the next $$$n$$$ lines contains a string of $$$m$$$ symbols. The $$$j$$$-th symbol on $$$i$$$-th line is $$$a_{ij}$$$. All strings consist only of "&lt;", "&gt;" and "=".
2,000
The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print $$$n$$$ integers — evaluations of dishes from the first set, and on the third line print $$$m$$$ integers — evaluations of dishes from the second set.
standard output
PASSED
8067779eee46380794a72f6ce17b40ef
train_001.jsonl
1550917200
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review  — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer.Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes.The gourmet tasted a set of $$$n$$$ dishes on the first day and a set of $$$m$$$ dishes on the second day. He made a table $$$a$$$ of size $$$n \times m$$$, in which he described his impressions. If, according to the expert, dish $$$i$$$ from the first set was better than dish $$$j$$$ from the second set, then $$$a_{ij}$$$ is equal to "&gt;", in the opposite case $$$a_{ij}$$$ is equal to "&lt;". Dishes also may be equally good, in this case $$$a_{ij}$$$ is "=".Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if $$$a_{ij}$$$ is "&lt;", then the number assigned to dish $$$i$$$ from the first set should be less than the number of dish $$$j$$$ from the second set, if $$$a_{ij}$$$ is "&gt;", then it should be greater, and finally if $$$a_{ij}$$$ is "=", then the numbers should be the same.Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.IOException; import java.io.Reader; import java.io.InputStreamReader; import java.util.List; import java.util.StringTokenizer; 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; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); D solver = new D(); solver.solve(1, in, out); out.close(); } static class D { List<Edge>[] g; boolean[] used; boolean[] processed; int[] val; private boolean dfs(int v) { used[v] = true; int min = 10000; for (Edge e : g[v]) { if (!used[e.to]) { if (!dfs(e.to)) return false; } else if (!processed[e.to]) { return false; } min = Math.min(min, val[e.to]); } val[v] = min - 1; processed[v] = true; return true; } public void solve(int testNumber, FastScanner in, PrintWriter out) { int n = in.ni(), m = in.ni(); char[][] map = in.nm(n, m); DSU dsu = new DSU(n + m); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (map[i][j] == '=') { dsu.union(i, n + j); } } } g = new List[n + m]; for (int i = 0; i < n + m; i++) { g[i] = new LinkedList<>(); } int[] dIn = new int[n + m]; int[] dOut = new int[n + m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (map[i][j] == '<') { int from = dsu.find(i); int to = dsu.find(n + j); g[from].add(new Edge(from, to)); dOut[from]++; dIn[to]++; } else if (map[i][j] == '>') { int from = dsu.find(n + j); int to = dsu.find(i); g[from].add(new Edge(from, to)); dOut[from]++; dIn[to]++; } } } used = new boolean[n + m]; processed = new boolean[n + m]; val = new int[n + m]; while (true) { int start = -1; for (int i = 0; i < n + m; i++) { if (!processed[i] && dIn[i] == 0 && dOut[i] > 0) { start = i; break; } } if (start == -1) { break; } if (!dfs(start)) { out.println("No"); return; } } for (int i = 0; i < n + m; i++) { if (!processed[i] && dOut[i] > 0) { out.println("No"); return; } } int min = 10000; for (int i = 0; i < n + m; i++) { if (val[i] != 0) { min = Math.min(val[i], min); } } if (min == 10000) min = 0; min--; out.println("Yes"); for (int i = 0; i < n; i++) { out.printf("%d ", val[dsu.find(i)] - min); } out.println(); for (int i = 0; i < m; i++) { out.printf("%d ", val[dsu.find(n + i)] - min); } } class Edge { int from; int to; public Edge(int from, int to) { this.from = from; this.to = to; } } } static class FastScanner { private BufferedReader in; private StringTokenizer st; public FastScanner(InputStream stream) { in = new BufferedReader(new InputStreamReader(stream)); } public String ns() { 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 ni() { return Integer.parseInt(ns()); } public char[] ns(int n) { char[] buf = new char[n]; try { in.read(buf); } catch (IOException e) { throw new RuntimeException(); } return buf; } public char[][] nm(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) { map[i] = ns(m); readLine(); } return map; } public String readLine() { try { return in.readLine(); } catch (IOException e) { throw new RuntimeException(); } } } static class DSU { int[] rank; int[] parent; int n; int sets; public DSU(int n) { rank = new int[n]; parent = new int[n]; this.n = n; sets = n; makeSet(); } void makeSet() { for (int i = 0; i < n; i++) { parent[i] = i; } } public int find(int x) { if (parent[x] != x) { parent[x] = find(parent[x]); } return parent[x]; } public void union(int x, int y) { int xRoot = find(x), yRoot = find(y); if (xRoot == yRoot) return; sets--; if (rank[xRoot] < rank[yRoot]) parent[xRoot] = yRoot; else if (rank[yRoot] < rank[xRoot]) parent[yRoot] = xRoot; else { parent[yRoot] = xRoot; rank[xRoot] = rank[xRoot] + 1; } } } }
Java
["3 4\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;", "3 3\n&gt;&gt;&gt;\n&lt;&lt;&lt;\n&gt;&gt;&gt;", "3 2\n==\n=&lt;\n=="]
2 seconds
["Yes\n2 2 2 \n1 1 1 1", "Yes\n3 1 3 \n2 2 2", "No"]
NoteIn the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be $$$2$$$, for all dishes of the first day.In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
Java 8
standard input
[ "dp", "greedy", "graphs", "dsu", "dfs and similar" ]
016bf7989ba58fdc3894a4cf3e0ac302
The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 1000$$$) — the number of dishes in both days. Each of the next $$$n$$$ lines contains a string of $$$m$$$ symbols. The $$$j$$$-th symbol on $$$i$$$-th line is $$$a_{ij}$$$. All strings consist only of "&lt;", "&gt;" and "=".
2,000
The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print $$$n$$$ integers — evaluations of dishes from the first set, and on the third line print $$$m$$$ integers — evaluations of dishes from the second set.
standard output
PASSED
63c468438f447f15e1495e2e12643bc4
train_001.jsonl
1550917200
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review  — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer.Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes.The gourmet tasted a set of $$$n$$$ dishes on the first day and a set of $$$m$$$ dishes on the second day. He made a table $$$a$$$ of size $$$n \times m$$$, in which he described his impressions. If, according to the expert, dish $$$i$$$ from the first set was better than dish $$$j$$$ from the second set, then $$$a_{ij}$$$ is equal to "&gt;", in the opposite case $$$a_{ij}$$$ is equal to "&lt;". Dishes also may be equally good, in this case $$$a_{ij}$$$ is "=".Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if $$$a_{ij}$$$ is "&lt;", then the number assigned to dish $$$i$$$ from the first set should be less than the number of dish $$$j$$$ from the second set, if $$$a_{ij}$$$ is "&gt;", then it should be greater, and finally if $$$a_{ij}$$$ is "=", then the numbers should be the same.Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.List; import java.util.Arrays; import java.util.InputMismatchException; import java.io.IOException; import java.util.Collections; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; 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 static int[] createSets(int size) { int[] p = new int[size]; for (int i = 0; i < size; i++) p[i] = i; return p; } public static int root(int[] p, int x) { return x == p[x] ? x : (p[x] = root(p, p[x])); } public static boolean unite(int[] p, int a, int b) { a = root(p, a); b = root(p, b); if (a != b) { p[a] = b; return true; } return false; } static int dfs(List<Integer>[] graph, int u, int[] color, int[] next) { color[u] = 1; for (int v : graph[u]) { next[u] = v; if (color[v] == 0) { int cycleStart = dfs(graph, v, color, next); if (cycleStart != -1) { return cycleStart; } } else if (color[v] == 1) { return v; } } color[u] = 2; return -1; } public static boolean findCycle(List<Integer>[] graph) { int n = graph.length; int[] color = new int[n]; int[] next = new int[n]; for (int u = 0; u < n; u++) { if (color[u] != 0) continue; int cycleStart = dfs(graph, u, color, next); if (cycleStart != -1) { List<Integer> cycle = new ArrayList<>(); cycle.add(cycleStart); for (int i = next[cycleStart]; i != cycleStart; i = next[i]) { cycle.add(i); } cycle.add(cycleStart); return true; } } return false; } static void dfs(List<Integer>[] graph, boolean[] used, List<Integer> order, int u) { used[u] = true; for (int v : graph[u]) if (!used[v]) dfs(graph, used, order, v); order.add(u); } public static List<Integer> topologicalSort(List<Integer>[] graph) { int n = graph.length; boolean[] used = new boolean[n]; List<Integer> order = new ArrayList<>(); for (int i = 0; i < n; i++) if (!used[i]) dfs(graph, used, order, i); Collections.reverse(order); return order; } public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); char[][] a = new char[n][]; int[] p = createSets(n + m); List<Integer>[] g = new List[n + m]; for (int i = 0; i < n + m; i++) { g[i] = new ArrayList<>(); } for (int i = 0; i < n; i++) { a[i] = in.next().toCharArray(); for (int j = 0; j < m; j++) { if (a[i][j] == '=') { unite(p, i, j + n); } } } List<Integer>[] map = new List[n + m]; for (int i = 0; i < map.length; i++) { map[i] = new ArrayList<>(); } for (int i = 0; i < n + m; i++) { map[root(p, i)].add(i); } for (int i = 0; i < n; i++) { int ri = root(p, i); for (int j = 0; j < m; j++) { int rj = root(p, n + j); if (ri == rj && a[i][j] != '=') { out.println("No"); return; } if (a[i][j] == '<') { g[ri].add(rj); } if (a[i][j] == '>') { g[rj].add(ri); } } } if (findCycle(g)) { out.println("No"); return; } List<Integer> order = topologicalSort(g); int[] res = new int[n + m]; Arrays.fill(res, 1); for (int i : order) { for (int j : g[i]) { res[j] = Math.max(res[j], res[i] + 1); } } int[] res2 = new int[n + m]; for (int i = 0; i < n + m; i++) { if (!map[i].isEmpty()) { for (int j : map[i]) { res2[j] = res[i]; } } } out.println("Yes"); for (int i = 0; i < n + m; i++) { out.print(res2[i] + " "); if (i == n - 1) out.println(); } out.println(); } } static class InputReader { final InputStream is; final byte[] buf = new byte[1024]; int pos; int size; public InputReader(InputStream is) { this.is = is; } public int nextInt() { int c = read(); while (isWhitespace(c)) c = read(); int sign = 1; if (c == '-') { sign = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = res * 10 + c - '0'; c = read(); } while (!isWhitespace(c)); return res * sign; } public String next() { int c = read(); while (isWhitespace(c)) c = read(); StringBuilder sb = new StringBuilder(); do { sb.append((char) c); c = read(); } while (!isWhitespace(c)); return sb.toString(); } int read() { if (size == -1) throw new InputMismatchException(); if (pos >= size) { pos = 0; try { size = is.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (size <= 0) return -1; } return buf[pos++] & 255; } static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["3 4\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;", "3 3\n&gt;&gt;&gt;\n&lt;&lt;&lt;\n&gt;&gt;&gt;", "3 2\n==\n=&lt;\n=="]
2 seconds
["Yes\n2 2 2 \n1 1 1 1", "Yes\n3 1 3 \n2 2 2", "No"]
NoteIn the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be $$$2$$$, for all dishes of the first day.In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
Java 8
standard input
[ "dp", "greedy", "graphs", "dsu", "dfs and similar" ]
016bf7989ba58fdc3894a4cf3e0ac302
The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 1000$$$) — the number of dishes in both days. Each of the next $$$n$$$ lines contains a string of $$$m$$$ symbols. The $$$j$$$-th symbol on $$$i$$$-th line is $$$a_{ij}$$$. All strings consist only of "&lt;", "&gt;" and "=".
2,000
The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print $$$n$$$ integers — evaluations of dishes from the first set, and on the third line print $$$m$$$ integers — evaluations of dishes from the second set.
standard output
PASSED
aeadfb852768226786a9194887c7ef2e
train_001.jsonl
1550917200
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review  — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer.Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes.The gourmet tasted a set of $$$n$$$ dishes on the first day and a set of $$$m$$$ dishes on the second day. He made a table $$$a$$$ of size $$$n \times m$$$, in which he described his impressions. If, according to the expert, dish $$$i$$$ from the first set was better than dish $$$j$$$ from the second set, then $$$a_{ij}$$$ is equal to "&gt;", in the opposite case $$$a_{ij}$$$ is equal to "&lt;". Dishes also may be equally good, in this case $$$a_{ij}$$$ is "=".Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if $$$a_{ij}$$$ is "&lt;", then the number assigned to dish $$$i$$$ from the first set should be less than the number of dish $$$j$$$ from the second set, if $$$a_{ij}$$$ is "&gt;", then it should be greater, and finally if $$$a_{ij}$$$ is "=", then the numbers should be the same.Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.List; import java.util.Arrays; import java.util.InputMismatchException; import java.io.IOException; import java.util.Collections; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; 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 static int[] createSets(int size) { int[] p = new int[size]; for (int i = 0; i < size; i++) p[i] = i; return p; } public static int root(int[] p, int x) { return x == p[x] ? x : (p[x] = root(p, p[x])); } public static void unite(int[] p, int a, int b) { a = root(p, a); b = root(p, b); p[a] = b; } static int dfs(List<Integer>[] graph, int u, int[] color, int[] next) { color[u] = 1; for (int v : graph[u]) { next[u] = v; if (color[v] == 0) { int cycleStart = dfs(graph, v, color, next); if (cycleStart != -1) { return cycleStart; } } else if (color[v] == 1) { return v; } } color[u] = 2; return -1; } public static boolean findCycle(List<Integer>[] graph) { int n = graph.length; int[] color = new int[n]; int[] next = new int[n]; for (int u = 0; u < n; u++) { if (color[u] != 0) continue; int cycleStart = dfs(graph, u, color, next); if (cycleStart != -1) { List<Integer> cycle = new ArrayList<>(); cycle.add(cycleStart); for (int i = next[cycleStart]; i != cycleStart; i = next[i]) { cycle.add(i); } cycle.add(cycleStart); return true; } } return false; } static void dfs(List<Integer>[] graph, boolean[] used, List<Integer> order, int u) { used[u] = true; for (int v : graph[u]) if (!used[v]) dfs(graph, used, order, v); order.add(u); } public static List<Integer> topologicalSort(List<Integer>[] graph) { int n = graph.length; boolean[] used = new boolean[n]; List<Integer> order = new ArrayList<>(); for (int i = 0; i < n; i++) if (!used[i]) dfs(graph, used, order, i); Collections.reverse(order); return order; } public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); char[][] a = new char[n][]; int[] p = createSets(n + m); List<Integer>[] g = new List[n + m]; for (int i = 0; i < n + m; i++) { g[i] = new ArrayList<>(); } for (int i = 0; i < n; i++) { a[i] = in.next().toCharArray(); for (int j = 0; j < m; j++) { if (a[i][j] == '=') { unite(p, i, j + n); } } } List<Integer>[] map = new List[n + m]; for (int i = 0; i < map.length; i++) { map[i] = new ArrayList<>(); } for (int i = 0; i < n + m; i++) { map[root(p, i)].add(i); } for (int i = 0; i < n; i++) { int ri = root(p, i); for (int j = 0; j < m; j++) { int rj = root(p, n + j); if (ri == rj && a[i][j] != '=') { out.println("No"); return; } if (a[i][j] == '<') { g[ri].add(rj); } if (a[i][j] == '>') { g[rj].add(ri); } } } if (findCycle(g)) { out.println("No"); return; } List<Integer> order = topologicalSort(g); int[] res = new int[n + m]; Arrays.fill(res, 1); for (int i : order) { for (int j : g[i]) { res[j] = Math.max(res[j], res[i] + 1); } } int[] res2 = new int[n + m]; for (int i = 0; i < n + m; i++) { if (!map[i].isEmpty()) { for (int j : map[i]) { res2[j] = res[i]; } } } out.println("Yes"); for (int i = 0; i < n + m; i++) { out.print(res2[i] + " "); if (i == n - 1) out.println(); } out.println(); } } static class InputReader { final InputStream is; final byte[] buf = new byte[1024]; int pos; int size; public InputReader(InputStream is) { this.is = is; } public int nextInt() { int c = read(); while (isWhitespace(c)) c = read(); int sign = 1; if (c == '-') { sign = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = res * 10 + c - '0'; c = read(); } while (!isWhitespace(c)); return res * sign; } public String next() { int c = read(); while (isWhitespace(c)) c = read(); StringBuilder sb = new StringBuilder(); do { sb.append((char) c); c = read(); } while (!isWhitespace(c)); return sb.toString(); } int read() { if (size == -1) throw new InputMismatchException(); if (pos >= size) { pos = 0; try { size = is.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (size <= 0) return -1; } return buf[pos++] & 255; } static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["3 4\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;", "3 3\n&gt;&gt;&gt;\n&lt;&lt;&lt;\n&gt;&gt;&gt;", "3 2\n==\n=&lt;\n=="]
2 seconds
["Yes\n2 2 2 \n1 1 1 1", "Yes\n3 1 3 \n2 2 2", "No"]
NoteIn the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be $$$2$$$, for all dishes of the first day.In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
Java 8
standard input
[ "dp", "greedy", "graphs", "dsu", "dfs and similar" ]
016bf7989ba58fdc3894a4cf3e0ac302
The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 1000$$$) — the number of dishes in both days. Each of the next $$$n$$$ lines contains a string of $$$m$$$ symbols. The $$$j$$$-th symbol on $$$i$$$-th line is $$$a_{ij}$$$. All strings consist only of "&lt;", "&gt;" and "=".
2,000
The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print $$$n$$$ integers — evaluations of dishes from the first set, and on the third line print $$$m$$$ integers — evaluations of dishes from the second set.
standard output
PASSED
3eb23a072c888c48676569bcbc727bec
train_001.jsonl
1550917200
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review  — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer.Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes.The gourmet tasted a set of $$$n$$$ dishes on the first day and a set of $$$m$$$ dishes on the second day. He made a table $$$a$$$ of size $$$n \times m$$$, in which he described his impressions. If, according to the expert, dish $$$i$$$ from the first set was better than dish $$$j$$$ from the second set, then $$$a_{ij}$$$ is equal to "&gt;", in the opposite case $$$a_{ij}$$$ is equal to "&lt;". Dishes also may be equally good, in this case $$$a_{ij}$$$ is "=".Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if $$$a_{ij}$$$ is "&lt;", then the number assigned to dish $$$i$$$ from the first set should be less than the number of dish $$$j$$$ from the second set, if $$$a_{ij}$$$ is "&gt;", then it should be greater, and finally if $$$a_{ij}$$$ is "=", then the numbers should be the same.Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; public class D{ 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 class Dsu { int n; int[] parent; int[] rank; public Dsu(int n) { this.n = n; parent = new int[n]; rank = new int[n]; } public void createSet() { for(int i = 0; i < n; i++) { parent[i] = i; rank[i] = 0; } } public int findParent(int x) { if(parent[x] == x) return x; parent[x] = findParent(parent[x]); return parent[x]; } public void mergeSet(int a,int b) { int pa = findParent(a); int pb = findParent(b); if(pa == pb) return; if(rank[pa] > rank[pb]) { parent[pb] = pa; } else if(rank[pa] < rank[pb]) { parent[pa] = pb; } else { parent[pb] = pa; rank[pa]++; } } } public static int dfs(int s) { vis[s] = true; Iterator<Integer> itr = ar[s].iterator(); int max = 0; while(itr.hasNext()) { int n = itr.next(); if(!vis[n]) { max = Math.max(max,dfs(n)); } else { max = Math.max(max,val[n]); } } val[s] = max+1; return val[s]; } public static boolean isCyclic(int s) { if(recStack[s] == true) return true; if(vis[s] == true) return false; vis[s] = true; recStack[s] = true; Iterator<Integer> itr = ar[s].iterator(); while(itr.hasNext()) { int n = itr.next(); if(isCyclic(n)) { return true; } } recStack[s] = false; return false; } static char mat[][]; static List<Integer> ar[]; static int val[]; static boolean vis[]; static boolean recStack[]; public static void main(String[] args) { OutputStream outputStream = System.out; FastReader sc = new FastReader(); PrintWriter out = new PrintWriter(outputStream); int n = sc.nextInt(); int m = sc.nextInt(); ar = new List[n+m]; for(int i = 0; i < n+m; i++) { ar[i] = new ArrayList<>(); } mat = new char[n][m]; for(int i = 0; i < n; i++) { mat[i] = sc.nextLine().toCharArray(); } vis = new boolean[n+m]; Arrays.fill(vis,false); recStack = new boolean[n+m]; Arrays.fill(recStack,false); val = new int[n+m]; Dsu d = new Dsu(n+m); //System.out.println("Next up finding equality"); d.createSet(); for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { if(mat[i][j] == '=') { d.mergeSet(i, n+j); } } } //System.out.println("Next up graph building"); int pi = -1,pj = -1; for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { pi = d.findParent(i); pj = d.findParent(n+j); if(mat[i][j] == '>') { ar[pi].add(pj); } else if(mat[i][j] == '<') { ar[pj].add(pi); } else { continue; } } } //System.out.println("Next up cyclic nature"); for(int i = 0; i < n+m; i++) { if(!vis[d.findParent(i)]) { if(isCyclic(d.findParent(i))) { out.println("No"); out.close(); return; } } } Arrays.fill(vis,false); //System.out.println("Next up dfs"); for(int i = 0; i < n+m; i++) { if(!vis[d.findParent(i)]) dfs(d.findParent(i)); } out.println("Yes"); for(int i = 0; i < n; i++) { out.print(val[d.findParent(i)]+" "); } out.println(); for(int i = n; i < n+m; i++) { out.print(val[d.findParent(i)]+" "); } out.close(); } }
Java
["3 4\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;", "3 3\n&gt;&gt;&gt;\n&lt;&lt;&lt;\n&gt;&gt;&gt;", "3 2\n==\n=&lt;\n=="]
2 seconds
["Yes\n2 2 2 \n1 1 1 1", "Yes\n3 1 3 \n2 2 2", "No"]
NoteIn the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be $$$2$$$, for all dishes of the first day.In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
Java 8
standard input
[ "dp", "greedy", "graphs", "dsu", "dfs and similar" ]
016bf7989ba58fdc3894a4cf3e0ac302
The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 1000$$$) — the number of dishes in both days. Each of the next $$$n$$$ lines contains a string of $$$m$$$ symbols. The $$$j$$$-th symbol on $$$i$$$-th line is $$$a_{ij}$$$. All strings consist only of "&lt;", "&gt;" and "=".
2,000
The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print $$$n$$$ integers — evaluations of dishes from the first set, and on the third line print $$$m$$$ integers — evaluations of dishes from the second set.
standard output
PASSED
6a9e4eb756526d422149d810103111d8
train_001.jsonl
1550917200
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review  — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer.Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes.The gourmet tasted a set of $$$n$$$ dishes on the first day and a set of $$$m$$$ dishes on the second day. He made a table $$$a$$$ of size $$$n \times m$$$, in which he described his impressions. If, according to the expert, dish $$$i$$$ from the first set was better than dish $$$j$$$ from the second set, then $$$a_{ij}$$$ is equal to "&gt;", in the opposite case $$$a_{ij}$$$ is equal to "&lt;". Dishes also may be equally good, in this case $$$a_{ij}$$$ is "=".Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if $$$a_{ij}$$$ is "&lt;", then the number assigned to dish $$$i$$$ from the first set should be less than the number of dish $$$j$$$ from the second set, if $$$a_{ij}$$$ is "&gt;", then it should be greater, and finally if $$$a_{ij}$$$ is "=", then the numbers should be the same.Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { public static class FastReader { BufferedReader br; StringTokenizer root; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (root == null || !root.hasMoreTokens()) { try { root = new StringTokenizer(br.readLine()); } catch (Exception addd) { addd.printStackTrace(); } } return root.nextToken(); } int nextInt() { return Integer.parseInt(next()); } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (Exception addd) { addd.printStackTrace(); } return str; } } public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out)); public static FastReader sc = new FastReader(); static int mod = (int) (1e9+7),MAX=(int) (2e5); static List<Integer>[] edges; static int[] in; public static void main(String[] args) { int n = sc.nextInt(); int m = sc.nextInt(); edges = new ArrayList[n+m+1]; in = new int[n+m+1]; DSU dsu = new DSU(n+m+1); for(int i=0;i<edges.length;++i) edges[i] = new ArrayList<>(); char[][] tab = new char[n+1][]; for(int i=1;i<=n;++i) { tab[i]= ("#"+sc.next()).toCharArray(); for(int j=1;j<=m;++j) { if(tab[i][j] == '=') dsu.unite(i,n+j); } } for(int i=1;i<=n;++i) { int u = dsu.findRoot(i); for(int j=1;j<=m;++j) { int v = dsu.findRoot(n+j); if(tab[i][j] == '>') { in[v]++; edges[u].add(v); }else if(tab[i][j] == '<') { edges[v].add(u); in[u]++; } } } Queue<Integer> q = new LinkedList<>(); for(int i=1;i<in.length;++i) if(dsu.findRoot(i) == i && in[i] == 0) q.add(i); // adding all the source node with indegree 0. List<Integer> order = new ArrayList<>(); while(q.size() > 0) { int x = q.poll(); order.add(x); for(int node : edges[x]) { if(--in[node] == 0) q.add(node); // adding only when it becomes source } } int[] dp = new int[n+m+1]; for(int i=order.size()-1;i>=0;--i) { int v = order.get(i); int ans = 1; for(int node : edges[v]) { ans = Math.max(ans,dp[node]+1); } dp[v] = ans; } boolean cycle = false; for(int i=1;i<dp.length;++i) { if(dsu.findRoot(i) == i && dp[i] == 0) cycle = true; // not in any group and value is not calc i.e cycle is present } if(cycle) out.println("No"); else { out.println("Yes"); for(int i=1;i<=n+m;++i) { out.print(dp[dsu.findRoot(i)]+" "); if(i == n) out.println(); } } out.close(); } static class DSU { int n; int[] parent, size; public DSU(int v) { n = v; parent = new int[n]; size = new int[n]; for(int i = 0; i < n; i++) { parent[i] = i; size[i] = 1; } } public int findRoot(int curr) { if(curr == parent[curr]) return curr; return parent[curr] = findRoot(parent[curr]); } public boolean unite(int a, int b) { int rootA = findRoot(a); int rootB = findRoot(b); if(rootA == rootB) return true; if(size[rootA] > size[rootB]) { parent[rootB] = rootA; size[rootA] += size[rootB]; } else { parent[rootA] = rootB; size[rootB] += size[rootA]; } return false; } } }
Java
["3 4\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;", "3 3\n&gt;&gt;&gt;\n&lt;&lt;&lt;\n&gt;&gt;&gt;", "3 2\n==\n=&lt;\n=="]
2 seconds
["Yes\n2 2 2 \n1 1 1 1", "Yes\n3 1 3 \n2 2 2", "No"]
NoteIn the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be $$$2$$$, for all dishes of the first day.In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
Java 8
standard input
[ "dp", "greedy", "graphs", "dsu", "dfs and similar" ]
016bf7989ba58fdc3894a4cf3e0ac302
The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 1000$$$) — the number of dishes in both days. Each of the next $$$n$$$ lines contains a string of $$$m$$$ symbols. The $$$j$$$-th symbol on $$$i$$$-th line is $$$a_{ij}$$$. All strings consist only of "&lt;", "&gt;" and "=".
2,000
The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print $$$n$$$ integers — evaluations of dishes from the first set, and on the third line print $$$m$$$ integers — evaluations of dishes from the second set.
standard output
PASSED
a12de02f266b6e0d7e655eb350152d13
train_001.jsonl
1550917200
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review  — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer.Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes.The gourmet tasted a set of $$$n$$$ dishes on the first day and a set of $$$m$$$ dishes on the second day. He made a table $$$a$$$ of size $$$n \times m$$$, in which he described his impressions. If, according to the expert, dish $$$i$$$ from the first set was better than dish $$$j$$$ from the second set, then $$$a_{ij}$$$ is equal to "&gt;", in the opposite case $$$a_{ij}$$$ is equal to "&lt;". Dishes also may be equally good, in this case $$$a_{ij}$$$ is "=".Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if $$$a_{ij}$$$ is "&lt;", then the number assigned to dish $$$i$$$ from the first set should be less than the number of dish $$$j$$$ from the second set, if $$$a_{ij}$$$ is "&gt;", then it should be greater, and finally if $$$a_{ij}$$$ is "=", then the numbers should be the same.Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible.
256 megabytes
import java.util.Scanner; public class Main { public static int[] dsu; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int m = scanner.nextInt(); scanner.nextLine(); int[] a = new int[n * m + 1]; int[] b = new int[n * m + 1]; int[] c = new int[n + m + 1]; dsu = new int[n + m + 1]; int[] state = new int[n + m + 1]; int[] inDegree = new int[n + m + 1]; for (int i = 1, total = n + m; i <= total; i++) dsu[i] = i; char[][] chars = new char[n][]; for (int i = 0; i < n; i++) { chars[i] = scanner.nextLine().toCharArray(); for (int j = 0; j < m; j++) { if (chars[i][j] == '=') { join(i + 1, n + j + 1); } } } int t = 0; int temp; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (chars[i][j] == '<') { t++; temp = find(i + 1); a[t] = find(temp); inDegree[temp]++; temp = find(n + j + 1); b[t] = c[temp]; c[temp] = t; } else if (chars[i][j] == '>') { t++; temp = find(n + j + 1); a[t] = find(temp); inDegree[temp]++; temp = find(i + 1); b[t] = c[temp]; c[temp] = t; } } } boolean findable = true; int count = 0; boolean[] used = new boolean[n + m + 1]; while (findable) { findable = false; count++; for (int i = 1, total = n + m; i <= total; i++) { if (state[i] == 0 && inDegree[find(i)] == 0) { findable = true; state[i] = count; } } for (int i = 1, total = n + m; i <= total; i++) { if (state[i] == count && !used[temp = find(i)]) { used[temp] = true; t = c[temp]; while (t != 0) { inDegree[find(a[t])]--; t = b[t]; } } } } for (int i = 1; i <= n + m; i++) if (state[i] == 0) { System.out.println("No"); System.exit(0); } System.out.println("Yes"); for (int i = 1; i < n; i++) System.out.print(count - state[i] + " "); System.out.println(count - state[n]); for (int i = n + 1; i <= n + m; i++) System.out.print(count - state[i] + " "); } public static int find(int x) { int r = x; while (dsu[r] != r) r = dsu[r]; int temp; while (dsu[x] != x) { temp = dsu[x]; dsu[x] = r; x = temp; } return r; } public static void join(int x, int y) { int rx = find(x); int ry = find(y); if (rx != ry){ dsu[ry] = rx; } } }
Java
["3 4\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;", "3 3\n&gt;&gt;&gt;\n&lt;&lt;&lt;\n&gt;&gt;&gt;", "3 2\n==\n=&lt;\n=="]
2 seconds
["Yes\n2 2 2 \n1 1 1 1", "Yes\n3 1 3 \n2 2 2", "No"]
NoteIn the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be $$$2$$$, for all dishes of the first day.In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
Java 8
standard input
[ "dp", "greedy", "graphs", "dsu", "dfs and similar" ]
016bf7989ba58fdc3894a4cf3e0ac302
The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 1000$$$) — the number of dishes in both days. Each of the next $$$n$$$ lines contains a string of $$$m$$$ symbols. The $$$j$$$-th symbol on $$$i$$$-th line is $$$a_{ij}$$$. All strings consist only of "&lt;", "&gt;" and "=".
2,000
The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print $$$n$$$ integers — evaluations of dishes from the first set, and on the third line print $$$m$$$ integers — evaluations of dishes from the second set.
standard output
PASSED
cdb8fddf422fe967bbbf8d59fb8cf166
train_001.jsonl
1550917200
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review  — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer.Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes.The gourmet tasted a set of $$$n$$$ dishes on the first day and a set of $$$m$$$ dishes on the second day. He made a table $$$a$$$ of size $$$n \times m$$$, in which he described his impressions. If, according to the expert, dish $$$i$$$ from the first set was better than dish $$$j$$$ from the second set, then $$$a_{ij}$$$ is equal to "&gt;", in the opposite case $$$a_{ij}$$$ is equal to "&lt;". Dishes also may be equally good, in this case $$$a_{ij}$$$ is "=".Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if $$$a_{ij}$$$ is "&lt;", then the number assigned to dish $$$i$$$ from the first set should be less than the number of dish $$$j$$$ from the second set, if $$$a_{ij}$$$ is "&gt;", then it should be greater, and finally if $$$a_{ij}$$$ is "=", then the numbers should be the same.Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible.
256 megabytes
import java.util.*; import java.io.*; import static java.lang.Math.*; public class MainS { static final long MOD = 1_000_000_007, INF = 1_000_000_000_000_000_000L; static final int INf = 1_000_000_000; static FastReader reader; static PrintWriter writer; public static void main(String[] args) { Thread t = new Thread(null, new O(), "Integer.MAX_VALUE", 100000000); t.start(); } static class O implements Runnable { public void run() { try { magic(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } } public static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static int N, baap[], weight[],dp[]; static ArrayList<Integer> adj[]; static boolean vis[], inStack[], cycleDetected = false; static int assigned[]; static void magic() throws IOException { reader = new FastReader(); writer = new PrintWriter(System.out, true); int n = reader.nextInt(), m = reader.nextInt(); N = n + m; baap = new int[N+1]; weight = new int[N+1]; char c[][] = new char[n][m]; for(int i=0;i<n;++i) { c[i] = reader.next().toCharArray(); } //writer.println("yaha0"); init(N); for(int i=0;i<n;++i) { for(int j=0;j<m;++j) { if(c[i][j]=='=') { un(i+1, n+j+1); } } } //writer.println("yaha1"); int indeg[] = new int[N+1]; dp = new int[N+1]; Arrays.fill(dp, -1); adj = new ArrayList[N+1]; for(int i=1;i<=N;++i) { adj[i] = new ArrayList<>(); } for(int i=0;i<n;++i) { for(int j=0;j<m;++j) { if(c[i][j]=='>') { int ra = gr(n+j+1); int rb = gr(i+1); if(ra==rb) { writer.println("No"); System.exit(0); } adj[rb].add(ra); indeg[ra]++; } else if(c[i][j]=='<') { int ra = gr(i+1); int rb = gr(n+j+1); if(ra==rb) { writer.println("No"); System.exit(0); } adj[rb].add(ra); indeg[ra]++; } } } //writer.println("yaha2"); vis = new boolean[N+1]; inStack = new boolean[N+1]; for(int i=1;i<=N;++i) { if(!vis[gr(i)]) { dfs(gr(i)); if(cycleDetected) { writer.println("No"); System.exit(0); } } } // writer.println("new vertices corresponding to old: "); // for(int i=1;i<=N;++i) { // writer.print(gr(i) + " "); // } // writer.println(); // writer.println("yaha3"); vis = new boolean[N+1]; assigned = new int[N+1]; for(int i=1;i<=N;++i) { if(indeg[gr(i)]>0) { continue; } //writer.println("Starting DFS from vertex: "+i); if(!vis[gr(i)]) { dfs1(gr(i)); } } //writer.println("yaha4"); writer.println("Yes"); for(int i=1;i<=n;++i) { writer.print(dp[gr(i)] + " "); } writer.println(); for(int i=n+1;i<=n+m;++i) { writer.print(dp[gr(i)] + " "); } writer.println(); } static int dfs1(int x) { if(dp[x]!=-1) { return dp[x]; } int max = 0; vis[x] = true; for(int e : adj[x]) { if(true) { max = max(max, dfs1(e)); } } return dp[x] = 1+max; } static void dfs(int x) { vis[x] = inStack[x] = true; for(int e : adj[x]) { if(!vis[e]) { dfs(e); } else if(inStack[e]) { cycleDetected = true; } } inStack[x] = false; } static void init(int n) { baap = new int[n+1]; weight = new int[n+1]; for(int i=0;i<=n;++i) { baap[i] = i; ++weight[i]; } } static int gr(int a) { if(baap[a]==a) return a; return baap[a] = gr(baap[a]); } static boolean un(int a,int b) { int ra = gr(a); int rb = gr(b); if(ra==rb) return false; if(weight[rb]>weight[ra]) { weight[rb]+=weight[ra]; baap[ra] = rb; } else { weight[ra]+=weight[rb]; baap[rb] = ra; } return true; } }
Java
["3 4\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;", "3 3\n&gt;&gt;&gt;\n&lt;&lt;&lt;\n&gt;&gt;&gt;", "3 2\n==\n=&lt;\n=="]
2 seconds
["Yes\n2 2 2 \n1 1 1 1", "Yes\n3 1 3 \n2 2 2", "No"]
NoteIn the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be $$$2$$$, for all dishes of the first day.In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
Java 8
standard input
[ "dp", "greedy", "graphs", "dsu", "dfs and similar" ]
016bf7989ba58fdc3894a4cf3e0ac302
The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 1000$$$) — the number of dishes in both days. Each of the next $$$n$$$ lines contains a string of $$$m$$$ symbols. The $$$j$$$-th symbol on $$$i$$$-th line is $$$a_{ij}$$$. All strings consist only of "&lt;", "&gt;" and "=".
2,000
The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print $$$n$$$ integers — evaluations of dishes from the first set, and on the third line print $$$m$$$ integers — evaluations of dishes from the second set.
standard output
PASSED
fc259f63b2c9ea66b918b98d2c12409a
train_001.jsonl
1550917200
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review  — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer.Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes.The gourmet tasted a set of $$$n$$$ dishes on the first day and a set of $$$m$$$ dishes on the second day. He made a table $$$a$$$ of size $$$n \times m$$$, in which he described his impressions. If, according to the expert, dish $$$i$$$ from the first set was better than dish $$$j$$$ from the second set, then $$$a_{ij}$$$ is equal to "&gt;", in the opposite case $$$a_{ij}$$$ is equal to "&lt;". Dishes also may be equally good, in this case $$$a_{ij}$$$ is "=".Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if $$$a_{ij}$$$ is "&lt;", then the number assigned to dish $$$i$$$ from the first set should be less than the number of dish $$$j$$$ from the second set, if $$$a_{ij}$$$ is "&gt;", then it should be greater, and finally if $$$a_{ij}$$$ is "=", then the numbers should be the same.Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible.
256 megabytes
import java.util.*; import java.io.*; public class gourmet { int N, M, nodeN, compN; int[] compID, inEdges, dishScores; boolean[][] adj, rawAdj, equalAdj; gourmet(BufferedReader in, PrintWriter out) throws IOException { StringTokenizer st = new StringTokenizer(in.readLine()); N = Integer.parseInt(st.nextToken()); M = Integer.parseInt(st.nextToken()); nodeN = N + M; rawAdj = new boolean[nodeN][nodeN]; equalAdj = new boolean[nodeN][nodeN]; for (int i = 0; i < N; i++) { String str = in.readLine(); for (int j = 0; j < M; j++) { char c = str.charAt(j); if (c == '>') { rawAdj[N+j][i] = true; } else if (c == '<') { rawAdj[i][N+j] = true; } else { equalAdj[N+j][i] = true; equalAdj[i][N+j] = true; } } } // Generate components compN = 0; compID = new int[nodeN]; Arrays.fill(compID, -1); for (int i = 0; i < nodeN; i++) { if (compID[i] == -1) dfsComp(i, compN++); } // Now, create the actual graph using these components adj = new boolean[compN][compN]; inEdges = new int[compN]; for (int i = 0; i < nodeN; i++) { for (int j = 0; j < nodeN; j++) { if (rawAdj[i][j] && !adj[compID[i]][compID[j]]) { inEdges[compID[j]]++; adj[compID[i]][compID[j]] = true; } } } // Generate topological ordering (if possible) dishScores = new int[compN]; for (int i = 0; i < compN; i++) { if (inEdges[i] == 0) { toEval.add(i); dishScores[i] = 1; } } int c; while (!toEval.isEmpty()) { c = toEval.poll(); // Spread to neighbors for (int i = 0; i < compN; i++) { if (adj[c][i]) { inEdges[i]--; if (inEdges[i] == 0) { dishScores[i] = dishScores[c] + 1; toEval.add(i); } } } } // If it got here, this is probably valid...? // System.out.println(Arrays.toString(inEdges)); for (int i = 0; i < compN; i++) { if (inEdges[i] != 0) { // Not all dishes were rated (cycle exists) out.println("No"); return; } } // Valid out.println("Yes"); for (int i = 0; i < nodeN; i++) { if (i == N) out.println(); else if (i != 0) out.print(' '); out.print(dishScores[compID[i]]); } out.println(); } void dfsComp(int n, int id) { compID[n] = id; for (int i = 0; i < nodeN; i++) { if (equalAdj[n][i] && compID[i] == -1) dfsComp(i, id); } } boolean[] checked; boolean checkEqual(int n) { checked[n] = true; for (int i = 0; i < nodeN; i++) { if (equalAdj[n][i] && !checked[i]) { if (dishScores[i] != dishScores[n]) return false; else if (!checkEqual(i)) return false; } } return true; } Queue<Integer> toEval = new LinkedList<>(); public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); new gourmet(in, out); in.close(); out.close(); } }
Java
["3 4\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;", "3 3\n&gt;&gt;&gt;\n&lt;&lt;&lt;\n&gt;&gt;&gt;", "3 2\n==\n=&lt;\n=="]
2 seconds
["Yes\n2 2 2 \n1 1 1 1", "Yes\n3 1 3 \n2 2 2", "No"]
NoteIn the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be $$$2$$$, for all dishes of the first day.In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
Java 8
standard input
[ "dp", "greedy", "graphs", "dsu", "dfs and similar" ]
016bf7989ba58fdc3894a4cf3e0ac302
The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 1000$$$) — the number of dishes in both days. Each of the next $$$n$$$ lines contains a string of $$$m$$$ symbols. The $$$j$$$-th symbol on $$$i$$$-th line is $$$a_{ij}$$$. All strings consist only of "&lt;", "&gt;" and "=".
2,000
The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print $$$n$$$ integers — evaluations of dishes from the first set, and on the third line print $$$m$$$ integers — evaluations of dishes from the second set.
standard output
PASSED
e4865663edb45c9035eb2f6e37d85c75
train_001.jsonl
1550917200
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review  — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer.Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes.The gourmet tasted a set of $$$n$$$ dishes on the first day and a set of $$$m$$$ dishes on the second day. He made a table $$$a$$$ of size $$$n \times m$$$, in which he described his impressions. If, according to the expert, dish $$$i$$$ from the first set was better than dish $$$j$$$ from the second set, then $$$a_{ij}$$$ is equal to "&gt;", in the opposite case $$$a_{ij}$$$ is equal to "&lt;". Dishes also may be equally good, in this case $$$a_{ij}$$$ is "=".Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if $$$a_{ij}$$$ is "&lt;", then the number assigned to dish $$$i$$$ from the first set should be less than the number of dish $$$j$$$ from the second set, if $$$a_{ij}$$$ is "&gt;", then it should be greater, and finally if $$$a_{ij}$$$ is "=", then the numbers should be the same.Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible.
256 megabytes
import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.lang.invoke.MethodHandles; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.PriorityQueue; import java.util.Random; import java.util.TreeSet; public final class CF_541_D2_De { static boolean verb=true; static void log(Object X){if (verb) System.err.println(X);} static void log(Object[] X){if (verb) {for (Object U:X) System.err.print(U+" ");System.err.println("");}} static void log(int[] X){if (verb) {for (int U:X) System.err.print(U+" ");System.err.println("");}} static void log(int[] X,int L){if (verb) {for (int i=0;i<L;i++) System.err.print(X[i]+" ");System.err.println("");}} static void log(long[] X){if (verb) {for (long U:X) System.err.print(U+" ");System.err.println("");}} static void logWln(Object X){if (verb) System.err.print(X);} static void info(Object o){ System.out.println(o);} static void output(Object o){outputWln(""+o+"\n"); } static void outputWln(Object o){try {out.write(""+ o);} catch (Exception e) {}} static long mod=1000000007; // Global vars static BufferedWriter out; static InputReader reader; static void test() { log("testing"); log("done"); } static int[] anc,rank,max,list; static void initSet(int x){ anc[x]=x; rank[x]=0; max[x]=x; } static int union(int x,int y){ //log("unioning x:"+x+" y:"+y); int xr=find(x); int yr=find(y); if (xr!=yr){ if (rank[xr]<rank[yr]){ anc[xr]=yr; max[yr]=Math.max(max[xr],max[yr]); return yr; // max[xr]=max[yr]; } else if (rank[xr]>rank[yr]) { anc[yr]=xr; max[xr]=Math.max(max[xr],max[yr]); // max[xr]=max[yr]; return xr; } else { anc[yr]=xr; rank[xr]++; max[xr]=Math.max(max[xr],max[yr]); //max[xr]=max[yr]; return xr; } } return -1; } static int find(int x){ if (anc[x]!=x){ anc[x]=find(anc[x]); } return anc[x]; } static void process() throws Exception { out = new BufferedWriter(new OutputStreamWriter(System.out)); reader = new InputReader(System.in); int n=reader.readInt(); int m=reader.readInt(); int nm=n+m; HashSet<Integer>[] upper=new HashSet[nm]; HashSet<Integer>[] lower=new HashSet[nm]; for (int i=0;i<nm;i++) { upper[i]=new HashSet<Integer>(); lower[i]=new HashSet<Integer>(); } anc=new int[nm]; rank=new int[nm]; max=new int[nm]; for (int i=0;i<nm;i++) initSet(i); String[] s=new String[n]; // first pass, merge for (int i=0;i<n;i++) { s[i]=reader.readString(); int u=i; for (int j=0;j<m;j++) { int v=j+n; char c=s[i].charAt(j); if (c=='=') { union(u,v); } } } for (int i=0;i<n;i++) { int u=find(i); for (int j=0;j<m;j++) { int v=find(j+n); char c=s[i].charAt(j); if (c=='>') { upper[v].add(u); lower[u].add(v); } if (c=='<') { upper[u].add(v); lower[v].add(u); } } } ArrayList<Integer>[] friends=new ArrayList[nm]; for (int u=0;u<nm;u++) { if (u==find(u)) { friends[u]=new ArrayList<Integer>(); friends[u].addAll(lower[u]); } } int[] it=new int[nm]; int tot=0; int processed=0; int[] stack=new int[nm]; int st=0; // now dfs starting from the lowest int time=0; int[] onstack=new int[nm]; boolean[] visited=new boolean[nm]; boolean error=false; int[] score=new int[nm]; Arrays.fill(score, -1); loop:for (int u=0;u<nm;u++) { if (u==anc[u]) { tot++; if (!visited[u]) { if (upper[u].size()==0) { //log("processing u:"+u); time++; st=0; stack[st++]=u; onstack[u]=time; it[u]=0; score[u]=1; visited[u]=true; while (st>0) { int v=stack[st-1]; if (it[v]==friends[v].size()) { onstack[v]=-1; it[v]=0; score[v]=1; for (int w:friends[v]) { if (score[v]<=score[w]) score[v]=score[w]+1; } st--; } else { int w=friends[v].get(it[v]++); if (onstack[w]==time) { error=true; //log("found loop"); break loop; } else { if (!visited[w]) { it[w]=0; onstack[w]=time; stack[st++]=w; visited[w]=true; } } } } } } } } if (!error) { // check for error for (int i=0;i<nm;i++) { int u=find(i); if (score[u]==-1) { //log("non allocated u:"+u); error=true; break; } } } if (error) { output("No"); } else { output("Yes"); for (int i=0;i<n;i++) { int u=find(i); output(score[u]); } output(""); for (int i=n;i<nm;i++) { int u=find(i); output(score[u]); } output(""); } try { out.close(); } catch (Exception e) { } } public static void main(String[] args) throws Exception { process(); } static final class InputReader { private final InputStream stream; private final byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } private int read() throws IOException { if (curChar >= numChars) { curChar = 0; numChars = stream.read(buf); if (numChars <= 0) { return -1; } } return buf[curChar++]; } public final String readString() throws IOException { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.append((char) c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public final int readInt() throws IOException { int c = read(); boolean neg = false; while (isSpaceChar(c)) { c = read(); } char d = (char) c; // log("d:"+d); if (d == '-') { neg = true; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); // log("res:"+res); if (neg) return -res; return res; } public final long readLong() throws IOException { int c = read(); boolean neg = false; while (isSpaceChar(c)) { c = read(); } char d = (char) c; // log("d:"+d); if (d == '-') { neg = true; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); // log("res:"+res); if (neg) return -res; return res; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["3 4\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;", "3 3\n&gt;&gt;&gt;\n&lt;&lt;&lt;\n&gt;&gt;&gt;", "3 2\n==\n=&lt;\n=="]
2 seconds
["Yes\n2 2 2 \n1 1 1 1", "Yes\n3 1 3 \n2 2 2", "No"]
NoteIn the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be $$$2$$$, for all dishes of the first day.In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
Java 8
standard input
[ "dp", "greedy", "graphs", "dsu", "dfs and similar" ]
016bf7989ba58fdc3894a4cf3e0ac302
The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 1000$$$) — the number of dishes in both days. Each of the next $$$n$$$ lines contains a string of $$$m$$$ symbols. The $$$j$$$-th symbol on $$$i$$$-th line is $$$a_{ij}$$$. All strings consist only of "&lt;", "&gt;" and "=".
2,000
The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print $$$n$$$ integers — evaluations of dishes from the first set, and on the third line print $$$m$$$ integers — evaluations of dishes from the second set.
standard output
PASSED
33fbb7814b8f2f9b5fe1a852a828bf08
train_001.jsonl
1550917200
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review  — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer.Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes.The gourmet tasted a set of $$$n$$$ dishes on the first day and a set of $$$m$$$ dishes on the second day. He made a table $$$a$$$ of size $$$n \times m$$$, in which he described his impressions. If, according to the expert, dish $$$i$$$ from the first set was better than dish $$$j$$$ from the second set, then $$$a_{ij}$$$ is equal to "&gt;", in the opposite case $$$a_{ij}$$$ is equal to "&lt;". Dishes also may be equally good, in this case $$$a_{ij}$$$ is "=".Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if $$$a_{ij}$$$ is "&lt;", then the number assigned to dish $$$i$$$ from the first set should be less than the number of dish $$$j$$$ from the second set, if $$$a_{ij}$$$ is "&gt;", then it should be greater, and finally if $$$a_{ij}$$$ is "=", then the numbers should be the same.Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible.
256 megabytes
import java.util.*; public class ACM { private static int find(int k, int[] fa) { fa[k] = (fa[k] == k ? k : find(fa[k], fa)); return fa[k]; } public static void main(String[] args) { int N = 2010; Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); ArrayList<String> a = new ArrayList<>(); ArrayList<Integer> res1 = new ArrayList<>(); ArrayList<ArrayList<Integer>> edges = new ArrayList<>(); int[] fa = new int[N]; int[] in = new int[N]; for (int i = 0; i < N; ++i) { res1.add(null); edges.add(new ArrayList<>()); } for (int i = 0; i < N; ++i) { fa[i] = i; } for (int i = 0; i < n; ++i) { String s = sc.next(); a.add(s); for (int j = 0; j < s.length(); ++j) { char c = s.charAt(j); if (c == '=') { fa[ find(j + n , fa)] = i; } } } for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { char c = a.get(i).charAt(j); int faI = find(i, fa); int faJ = find(n + j, fa); // System.out.println(i+","+j+"," + faI + "," + faJ); if (c == '<') { edges.get(faI).add(faJ); in[faJ]++; } else if (c == '>') { edges.get(faJ).add(faI); in[faI]++; } } } ArrayList<Integer> queue = new ArrayList<>(); for (int i = 0; i < n + m; ++i) { int fai = find(i, fa); if (in[fai] == 0 && !queue.contains(fai)) { queue.add(fai); res1.set(fai,1); } } while (!queue.isEmpty()) { int i = queue.get(queue.size() - 1); queue.remove(queue.size() - 1); for (Integer to : edges.get(i)) { in[to]--; if (in[to] == 0) { queue.add(to); res1.set(to,res1.get(i) + 1); } } } boolean f = false; for (int i = 0; i < n && !f; ++i) { for (int j = n; j < n + m && !f; ++j) { int fai = find(i, fa); int faj = find(j, fa); if (res1.get(fai) == null || res1.get(faj) == null) { f = true; break; } char c = a.get(i).charAt(j - n); if (c == '=' && res1.get(fai) != res1.get(faj)) { f = true; break; } else if (c == '>' && res1.get(fai) <= res1.get(faj)) { f = true; break; } else if (c == '<' && res1.get(fai) >= res1.get(faj)) { f = true; break; } } } // for (int i = 0; i < n + m; ++i) { // if (i == n) { // System.out.println(); // } // System.out.print(res1.get(find(i, fa)) + " "); // } if (f) { System.out.print("No"); } else { System.out.println("Yes"); for (int i = 0; i < n + m; ++i) { if (i == n) { System.out.println(); } System.out.print(res1.get(find(i, fa)) + " "); } } } }
Java
["3 4\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;", "3 3\n&gt;&gt;&gt;\n&lt;&lt;&lt;\n&gt;&gt;&gt;", "3 2\n==\n=&lt;\n=="]
2 seconds
["Yes\n2 2 2 \n1 1 1 1", "Yes\n3 1 3 \n2 2 2", "No"]
NoteIn the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be $$$2$$$, for all dishes of the first day.In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
Java 8
standard input
[ "dp", "greedy", "graphs", "dsu", "dfs and similar" ]
016bf7989ba58fdc3894a4cf3e0ac302
The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 1000$$$) — the number of dishes in both days. Each of the next $$$n$$$ lines contains a string of $$$m$$$ symbols. The $$$j$$$-th symbol on $$$i$$$-th line is $$$a_{ij}$$$. All strings consist only of "&lt;", "&gt;" and "=".
2,000
The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print $$$n$$$ integers — evaluations of dishes from the first set, and on the third line print $$$m$$$ integers — evaluations of dishes from the second set.
standard output
PASSED
5011ac6c76bffec42dac16013226f30a
train_001.jsonl
1550917200
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review  — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer.Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes.The gourmet tasted a set of $$$n$$$ dishes on the first day and a set of $$$m$$$ dishes on the second day. He made a table $$$a$$$ of size $$$n \times m$$$, in which he described his impressions. If, according to the expert, dish $$$i$$$ from the first set was better than dish $$$j$$$ from the second set, then $$$a_{ij}$$$ is equal to "&gt;", in the opposite case $$$a_{ij}$$$ is equal to "&lt;". Dishes also may be equally good, in this case $$$a_{ij}$$$ is "=".Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if $$$a_{ij}$$$ is "&lt;", then the number assigned to dish $$$i$$$ from the first set should be less than the number of dish $$$j$$$ from the second set, if $$$a_{ij}$$$ is "&gt;", then it should be greater, and finally if $$$a_{ij}$$$ is "=", then the numbers should be the same.Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible.
256 megabytes
import java.io.*; import java.util.*; public class cf { static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(Reader in) { br = new BufferedReader(in); } public FastScanner() { this(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] nextIntArray(int n) { int[] a = new int[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextInt(); } return a; } } static char[][] grid; static ArrayList<Integer>[] adj; static int[] val; static boolean[] vis; static boolean[] recStack; public static void main(String[] args) { FastScanner sc = new FastScanner(); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(), m = sc.nextInt(); adj = new ArrayList[n+m]; for(int i=0;i<n+m;i++) { adj[i] = new ArrayList<Integer>(); } grid = new char[n][m]; for(int i=0;i<n;i++) { grid[i] = sc.nextLine().toCharArray(); } vis = new boolean[n+m]; Arrays.fill(vis, false); val = new int[n+m]; recStack = new boolean[n+m]; Arrays.fill(recStack, false); DSU d = new DSU(n+m); d.createSet(); // organize sets based off equality for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(grid[i][j] == '=') { d.union(i, n+j); } } } // construct graph int pi = -1, pj = -1; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { pi = d.find(i); pj = d.find(n+j); if(grid[i][j] == '>') { adj[pi].add(pj); } else if(grid[i][j] == '<') { adj[pj].add(pi); } else { continue; } } } // check cyclic nature (self loops, etc) for(int i=0;i<n+m;i++) { if(!vis[d.find(i)]) { if(isCyclic(d.find(i))) { pw.println("No"); pw.close(); return; } } } // dfs Arrays.fill(vis, false); for(int i=0;i<n+m;i++) { if(!vis[d.find(i)]) { dfs(d.find(i)); } } pw.println("Yes"); for(int i=0;i<n;i++) { pw.print(val[d.find(i)] + " "); } pw.println(); for(int i=n;i<n+m;i++) { pw.print(val[d.find(i)] + " "); } pw.println(); pw.close(); } static int dfs(int v) { vis[v] = true; Iterator<Integer> itr = adj[v].iterator(); int max = 0; while(itr.hasNext()) { int next = itr.next(); if(!vis[next]) { max = Math.max(max, dfs(next)); } else { max = Math.max(max, val[next]); } } val[v] = max + 1; return val[v]; } static boolean isCyclic(int v) { if(recStack[v]) { return true; } if(vis[v]) { return false; } vis[v] = true; recStack[v] = true; Iterator<Integer> itr = adj[v].iterator(); while(itr.hasNext()) { int next = itr.next(); if(isCyclic(next)) { return true; } } recStack[v] = false; return false; } static class DSU { int n; int[] rank; int[] parent; public DSU(int n) { this.n = n; rank = new int[n]; parent = new int[n]; } public void createSet() { for(int i=0;i<n;i++) { parent[i] = i; rank[i] = 0; } } public int find(int p) { if(parent[p] == p) { return p; } parent[p] = find(parent[p]); return parent[p]; } public void union(int p, int q) { int i = find(p); int j = find(q); if(i == j) { return; } if(rank[i] > rank[j]) { parent[j] = i; } else if(rank[j] > rank[i]) { parent[i] = j; } else { parent[i] = j; rank[j]++; } } } }
Java
["3 4\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;", "3 3\n&gt;&gt;&gt;\n&lt;&lt;&lt;\n&gt;&gt;&gt;", "3 2\n==\n=&lt;\n=="]
2 seconds
["Yes\n2 2 2 \n1 1 1 1", "Yes\n3 1 3 \n2 2 2", "No"]
NoteIn the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be $$$2$$$, for all dishes of the first day.In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
Java 8
standard input
[ "dp", "greedy", "graphs", "dsu", "dfs and similar" ]
016bf7989ba58fdc3894a4cf3e0ac302
The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 1000$$$) — the number of dishes in both days. Each of the next $$$n$$$ lines contains a string of $$$m$$$ symbols. The $$$j$$$-th symbol on $$$i$$$-th line is $$$a_{ij}$$$. All strings consist only of "&lt;", "&gt;" and "=".
2,000
The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print $$$n$$$ integers — evaluations of dishes from the first set, and on the third line print $$$m$$$ integers — evaluations of dishes from the second set.
standard output
PASSED
824efdb6430707f1193a90c0a27d29df
train_001.jsonl
1550917200
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review  — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer.Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes.The gourmet tasted a set of $$$n$$$ dishes on the first day and a set of $$$m$$$ dishes on the second day. He made a table $$$a$$$ of size $$$n \times m$$$, in which he described his impressions. If, according to the expert, dish $$$i$$$ from the first set was better than dish $$$j$$$ from the second set, then $$$a_{ij}$$$ is equal to "&gt;", in the opposite case $$$a_{ij}$$$ is equal to "&lt;". Dishes also may be equally good, in this case $$$a_{ij}$$$ is "=".Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if $$$a_{ij}$$$ is "&lt;", then the number assigned to dish $$$i$$$ from the first set should be less than the number of dish $$$j$$$ from the second set, if $$$a_{ij}$$$ is "&gt;", then it should be greater, and finally if $$$a_{ij}$$$ is "=", then the numbers should be the same.Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible.
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.BufferedWriter; import java.util.Collection; 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.util.Queue; import java.io.BufferedReader; import java.util.ArrayDeque; 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); DGourmetChoice solver = new DGourmetChoice(); solver.solve(1, in, out); out.close(); } static class DGourmetChoice { public void solve(int testNumber, LightScanner in, LightWriter out) { // out.setBoolLabel(LightWriter.BoolLabel.YES_NO_FIRST_UP); int n = in.ints(), m = in.ints(); DGourmetChoice.Node[] nodes = new DGourmetChoice.Node[n + m]; for (int i = 0; i < n + m; i++) nodes[i] = new DGourmetChoice.Node(i); char[][] tbl = new char[n][]; for (int i = 0; i < n; i++) tbl[i] = in.string().toCharArray(); IntUnionFind uf = new IntUnionFind(n + m); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (tbl[i][j] == '=') uf.union(i, n + j); } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (tbl[i][j] == '=') continue; nodes[uf.find(i)].valid = nodes[uf.find(n + j)].valid = true; if (uf.find(i) == uf.find(n + j)) { //System.out.println("DIFF EQUAL"); out.noln(); return; } else if (tbl[i][j] == '<') { nodes[uf.find(i)].adj.add(nodes[uf.find(n + j)]); nodes[uf.find(n + j)].incoming++; } else { nodes[uf.find(n + j)].adj.add(nodes[uf.find(i)]); nodes[uf.find(i)].incoming++; } } } Queue<DGourmetChoice.Node> q = new ArrayDeque<>(); for (int i = 0; i < n + m; i++) if (nodes[i].incoming == 0) q.offer(nodes[i]); int cur = 1; while (!q.isEmpty()) { Queue<DGourmetChoice.Node> nq = new ArrayDeque<>(); while (!q.isEmpty()) { DGourmetChoice.Node node = q.poll(); node.order = cur; for (DGourmetChoice.Node next : node.adj) { if (next.valid && --next.incoming == 0) { nq.offer(next); } } } cur++; q = nq; } for (int i = 0; i < n + m; i++) { if (nodes[i].valid && nodes[i].incoming != 0) { //System.out.println("INCOMING 0 NODE " + i); out.noln(); return; } } int[] ansA = new int[n], ansB = new int[m]; int[] order = new int[n + m + 1]; out.yesln(); for (int i = 0; i < n; i++) { out.ans(nodes[uf.find(i)].order); } out.ln(); for (int i = 0; i < m; i++) { out.ans(nodes[uf.find(n + i)].order); } out.ln(); } private static class Node { int index; int incoming; boolean valid; int order = 0; List<DGourmetChoice.Node> adj = new ArrayList<>(); Node(int index) { this.index = index; } } } 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 IntUnionFind { private int groups; private final int[] nodes; private final int[] rank; public IntUnionFind(int n) { groups = n; nodes = new int[n]; Arrays.fill(nodes, -1); rank = new int[n]; } public int find(int i) { int ans = nodes[i]; if (ans < 0) { return i; } else { return nodes[i] = find(ans); } } public boolean union(int x, int y) { x = find(x); y = find(y); if (x == y) { return false; } else if (rank[x] < rank[y]) { nodes[y] += nodes[x]; nodes[x] = y; } else if (rank[x] == rank[y]) { rank[x]++; nodes[x] += nodes[y]; nodes[y] = x; } else { nodes[x] += nodes[y]; nodes[y] = x; } groups--; return true; } } static class LightWriter implements AutoCloseable { private final Writer out; private boolean autoflush = false; private boolean breaked = true; private LightWriter.BoolLabel boolLabel = LightWriter.BoolLabel.YES_NO_FIRST_UP; 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 ans(String s) { if (!breaked) { print(' '); } return print(s); } public LightWriter ans(int i) { return ans(Integer.toString(i)); } public LightWriter ans(boolean b) { return ans(boolLabel.transfer(b)); } public LightWriter yesln() { return ans(true).ln(); } public LightWriter noln() { return ans(false).ln(); } 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); } } public enum BoolLabel { YES_NO_FIRST_UP("Yes", "No"), YES_NO_ALL_UP("YES", "NO"), YES_NO_ALL_DOWN("yes", "no"), Y_N_ALL_UP("Y", "N"), POSSIBLE_IMPOSSIBLE_FIRST_UP("Possible", "Impossible"), POSSIBLE_IMPOSSIBLE_ALL_UP("POSSIBLE", "IMPOSSIBLE"), POSSIBLE_IMPOSSIBLE_ALL_DOWN("possible", "impossible"), FIRST_SECOND_FIRST_UP("First", "Second"), FIRST_SECOND_ALL_UP("FIRST", "SECOND"), FIRST_SECOND_ALL_DOWN("first", "second"), ALICE_BOB_FIRST_UP("Alice", "Bob"), ALICE_BOB_ALL_UP("ALICE", "BOB"), ALICE_BOB_ALL_DOWN("alice", "bob"), ; private final String positive; private final String negative; BoolLabel(String positive, String negative) { this.positive = positive; this.negative = negative; } private String transfer(boolean f) { return f ? positive : negative; } } } }
Java
["3 4\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;", "3 3\n&gt;&gt;&gt;\n&lt;&lt;&lt;\n&gt;&gt;&gt;", "3 2\n==\n=&lt;\n=="]
2 seconds
["Yes\n2 2 2 \n1 1 1 1", "Yes\n3 1 3 \n2 2 2", "No"]
NoteIn the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be $$$2$$$, for all dishes of the first day.In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
Java 8
standard input
[ "dp", "greedy", "graphs", "dsu", "dfs and similar" ]
016bf7989ba58fdc3894a4cf3e0ac302
The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 1000$$$) — the number of dishes in both days. Each of the next $$$n$$$ lines contains a string of $$$m$$$ symbols. The $$$j$$$-th symbol on $$$i$$$-th line is $$$a_{ij}$$$. All strings consist only of "&lt;", "&gt;" and "=".
2,000
The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print $$$n$$$ integers — evaluations of dishes from the first set, and on the third line print $$$m$$$ integers — evaluations of dishes from the second set.
standard output
PASSED
7566668ce6ac3d7ef0b6eb8ff0250e69
train_001.jsonl
1550917200
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review  — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer.Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes.The gourmet tasted a set of $$$n$$$ dishes on the first day and a set of $$$m$$$ dishes on the second day. He made a table $$$a$$$ of size $$$n \times m$$$, in which he described his impressions. If, according to the expert, dish $$$i$$$ from the first set was better than dish $$$j$$$ from the second set, then $$$a_{ij}$$$ is equal to "&gt;", in the opposite case $$$a_{ij}$$$ is equal to "&lt;". Dishes also may be equally good, in this case $$$a_{ij}$$$ is "=".Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if $$$a_{ij}$$$ is "&lt;", then the number assigned to dish $$$i$$$ from the first set should be less than the number of dish $$$j$$$ from the second set, if $$$a_{ij}$$$ is "&gt;", then it should be greater, and finally if $$$a_{ij}$$$ is "=", then the numbers should be the same.Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible.
256 megabytes
import java.util.*; import java.io.*; /* BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); Integer.parseInt(st.nextToken()); Long.parseLong(st.nextToken()); Scanner sc = new Scanner(System.in); */ public class Waw{ static HashMap<Integer,Node> luckup = new HashMap<Integer,Node>(); static class Node{ int id; int nb; LinkedList<Integer> neighbers = new LinkedList<Integer>(); int precedent; public Node(int i){ id = i; precedent = 0; nb = 0; } } static Node getNode(int id){ return luckup.get(id); } static void addEdges(int first,int second){ Node node = getNode(first); node.neighbers.add(second); getNode(second).precedent++; } static boolean bfs(int n,int m,boolean[] exist){ Node node; int nb = 1; LinkedList<Integer> nextToVisit = new LinkedList<Integer>(); boolean ok = true; while(ok){ ok = false; for(int i=1;i<=n+m;i++){ if(!exist[i]) continue; if(getNode(i).precedent==0 && getNode(i).nb==0) { ok = true; nextToVisit.add(i); } } while(!nextToVisit.isEmpty()){ node = getNode(nextToVisit.poll()); node.nb = nb; for(int i:node.neighbers){ getNode(i).precedent--; } } nb++; } for(int i=1;i<=n+m;i++){ if(!exist[i]) continue; if(getNode(i).nb==0) return false; } return true; } /* static boolean cycle(int n,int m){ boolean ok = false; boolean[] visited = new boolean[n+m+1]; for(int i=1;i<=n+m;i++){ Arrays.fill(visited,false); ok = cycle(i,n,m,visited); if(ok) return true; } return false; } static boolean cycle(int k,int n,int m,boolean[] visited){ LinkedList<Integer> nextToVisit = new LinkedList<Integer>(); Node node; nextToVisit.add(k); visited[k] = true; while(!nextToVisit.isEmpty()){ node = getNode(nextToVisit.poll()); for(int i:node.neighbers){ if(i==k) return true; if(visited[i]) continue; visited[i] = true; nextToVisit.add(i); } } return false; } */ static boolean isCyclicUtil(int i, boolean[] visited, boolean[] recStack) { // Mark the current node as visited and // part of recursion stack if (recStack[i]) return true; if (visited[i]) return false; visited[i] = true; recStack[i] = true; for (int c: getNode(i).neighbers) if (isCyclicUtil(c, visited, recStack)) return true; recStack[i] = false; return false; } static boolean isCyclic(int n,int m,boolean[] exist) { // Mark all the vertices as not visited and // not part of recursion stack boolean[] visited = new boolean[n+m+1]; boolean[] recStack = new boolean[n+m+1]; // Call the recursive helper function to // detect cycle in different DFS trees for (int i = 1; i <= n+m; i++) { if(!exist[i]) continue; if (isCyclicUtil(i, visited, recStack)) return true; } return false; } static class Subset{ int parent; int rank; public Subset(int p,int r){ parent = p; rank = r; } } static int find(Subset[] subsets,int i){ if(subsets[i].parent!=i) subsets[i].parent = find(subsets,subsets[i].parent); return subsets[i].parent; } static void union(Subset[] subsets,int x,int y){ int xroot = find(subsets,x); int yroot = find(subsets,y); if(subsets[xroot].rank<subsets[xroot].rank) subsets[xroot].parent = yroot; else if(subsets[yroot].rank<subsets[xroot].rank) subsets[yroot].parent = xroot; else{ subsets[xroot].parent = yroot; subsets[yroot].rank++; } } public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); Subset[] subsets = new Subset[n+m+1]; for(int i=1;i<=n+m;i++){ subsets[i] = new Subset(i,0); } PrintWriter out = new PrintWriter(System.out); String[] s = new String[n]; for(int i=0;i<n;i++){ s[i] = br.readLine(); } int x,y; for(int i=0;i<n;i++){ x = i+1; for(int j=0;j<m;j++){ y = n+j+1; if(s[i].charAt(j)=='='){ union(subsets,x,y); } } } boolean[] exist = new boolean[n+m+1]; for(int i=1;i<=n+m;i++){ if(subsets[i].parent==i) { exist[i] = true; luckup.put(i,new Node(i)); } } for(int i=0;i<n;i++){ x = i+1; for(int j=0;j<m;j++){ y = n+j+1; if(s[i].charAt(j)=='>'){ addEdges(find(subsets,y),find(subsets,x)); } else if(s[i].charAt(j)=='<'){ addEdges(find(subsets,x),find(subsets,y)); } } } boolean ok = false; //ok = cycle(n,m); ok = isCyclic(n,m,exist); if(ok){ out.println("No"); } else{ ok = bfs(n,m,exist); if(!ok){ out.println("No"); } else{ out.println("Yes"); out.print(getNode(find(subsets,1)).nb); for(int i=2;i<=n;i++) { out.print(" "+getNode(find(subsets,i)).nb); } out.println(""); out.print(getNode(find(subsets,n+1)).nb); for(int i=n+2;i<=n+m;i++) { out.print(" "+getNode(find(subsets,i)).nb); } out.println(""); } } out.flush(); } }
Java
["3 4\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;", "3 3\n&gt;&gt;&gt;\n&lt;&lt;&lt;\n&gt;&gt;&gt;", "3 2\n==\n=&lt;\n=="]
2 seconds
["Yes\n2 2 2 \n1 1 1 1", "Yes\n3 1 3 \n2 2 2", "No"]
NoteIn the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be $$$2$$$, for all dishes of the first day.In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
Java 8
standard input
[ "dp", "greedy", "graphs", "dsu", "dfs and similar" ]
016bf7989ba58fdc3894a4cf3e0ac302
The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 1000$$$) — the number of dishes in both days. Each of the next $$$n$$$ lines contains a string of $$$m$$$ symbols. The $$$j$$$-th symbol on $$$i$$$-th line is $$$a_{ij}$$$. All strings consist only of "&lt;", "&gt;" and "=".
2,000
The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print $$$n$$$ integers — evaluations of dishes from the first set, and on the third line print $$$m$$$ integers — evaluations of dishes from the second set.
standard output
PASSED
d59ed0809738f8e53ecc47717d155566
train_001.jsonl
1550917200
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review  — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer.Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes.The gourmet tasted a set of $$$n$$$ dishes on the first day and a set of $$$m$$$ dishes on the second day. He made a table $$$a$$$ of size $$$n \times m$$$, in which he described his impressions. If, according to the expert, dish $$$i$$$ from the first set was better than dish $$$j$$$ from the second set, then $$$a_{ij}$$$ is equal to "&gt;", in the opposite case $$$a_{ij}$$$ is equal to "&lt;". Dishes also may be equally good, in this case $$$a_{ij}$$$ is "=".Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if $$$a_{ij}$$$ is "&lt;", then the number assigned to dish $$$i$$$ from the first set should be less than the number of dish $$$j$$$ from the second set, if $$$a_{ij}$$$ is "&gt;", then it should be greater, and finally if $$$a_{ij}$$$ is "=", then the numbers should be the same.Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.List; import java.util.Arrays; import java.util.Iterator; import java.util.Collection; import java.util.HashMap; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); PrintWriter out = new PrintWriter(outputStream); DGourmetChoice solver = new DGourmetChoice(); solver.solve(1, in, out); out.close(); } static class DGourmetChoice { public void solve(int testNumber, FastReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); char[][] map = in.nextCharacterMap(n, m); DJSet djSet = new DJSet(n + m); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (map[i][j] == '=') { djSet.union(i, n + j); } } } HashMap<Integer, Integer> comp = new HashMap<>(); for (int i = 0; i < n + m; ++i) { int root = djSet.root(i); if (comp.containsKey(root)) continue; comp.put(root, comp.size()); } List<Integer>[] g = new List[n + m]; for (int i = 0; i < n + m; ++i) g[i] = new ArrayList<>(); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (map[i][j] == '>') { int f1 = djSet.root(i); f1 = comp.get(f1); int f2 = djSet.root(n + j); f2 = comp.get(f2); g[f2].add(f1); } else if (map[i][j] == '<') { int f1 = djSet.root(i); f1 = comp.get(f1); int f2 = djSet.root(n + j); f2 = comp.get(f2); g[f1].add(f2); } } } int[] indeg = new int[n + m]; for (int cur = 0; cur < n + m; ++cur) { for (Integer next : g[cur]) { ++indeg[next]; } } int[] score = new int[n + m]; ArrayUtils.fill(score, 1); int[] ret = new int[n + m]; int ptr = 0; //sources for (int i = 0; i < n + m; ++i) if (indeg[i] == 0) { ret[ptr++] = i; score[i] = 1; } //remaining nodes for (int start = 0; start < ptr; ++start) { for (Integer next : g[ret[start]]) { --indeg[next]; score[next] = Math.max(score[next], score[ret[start]] + 1); if (indeg[next] == 0) { ret[ptr++] = next; } } } //loop for (int i = 0; i < n; ++i) { if (indeg[i] > 0) { out.println("No"); return; } } out.println("Yes"); ArrayList<Integer> ans1 = new ArrayList<>(); ArrayList<Integer> ans2 = new ArrayList<>(); for (int i = 0; i < n + m; ++i) { int r = djSet.root(i); r = comp.get(r); if (i < n) ans1.add(score[r]); if (i >= n) ans2.add(score[r]); } ArrayUtils.printArray(out, ans1); ArrayUtils.printArray(out, ans2); } } static class FastReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar; private int pnumChars; public FastReader(InputStream stream) { this.stream = stream; } private int pread() { if (pnumChars == -1) { throw new InputMismatchException(); } if (curChar >= pnumChars) { curChar = 0; try { pnumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (pnumChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = pread(); while (isSpaceChar(c)) c = pread(); int sgn = 1; if (c == '-') { sgn = -1; c = pread(); } int res = 0; do { if (c == ',') { c = pread(); } if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = pread(); } while (!isSpaceChar(c)); return res * sgn; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public char nextCharacter() { int c = pread(); while (isSpaceChar(c)) c = pread(); return (char) c; } public char[] nextCharacterArray(int n) { char[] chars = new char[n]; for (int i = 0; i < n; i++) { chars[i] = nextCharacter(); } return chars; } public char[][] nextCharacterMap(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) { map[i] = nextCharacterArray(m); } return map; } } static class DJSet { public int[] upper; public int count; public DJSet(int n) { upper = new int[n]; count = n; Arrays.fill(upper, -1); } public int root(int x) { return upper[x] < 0 ? x : (upper[x] = root(upper[x])); } public boolean union(int x, int y) { x = root(x); y = root(y); if (x != y) { if (upper[y] < upper[x]) { int d = x; x = y; y = d; } upper[x] += upper[y]; upper[y] = x; --count; return true; } return false; } } static class ArrayUtils { public static void fill(int[] array, int value) { Arrays.fill(array, value); } public static <T> void printArray(PrintWriter out, Collection<T> array) { if (array.size() == 0) return; int size = array.size(); Iterator<T> iterator = array.iterator(); int ct = 0; for (; ct < size && iterator.hasNext(); ct++) { if (ct != 0) out.print(" "); out.print(iterator.next()); } out.println(); } } }
Java
["3 4\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;", "3 3\n&gt;&gt;&gt;\n&lt;&lt;&lt;\n&gt;&gt;&gt;", "3 2\n==\n=&lt;\n=="]
2 seconds
["Yes\n2 2 2 \n1 1 1 1", "Yes\n3 1 3 \n2 2 2", "No"]
NoteIn the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be $$$2$$$, for all dishes of the first day.In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
Java 8
standard input
[ "dp", "greedy", "graphs", "dsu", "dfs and similar" ]
016bf7989ba58fdc3894a4cf3e0ac302
The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 1000$$$) — the number of dishes in both days. Each of the next $$$n$$$ lines contains a string of $$$m$$$ symbols. The $$$j$$$-th symbol on $$$i$$$-th line is $$$a_{ij}$$$. All strings consist only of "&lt;", "&gt;" and "=".
2,000
The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print $$$n$$$ integers — evaluations of dishes from the first set, and on the third line print $$$m$$$ integers — evaluations of dishes from the second set.
standard output
PASSED
8ca39f3b236e049b25711ac9ef5e5d3c
train_001.jsonl
1550917200
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review  — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer.Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes.The gourmet tasted a set of $$$n$$$ dishes on the first day and a set of $$$m$$$ dishes on the second day. He made a table $$$a$$$ of size $$$n \times m$$$, in which he described his impressions. If, according to the expert, dish $$$i$$$ from the first set was better than dish $$$j$$$ from the second set, then $$$a_{ij}$$$ is equal to "&gt;", in the opposite case $$$a_{ij}$$$ is equal to "&lt;". Dishes also may be equally good, in this case $$$a_{ij}$$$ is "=".Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if $$$a_{ij}$$$ is "&lt;", then the number assigned to dish $$$i$$$ from the first set should be less than the number of dish $$$j$$$ from the second set, if $$$a_{ij}$$$ is "&gt;", then it should be greater, and finally if $$$a_{ij}$$$ is "=", then the numbers should be the same.Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible.
256 megabytes
import java.util.*; public class Main { static ArrayList<Node> V = new ArrayList<>(); /** * @param args the command line arguments */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); char[][] c = new char[n][m]; for (int i = 0; i < n; i++) { String line = sc.next(); for (int j = 0; j < m; j++) { c[i][j] = line.charAt(j); } } int[] a = new int[n]; int[] b = new int[m]; Arrays.fill(a, -1); Arrays.fill(b, -1); for (int i = 0; i < n; i++) { if (a[i] == -1) { ArrayDeque<Integer> qa = new ArrayDeque<>(); ArrayDeque<Integer> qb = new ArrayDeque<>(); qa.add(i); int count = V.size(); V.add(new Node()); while (!qa.isEmpty() || !qb.isEmpty()) { if (!qa.isEmpty()) { int j = qa.removeFirst(); if (a[j] != -1) continue; a[j] = count; for (int k = 0; k < m; k++) { if (c[j][k] == '=') { qb.add(k); } else if (c[j][k] == '>') { V.get(count).adjFirstB.add(k); } } } else { int j = qb.removeFirst(); if (b[j] != -1) continue; b[j] = count; for (int k = 0; k < n; k++) { if (c[k][j] == '=') { qa.add(k); } else if (c[k][j] == '<') { V.get(count).adjFirstA.add(k); } } } } } } for (int i = 0; i < m; i++) { if (b[i] == -1) { ArrayDeque<Integer> qa = new ArrayDeque<>(); ArrayDeque<Integer> qb = new ArrayDeque<>(); qb.add(i); int count = V.size(); V.add(new Node()); while (!qa.isEmpty() || !qb.isEmpty()) { if (!qa.isEmpty()) { int j = qa.removeFirst(); if (a[j] != -1) continue; a[j] = count; for (int k = 0; k < m; k++) { if (c[j][k] == '=') { qb.add(k); } else if (c[j][k] == '>') { V.get(count).adjFirstB.add(k); } } } else { int j = qb.removeFirst(); if (b[j] != -1) continue; b[j] = count; for (int k = 0; k < n; k++) { if (c[k][j] == '=') { qa.add(k); } else if (c[k][j] == '<') { V.get(count).adjFirstA.add(k); } } } } } } for (Node v : V) { HashSet<Integer> adj = new HashSet<>(); for (int i : v.adjFirstA) { adj.add(a[i]); } for (int i : v.adjFirstB) { adj.add(b[i]); } for (int i : adj) { v.adj.add(i); } } int[] scoreA = new int[n]; int[] scoreB = new int[m]; for (int i = 0; i < n; i++) { scoreA[i] = getScore(a[i]); } for (int i = 0; i < m; i++) { scoreB[i] = getScore(b[i]); } boolean pos = true; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (c[i][j] == '>' && scoreA[i] <= scoreB[j]) pos = false; if (c[i][j] == '<' && scoreA[i] >= scoreB[j]) pos = false; if (c[i][j] == '=' && scoreA[i] != scoreB[j]) pos = false; } } if (pos) { System.out.println("Yes"); for (int i = 0; i < n; i++) { System.out.print(scoreA[i] + " "); } System.out.println(); for (int i = 0; i < m; i++) { System.out.print(scoreB[i] + " "); } System.out.println(); } else { System.out.println("No"); } } static int getScore(int i) { if (V.get(i).visited) return V.get(i).score; V.get(i).visited = true; for (int j : V.get(i).adj) { V.get(i).score = Math.max(V.get(i).score, getScore(j) + 1); } return V.get(i).score; } } class Node { ArrayList<Integer> adjFirstA = new ArrayList<>(); ArrayList<Integer> adjFirstB = new ArrayList<>(); ArrayList<Integer> adj = new ArrayList<>(); int score = 1; boolean visited = false; }
Java
["3 4\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;", "3 3\n&gt;&gt;&gt;\n&lt;&lt;&lt;\n&gt;&gt;&gt;", "3 2\n==\n=&lt;\n=="]
2 seconds
["Yes\n2 2 2 \n1 1 1 1", "Yes\n3 1 3 \n2 2 2", "No"]
NoteIn the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be $$$2$$$, for all dishes of the first day.In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
Java 8
standard input
[ "dp", "greedy", "graphs", "dsu", "dfs and similar" ]
016bf7989ba58fdc3894a4cf3e0ac302
The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 1000$$$) — the number of dishes in both days. Each of the next $$$n$$$ lines contains a string of $$$m$$$ symbols. The $$$j$$$-th symbol on $$$i$$$-th line is $$$a_{ij}$$$. All strings consist only of "&lt;", "&gt;" and "=".
2,000
The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print $$$n$$$ integers — evaluations of dishes from the first set, and on the third line print $$$m$$$ integers — evaluations of dishes from the second set.
standard output
PASSED
3cc9bae7bdfa6e70607470edea86b510
train_001.jsonl
1550917200
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review  — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer.Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes.The gourmet tasted a set of $$$n$$$ dishes on the first day and a set of $$$m$$$ dishes on the second day. He made a table $$$a$$$ of size $$$n \times m$$$, in which he described his impressions. If, according to the expert, dish $$$i$$$ from the first set was better than dish $$$j$$$ from the second set, then $$$a_{ij}$$$ is equal to "&gt;", in the opposite case $$$a_{ij}$$$ is equal to "&lt;". Dishes also may be equally good, in this case $$$a_{ij}$$$ is "=".Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if $$$a_{ij}$$$ is "&lt;", then the number assigned to dish $$$i$$$ from the first set should be less than the number of dish $$$j$$$ from the second set, if $$$a_{ij}$$$ is "&gt;", then it should be greater, and finally if $$$a_{ij}$$$ is "=", then the numbers should be the same.Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.FilterInputStream; import java.io.BufferedInputStream; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Jenish */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; ScanReader in = new ScanReader(inputStream); PrintWriter out = new PrintWriter(outputStream); DGourmetChoice solver = new DGourmetChoice(); solver.solve(1, in, out); out.close(); } static class DGourmetChoice { int[] arr; int[] size; ArrayList<Integer>[] arrayList; int[] visited; boolean[] visit; int[] val; int n; int m; public void solve(int testNumber, ScanReader in, PrintWriter out) { n = in.scanInt(); m = in.scanInt(); char ccc[][] = new char[n][m]; arrayList = new ArrayList[n + m]; visited = new int[n + m]; for (int i = 0; i < n + m; i++) arrayList[i] = new ArrayList<>(); val = new int[n + m + 1]; arr = new int[n + m + 1]; size = new int[n + m + 1]; for (int i = 0; i < m + n; i++) { arr[i] = i; size[i] = 1; } for (int i = 0; i < n; i++) ccc[i] = in.scanString().toCharArray(); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (ccc[i][j] == '=') { if (root(i) != root(j + n)) { w_union(i, j + n); } } } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (ccc[i][j] == '>') { arrayList[root(i)].add(root(j + n)); } else if (ccc[i][j] == '<') { arrayList[root(j + n)].add(root(i)); } } } if (checkLoop()) { out.println("No"); return; } visit = new boolean[n + m]; for (int i = 0; i < n + m; i++) dfs(i); out.println("Yes"); for (int i = 0; i < n; i++) out.print(val[root(i)] + " "); out.println(); for (int i = n; i < n + m; i++) out.print(val[root(i)] + " "); } int root(int i) { while (arr[i] != i) { i = arr[i]; } return i; } void w_union(int A, int B) { int root_A = root(A); int root_B = root(B); if (size[root_A] < size[root_B]) { arr[root_A] = arr[root_B]; size[root_B] += size[root_A]; size[root_A] = 0; } else { arr[root_B] = arr[root_A]; size[root_A] += size[root_B]; size[root_B] = 0; } } boolean findLoop(int v) { if (visited[v] == 1) return true; if (visited[v] == 2) return false; visited[v] = 1; for (int it : arrayList[v]) { if (findLoop(it)) return true; } visited[v] = 2; return false; } boolean checkLoop() { visited = new int[n + m + 1]; for (int i = 0; i < n + m; i++) { if (visited[i] == 0 && findLoop(i)) return true; } return false; } void dfs(int u) { if (visit[u]) return; visit[u] = true; for (int it : arrayList[u]) dfs(it); val[u] = 1; for (int it : arrayList[u]) val[u] = Math.max(val[u], val[it] + 1); } } 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 I = 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') { I *= 10; I += n - '0'; n = scan(); } } return neg * I; } public String scanString() { int c = scan(); while (isWhiteSpace(c)) c = scan(); StringBuilder RESULT = new StringBuilder(); do { RESULT.appendCodePoint(c); c = scan(); } while (!isWhiteSpace(c)); return RESULT.toString(); } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; else return false; } } }
Java
["3 4\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;", "3 3\n&gt;&gt;&gt;\n&lt;&lt;&lt;\n&gt;&gt;&gt;", "3 2\n==\n=&lt;\n=="]
2 seconds
["Yes\n2 2 2 \n1 1 1 1", "Yes\n3 1 3 \n2 2 2", "No"]
NoteIn the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be $$$2$$$, for all dishes of the first day.In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
Java 8
standard input
[ "dp", "greedy", "graphs", "dsu", "dfs and similar" ]
016bf7989ba58fdc3894a4cf3e0ac302
The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 1000$$$) — the number of dishes in both days. Each of the next $$$n$$$ lines contains a string of $$$m$$$ symbols. The $$$j$$$-th symbol on $$$i$$$-th line is $$$a_{ij}$$$. All strings consist only of "&lt;", "&gt;" and "=".
2,000
The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print $$$n$$$ integers — evaluations of dishes from the first set, and on the third line print $$$m$$$ integers — evaluations of dishes from the second set.
standard output
PASSED
6b1b4711dfb8b43a1772a4dd802d8684
train_001.jsonl
1550917200
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review  — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer.Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes.The gourmet tasted a set of $$$n$$$ dishes on the first day and a set of $$$m$$$ dishes on the second day. He made a table $$$a$$$ of size $$$n \times m$$$, in which he described his impressions. If, according to the expert, dish $$$i$$$ from the first set was better than dish $$$j$$$ from the second set, then $$$a_{ij}$$$ is equal to "&gt;", in the opposite case $$$a_{ij}$$$ is equal to "&lt;". Dishes also may be equally good, in this case $$$a_{ij}$$$ is "=".Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if $$$a_{ij}$$$ is "&lt;", then the number assigned to dish $$$i$$$ from the first set should be less than the number of dish $$$j$$$ from the second set, if $$$a_{ij}$$$ is "&gt;", then it should be greater, and finally if $$$a_{ij}$$$ is "=", then the numbers should be the same.Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible.
256 megabytes
import java.util.*; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; public class tr0 { static PrintWriter out; static StringBuilder sb; static int mod = 1000000007; static long inf = (long) 1e16; static int[][] ad; static int n, m; static long[][][] memo; static HashSet<Integer> h; static long[] a; static HashSet<Integer> leaves; static TreeMap<pair, Long> dp; static ArrayList<Long> ar; static boolean f; public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); out = new PrintWriter(System.out); n = sc.nextInt(); m = sc.nextInt(); unionfind uf = new unionfind(n + m); char[][] g = new char[n][m]; for (int i = 0; i < n; i++) g[i] = sc.nextLine().toCharArray(); f = true; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (g[i][j] == '>') { if (uf.sameSet(i, j + n)) f = false; uf.ha[uf.findSet(j + n)].add(uf.findSet(i)); } if (g[i][j] == '<') { if (uf.sameSet(i, j + n)) f = false; uf.ha[uf.findSet(i)].add(uf.findSet(j + n)); } if (g[i][j] == '=') { uf.combine(i, j + n); } } } uf.bfs(); if (!f) { System.out.println("No"); return; } System.out.println("Yes"); int[] pr1 = new int[n]; for (int i = 0; i < n; i++) pr1[i] = uf.ans[uf.findSet(i)]; int[] pr2 = new int[m]; for (int i = 0; i < m; i++) pr2[i] = uf.ans[uf.findSet(i + n)]; for (int i = 0; i < n; i++) out.print(pr1[i] + " "); out.println(); for (int i = 0; i < m; i++) out.print(pr2[i] + " "); out.close(); } static class unionfind { int[] p; int[] size; int[] max; int num; int[] ans; HashSet<Integer>[] ha; unionfind(int n) { p = new int[n]; size = new int[n]; ha = new HashSet[n]; ans = new int[n]; for (int i = 0; i < n; i++) { p[i] = i; ha[i] = new HashSet<>(); } Arrays.fill(size, 1); num = n; } int findSet(int v) { if (v == p[v]) return v; p[v] = findSet(p[v]); return p[v]; } boolean sameSet(int a, int b) { a = findSet(a); b = findSet(b); if (a == b) return true; return false; } boolean combine(int a, int b) { a = findSet(a); b = findSet(b); if (a == b) return true; // System.out.println(num+" ppp"); num--; if (size[a] > size[b]) { p[b] = a; size[a] += size[b]; size[b] = -1; ha[a].addAll(ha[b]); ha[b].clear(); } else { p[a] = b; size[b] += size[a]; size[a] = -1; ha[b].addAll(ha[a]); ha[a].clear(); } return false; } void bfs() { //System.out.println(Arrays.toString(ha)); // System.out.println(Arrays.toString(size)); int si = size.length; int[] dist = new int[si]; Queue<Integer> q = new LinkedList(); Arrays.fill(dist, -1); int[] pa = new int[si]; for (int i = 0; i < si; i++) if (size[i] == -1) continue; else { for (int v : ha[i]) pa[findSet(v)]++; } for (int i = 0; i < si; i++) if (pa[i] == 0 && size[i] != -1) { q.add(findSet(i)); ans[findSet(i)] = dist[findSet(i)] = 1; } // System.out.println(q); // System.out.println(Arrays.toString(pa)); while (!q.isEmpty()) { int u = q.poll(); for (int v : ha[u]) { // System.out.println(u+" "+findSet(v)+" "+pa[findSet(v)]); pa[findSet(v)]--; if(pa[findSet(v)]==0) { q.add(findSet(findSet(v))); ans[findSet(v)] = ans[findSet(u)] + 1; } } } for (int i = 0; i < si; i++) if (pa[i] > 0) f = false; } } static class pair implements Comparable<pair> { int to; long number; pair(int t, long n) { number = n; to = t; } public String toString() { return to + " " + number; } @Override public int compareTo(pair o) { if (to == o.to) return Long.compare(number, o.number); return to - o.to; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public int[] nextArrInt(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextArrLong(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } }
Java
["3 4\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;", "3 3\n&gt;&gt;&gt;\n&lt;&lt;&lt;\n&gt;&gt;&gt;", "3 2\n==\n=&lt;\n=="]
2 seconds
["Yes\n2 2 2 \n1 1 1 1", "Yes\n3 1 3 \n2 2 2", "No"]
NoteIn the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be $$$2$$$, for all dishes of the first day.In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
Java 8
standard input
[ "dp", "greedy", "graphs", "dsu", "dfs and similar" ]
016bf7989ba58fdc3894a4cf3e0ac302
The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 1000$$$) — the number of dishes in both days. Each of the next $$$n$$$ lines contains a string of $$$m$$$ symbols. The $$$j$$$-th symbol on $$$i$$$-th line is $$$a_{ij}$$$. All strings consist only of "&lt;", "&gt;" and "=".
2,000
The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print $$$n$$$ integers — evaluations of dishes from the first set, and on the third line print $$$m$$$ integers — evaluations of dishes from the second set.
standard output
PASSED
1ced771c7ee2a6a7a9f46e160af806f0
train_001.jsonl
1550917200
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review  — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer.Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes.The gourmet tasted a set of $$$n$$$ dishes on the first day and a set of $$$m$$$ dishes on the second day. He made a table $$$a$$$ of size $$$n \times m$$$, in which he described his impressions. If, according to the expert, dish $$$i$$$ from the first set was better than dish $$$j$$$ from the second set, then $$$a_{ij}$$$ is equal to "&gt;", in the opposite case $$$a_{ij}$$$ is equal to "&lt;". Dishes also may be equally good, in this case $$$a_{ij}$$$ is "=".Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if $$$a_{ij}$$$ is "&lt;", then the number assigned to dish $$$i$$$ from the first set should be less than the number of dish $$$j$$$ from the second set, if $$$a_{ij}$$$ is "&gt;", then it should be greater, and finally if $$$a_{ij}$$$ is "=", then the numbers should be the same.Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible.
256 megabytes
import java.io.*; import java.util.*; public class MainClass { static int n, m; static char[][] A; static BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); static StringBuilder stringBuilder = new StringBuilder(); static boolean[] visited; static int[] ids; static List<Integer>[] adj; static List<Integer> postOrder = new ArrayList<>(); static Set<Integer> set = new HashSet<>(); public static void main(String[] args)throws IOException { String s1[] = in.readLine().split(" "); n = Integer.parseInt(s1[0]); m = Integer.parseInt(s1[1]); A = new char[n][m]; visited = new boolean[n + m]; ids = new int[n + m]; adj = new ArrayList[n + m]; for (int i=0;i<n + m;i++) adj[i] = new ArrayList<>(); for (int i=0;i<n;i++) A[i] = in.readLine().toCharArray(); for (int i=0;i<n + m;i++) ids[i] = i; solve(); } public static void solve() { for (int i=0;i<n;i++) for (int j=0;j<m;j++) if (A[i][j] == '=') ids[i] = ids[n + j] = Math.min(ids[i], ids[n + j]); for (int i=0;i<n;i++) for (int j=0;j<m;j++) if (A[i][j] != '=') { if (ids[i] == ids[n + j]) { System.out.println("No"); System.exit(0); } if (A[i][j] == '>') adj[ids[n + j]].add(ids[i]); else adj[ids[i]].add(ids[n + j]); } for (int i=0;i<n + m;i++) if (!visited[i]) explore(i, -1); long[] dp = new long[n + m]; for (int i: postOrder) { dp[i] = 1L; long max = 0L; for (int u: adj[i]) max = Math.max(dp[u], max); dp[i] += max; } long max = 1L; for (int i=0;i<n + m;i++) max = Math.max(max, dp[i]); stringBuilder.append("Yes\n"); for (int i=0;i<n;i++) stringBuilder.append(max - dp[ids[i]] + 1).append(" "); stringBuilder.append("\n"); for (int i=0;i<m;i++) stringBuilder.append(max - dp[ids[n + i]] + 1).append(" "); System.out.println(stringBuilder); } public static void explore(int v, int par) { visited[v] = true; set.add(v); for (int u: adj[v]) { if (u == par) continue; else if (!visited[u]) explore(u, v); else if (set.contains(u)) { System.out.println("No"); System.exit(0); } } set.remove(v); postOrder.add(v); } } class Reader { final private int BUFFER_SIZE = 1 << 16; private final DataInputStream din; private final byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } }
Java
["3 4\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;", "3 3\n&gt;&gt;&gt;\n&lt;&lt;&lt;\n&gt;&gt;&gt;", "3 2\n==\n=&lt;\n=="]
2 seconds
["Yes\n2 2 2 \n1 1 1 1", "Yes\n3 1 3 \n2 2 2", "No"]
NoteIn the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be $$$2$$$, for all dishes of the first day.In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
Java 8
standard input
[ "dp", "greedy", "graphs", "dsu", "dfs and similar" ]
016bf7989ba58fdc3894a4cf3e0ac302
The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 1000$$$) — the number of dishes in both days. Each of the next $$$n$$$ lines contains a string of $$$m$$$ symbols. The $$$j$$$-th symbol on $$$i$$$-th line is $$$a_{ij}$$$. All strings consist only of "&lt;", "&gt;" and "=".
2,000
The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print $$$n$$$ integers — evaluations of dishes from the first set, and on the third line print $$$m$$$ integers — evaluations of dishes from the second set.
standard output
PASSED
dc978a3530e1a45272d432ef18babfe0
train_001.jsonl
1550917200
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review  — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer.Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes.The gourmet tasted a set of $$$n$$$ dishes on the first day and a set of $$$m$$$ dishes on the second day. He made a table $$$a$$$ of size $$$n \times m$$$, in which he described his impressions. If, according to the expert, dish $$$i$$$ from the first set was better than dish $$$j$$$ from the second set, then $$$a_{ij}$$$ is equal to "&gt;", in the opposite case $$$a_{ij}$$$ is equal to "&lt;". Dishes also may be equally good, in this case $$$a_{ij}$$$ is "=".Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if $$$a_{ij}$$$ is "&lt;", then the number assigned to dish $$$i$$$ from the first set should be less than the number of dish $$$j$$$ from the second set, if $$$a_{ij}$$$ is "&gt;", then it should be greater, and finally if $$$a_{ij}$$$ is "=", then the numbers should be the same.Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible.
256 megabytes
import java.io.*; import java.util.*; public class D { static class DSU { private final int n; private final int[] root; DSU(int n) { this.n = n; root = new int[n + 1]; for (int i = 0; i <= n; i++) { root[i] = i; } } int findRoot(int x) { if (root[x] == x) { return x; } return root[x] = findRoot(root[x]); } void unite(int x, int y) { x = findRoot(x); y = findRoot(y); if (x != y) { root[x] = y; } } } public static void main(String[] args) throws IOException { try (Input input = new StandardInput(); PrintWriter writer = new PrintWriter(System.out)) { int n = input.nextInt(), m = input.nextInt(); char[][] g = new char[n][]; DSU dsu = new DSU(n + m); for (int i = 0; i < n; i++) { g[i] = input.next().toCharArray(); for (int j = 0; j < m; j++) { if (g[i][j] == '=') { dsu.unite(i, n + j); } } } int[][] graph = new int[n + m][n + m]; int[] incoming = new int[n + m]; for (int i = 0; i < n; i++) { int u = dsu.findRoot(i); for (int j = 0; j < m; j++) { if (g[i][j] == '=') { continue; } int v = dsu.findRoot(n + j); if (u == v) { writer.println("No"); return; } if (g[i][j] == '<' && graph[u][v] == 0) { graph[u][v] = 1; incoming[v]++; } else if (g[i][j] == '>' && graph[v][u] == 0) { graph[v][u] = 1; incoming[u]++; } } } int[] grade = new int[n + m]; Queue<Integer> q = new LinkedList<>(); for (int i = 0; i < n + m; i++) { if (incoming[i] == 0 && dsu.findRoot(i) == i) { q.add(i); grade[i] = 1; } } boolean[] visited = new boolean[n + m]; while (!q.isEmpty()) { int u = q.poll(); visited[u] = true; for (int v = 0; v < n + m; v++) { if (graph[u][v] == 0) { continue; } incoming[v]--; grade[v] = Math.max(grade[v], grade[u] + 1); if (incoming[v] == 0) { q.add(v); } } } for (int i = 0; i < n + m; i++) { int root = dsu.findRoot(i); if (root != i) { grade[i] = grade[root]; } if (grade[i] == 0 || !visited[root]) { writer.println("No"); return; } } writer.println("Yes"); for (int[] x : new int[][]{{0, n}, {n, m}}) { int offset = x[0]; int count = x[1]; for (int i = 0; i < count; i++) { writer.print(grade[i + offset] + " "); } writer.println(); } } } interface Input extends Closeable { String next() throws IOException; default int nextInt() throws IOException { return Integer.parseInt(next()); } default long nextLong() throws IOException { return Long.parseLong(next()); } } private static class StandardInput implements Input { private final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); private StringTokenizer stringTokenizer; @Override public void close() throws IOException { reader.close(); } @Override public String next() throws IOException { if (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) { stringTokenizer = new StringTokenizer(reader.readLine()); } return stringTokenizer.nextToken(); } } }
Java
["3 4\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;\n&gt;&gt;&gt;&gt;", "3 3\n&gt;&gt;&gt;\n&lt;&lt;&lt;\n&gt;&gt;&gt;", "3 2\n==\n=&lt;\n=="]
2 seconds
["Yes\n2 2 2 \n1 1 1 1", "Yes\n3 1 3 \n2 2 2", "No"]
NoteIn the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be $$$2$$$, for all dishes of the first day.In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
Java 8
standard input
[ "dp", "greedy", "graphs", "dsu", "dfs and similar" ]
016bf7989ba58fdc3894a4cf3e0ac302
The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 1000$$$) — the number of dishes in both days. Each of the next $$$n$$$ lines contains a string of $$$m$$$ symbols. The $$$j$$$-th symbol on $$$i$$$-th line is $$$a_{ij}$$$. All strings consist only of "&lt;", "&gt;" and "=".
2,000
The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print $$$n$$$ integers — evaluations of dishes from the first set, and on the third line print $$$m$$$ integers — evaluations of dishes from the second set.
standard output
PASSED
8302062f5c1e214a9758e5a5dc8b2e7b
train_001.jsonl
1414170000
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≤ li ≤ ri ≤ n) meaning that value should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist.Expression x&amp;y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&amp;", in Pascal — as "and".
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; public class InterestingArray_CodeForces { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String []temp = br.readLine().split(" "); int n = Integer.parseInt(temp[0]); int m = Integer.parseInt(temp[1]); String []updates=new String[m]; int N=1; while(N<n){ N<<=1; } long input[]=new long[N+1]; //Arrays.fill(input, (1<<31)-1); // SegmentT stt = new SegmentT(input); andSegTree and=new andSegTree(input); long num []=new long [N+1]; // one based for(int i=0;i<m;i++){ String s = br.readLine(); updates[i]=s; temp = s.split(" "); int start = Integer.parseInt(temp[0]); int end = Integer.parseInt(temp[1]); long x = Integer.parseInt(temp[2]); // stt.updateRange(start, end, x); and.updateRange(start, end, x); //for(int j=start;j<=end;j++){ // num[j]|=x; // } } //and.query(1, 1); //and.query(and.N-1, and.N-1); and.all(1, 1, and.N); //for(int i=1;i<and.Stree.length;i++){ //System.out.print(and.Stree[i]+" "); //} //System.out.println(); for(int i=1;i<n+1;i++){ //num[i]=and.query(i, i); num[i]=and.Stree[and.N-1+i]; //System.out.println(num[i]); } // andSegTree st = new andSegTree(num); // for(int i=1;i<st.Stree.length;i++){ // System.out.print(st.Stree[i]+" "); // } //System.out.println(); for(int i=0;i<m;i++){ String []r = updates[i].split(" "); int start = Integer.parseInt(r[0]); int end = Integer.parseInt(r[1]); int x = Integer.parseInt(r[2]); if(and.query(start, end)!=x){ System.out.println("NO"); System.exit(0); } } System.out.println("YES"); for(int i=1;i<n+1;i++){ System.out.print(num[i]); if(i!=n) System.out.print(" "); } } } //class SegmentT { // int N; // long [] array,STree,lazy; // public SegmentT(long []input){ // N=input.length-1; // array=input; // STree= new long[N<<1]; // lazy=new long[N<<1]; // build(1,1,N); // } // public void build (int nodeIndex, int begin, int end){ // if(begin==end) // STree[nodeIndex]=array[begin]; // else { // int leftNode=2*nodeIndex; // int rightNode=2*nodeIndex+1; // int mid = (begin+end)/2; // build(leftNode, begin, mid); // build(rightNode,mid+1,end); // STree[nodeIndex]=STree[leftNode]+STree[rightNode]; // } // } // public void probagate(int nodeIndex , int begin , int end){ // int leftChild = 2*nodeIndex ; // int rightChild = 2*nodeIndex+1 ; // lazy[leftChild]|=lazy[nodeIndex]; // lazy[rightChild]|=lazy[nodeIndex]; // int mid = (begin+end)/2; // STree[leftChild]|=(mid-begin+1)*lazy[nodeIndex]; // STree[rightChild]|=(end-mid)*lazy[nodeIndex]; // lazy[nodeIndex]=0; // } // // public void updatePoint(int index, int value ){ // int nodeIndex = index+N-1; // STree[nodeIndex]+=value; // while(nodeIndex>1){ // nodeIndex/=2; // STree[nodeIndex]=STree[nodeIndex*2]+STree[nodeIndex*2+1]; // } // } // // public long query(int i,int j){ // return query(1,1,N,i,j); // } // // public long query(int node,int begin, int end, int i, int j){ // if(end<i||begin>j) // return 0; // if(begin >=i&& end<=j ) // return STree[node]; // int mid = (begin+end)/2; // probagate(node, begin ,end); // long q1=query(node*2,begin , mid, i ,j); // long q2=query(node*2+1,mid+1,end,i ,j ); // return q1|q2; // } // // public void updateRange(int i , int j , long val){ // updateRange(1,1,N,i,j,val); // } // // public void updateRange(int node, int begin, int end, int i,int j ,long val){ // if(end<i || begin>j) // return; // if(begin>=i &&end<=j){ // STree[node]|=val;; // lazy[node]|=val; // } // else // { // int mid = (begin+end)/2; // probagate(node, begin ,end); // updateRange(node*2, begin,mid, i, j, val); // updateRange(node*2+1, mid+1, end, i, j, val); // STree[node]=STree[node*2]|STree[node*2+1]; // } // } //} class andSegTree { long []Stree; long []lazy; long []array; int N; public andSegTree(long [] input){ N = input.length-1; array= input; Stree= new long [N<<1]; lazy = new long [N<<1]; build(1,1,N); } public void build(int node, int b, int e){ if(b==e) Stree[node]=array[b]; else{ int left = 2*node; int right= left+1; int mid = (b+e)/2; build(left,b,mid); build(right,mid+1,e); Stree[node]=Stree[left]&Stree[right]; } } public void probagate(int node, int b, int e){ int left=2*node; int right=left+1; lazy[left]|=lazy[node]; lazy[right]|=lazy[node]; int mid =(b+e)/2; Stree[left]|=lazy[node]; Stree[right]|=lazy[node]; lazy[node]=0; // to make sure that being anded with anything would give the thing } public void all (int node , int b, int e){ if(b==e) return ; probagate(node, b, e); int mid =(b+e)/2; all(node*2,b,mid); all(node*2+1,mid+1,e); } public long query(int i,int j){ return query(1,1,N,i,j); } public long query(int node, int b ,int e, int i ,int j){ if(b>j || e<i) return -1; // think about this if(b>=i && e<=j) return Stree[node]; int mid = (b+e)/2; probagate(node,b, e); long q1 = query(node*2,b,mid,i,j); long q2 = query(node*2+1,mid+1,e,i,j); return q1&q2; } public void updatePoint( int index, long val){ // changes the point to value array[index]=val; int node = N+index-1; Stree[node]=val; while(node>1){ node/=2; Stree[node]=Stree[node*2]&Stree[node*2+1]; } } public void updateRange ( int i ,int j, long val){ updateRange(1,1,N,i,j,val); } public void updateRange(int node, int b ,int e, int i, int j ,long val ){ if(e<i || b>j) return ; if(b>=i && e<=j){ Stree[node]|=val; // think lazy[node]|=val; } else{ int mid = (b+e)/2; probagate(node,b,e); updateRange(node*2, b, mid, i, j, val); updateRange(node*2+1, mid+1, e, i, j, val); Stree[node]=Stree[node*2]&Stree[node*2+1]; } } }
Java
["3 1\n1 3 3", "3 2\n1 3 3\n1 3 2"]
1 second
["YES\n3 3 3", "NO"]
null
Java 8
standard input
[ "data structures", "constructive algorithms", "trees" ]
0b204773f8d06362b7569bd82224b218
The first line contains two integers n, m (1 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≤ li ≤ ri ≤ n, 0 ≤ qi &lt; 230) describing the i-th limit.
1,800
If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≤ a[i] &lt; 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line.
standard output
PASSED
5d1a91eecce25a055b19bd2aec5eba3b
train_001.jsonl
1414170000
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≤ li ≤ ri ≤ n) meaning that value should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist.Expression x&amp;y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&amp;", in Pascal — as "and".
256 megabytes
import java.io.*; import java.io.IOException; import java.util.*; //import javafx.util.Pair; //import java.util.concurrent.LinkedBlockingDeque; //import sun.net.www.content.audio.wav; import java.text.DecimalFormat; public class Codeforces { public static long mod = (long)Math.pow(10, 9)+7 ; public static double epsilon=0.00000000008854;//value of epsilon public static InputReader sc = new InputReader(System.in); public static PrintWriter pw = new PrintWriter(System.out); public static void diji(PriorityQueue<Pair> q,ArrayList<ArrayList<Pair>> a){ //int vis[]=new int[a.size()]; boolean vis[]=new boolean[a.size()]; //vis[0]=1; Arrays.fill(vis, false); int n=a.size(); long val[]=new long[n]; long inf=Long.MAX_VALUE; Arrays.fill(val, inf); q.add(new Pair(0, 0)); val[0]=0; int p[]=new int[n]; p[0]=-1; while(q.size()>0){ Pair r=q.remove(); if(vis[r.i]) continue; vis[r.i]=true;///removed int u=r.i; for(int i=0;i<a.get(u).size();i++){ int v=a.get(u).get(i).i; long w=a.get(u).get(i).j; if(val[v]>r.j+w){ p[v]=u; val[v]=r.j+w; q.add(new Pair(v, val[v])); } } } //pw.println(Arrays.toString(p)); int i=n-1; Stack<Integer> st=new Stack<>(); if(val[i]==inf) { pw.println(-1); return; } while(i!=-1){ st.add(i+1); i=p[i]; } while(st.size()>0){ pw.print(st.pop()+" "); } } public static int countSet(int a){ int c=0; while(a>0){ a&=(a-1); c++; } return c; } public static void Zfunction(String s){ int n=s.length(); int a[]=new int[n]; int r1=0,r2=1; for(int i=1;i<n;){ int f=0; while(r2<n&&s.charAt(r1)==s.charAt(r2)){ r1++; r2++; } a[i]=r1; i++; int l2=1; for(;i<r2;i++){ if(i+a[l2]<r2) a[i]=a[l2++]; else{ f=1; r1=r2-i; break; } } if(f==0){ r2=i; r1=0; } } pw.println(Arrays.toString(a)); } public static ArrayList<ArrayList <Integer>> GetGraph(int n,int m){ ArrayList<ArrayList <Integer>> a=new ArrayList<>(); for(int i=0;i<n;i++){ a.add(new ArrayList<>()); } for(int i=0;i<m;i++){ int u=sc.nextInt()-1; int v=sc.nextInt()-1; a.get(u).add(v); a.get(v).add(u); } return a; } public static int firstNode(int a,int p[]){ if(a!=p[a]){ p[a]=firstNode(p[a], p); } return p[a]; } public static void Union(int a,int b,int p[]){ //int a=firstNode(a1, p); //int b=firstNode(b1, p); /*if(a!=b){ if(r[a]<r[b]){ p[a]=b; } else if(r[a]>r[b]){ p[b]=a; } else{ r[b]++; p[a]=b; } }*/ if(a!=b) p[firstNode(a,p)]=firstNode(b,p);//if no rank than } public static void main(String[] args) { // code starts.. int n=sc.nextInt(); int m=sc.nextInt(); int a[][]=new int[m][5]; for(int i=0;i<m;i++){ a[i][0]=sc.nextInt()-1; a[i][1]=sc.nextInt()-1; a[i][2]=sc.nextInt(); a[i][3]=a[i][1]-a[i][0]; a[i][4]=i; } //Arrays.sort(a,pair()); int ans[]=new int[n+1]; //Arrays.fill(ans, (int)(Math.pow(2, 30)-1)); //int l=0; for(int j=0;j<=30;j++){ int f[]=new int[n+1]; for(int i=0;i<m;i++){ int l=a[i][0]; int r=a[i][1]+1; if((a[i][2]&(1<<j))>0){ f[l]++; f[r]--; } } if(f[0]>0){ ans[0]+=(1<<j); } for(int i=1;i<n;i++){ f[i]+=f[i-1]; if(f[i]>0){ ans[i]+=(1<<j); } } } SegmentTree s=new SegmentTree(ans); int f=0; for(int i=0;i<m;i++){ int x=s.getValue(a[i][0], a[i][1]); if(x!=a[i][2]){ f=1; break; } } if(f!=1){ pw.println("YES"); for(int i=0;i<n;i++) pw.print(ans[i]+" "); } else pw.println("NO"); // Code ends... pw.flush(); pw.close(); } public static Comparator<Integer> C(){ return new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o2.compareTo(o1);//for descending } }; } public static Comparator<Pair> di(){ return new Comparator<Pair>() { @Override public int compare(Pair o1, Pair o2) { Long a=o1.j; Long b=o2.j; return a.compareTo(b);//ascending } }; } static class tripletL implements Comparable<tripletL> { Long x, y, z; tripletL(long x, long y, long z) { this.x = x; this.y = y; this.z = z; } public int compareTo(tripletL o) { int result = x.compareTo(o.x); if (result == 0) result = y.compareTo(o.y); if (result == 0) result = z.compareTo(o.z); return result; } public boolean equlas(Object o) { if (o instanceof tripletL) { tripletL p = (tripletL) o; return (x - p.x == 0) && (y - p.y ==0 ) && (z - p.z == 0); } return false; } public String toString() { return x + " " + y + " " + z; } public int hashCode() { return new Long(x).hashCode() * 31 + new Long(y).hashCode() + new Long(z).hashCode(); } } public static String Doubleformate(double a,int n){ String s=""; while(n-->0){ s+='0'; } DecimalFormat f =new DecimalFormat("#0."+s); return f.format(a); } public static Comparator<Integer[]> column(int i){ return new Comparator<Integer[]>() { @Override public int compare(Integer[] o1, Integer[] o2) { return o1[i].compareTo(o2[i]);//for ascending //return o2[i].compareTo(o1[i]);//for descending } }; } public static Comparator<Long[]> column1(int i){ return new Comparator<Long[]>() { @Override public int compare(Long[] o1, Long[] o2) { return o1[i].compareTo(o2[i]);//for ascending //return o2[i].compareTo(o1[i]);//for descending } }; } public static Comparator<Integer[]> pair(){ return new Comparator<Integer[]>() { @Override public int compare(Integer[] o1, Integer[] o2) { int result=o1[0].compareTo(o2[0]); if(result==0) result=o1[1].compareTo(o2[1]); return result; } }; } public static Comparator<Integer[]> Triplet(){ return new Comparator<Integer[]>() { @Override public int compare(Integer[] o1, Integer[] o2) { for(int i=0;i<3;i++){ for(int j=i+1;j<3;j++){ for(int k=0;k<3;k++){ for(int p=k+1;p<3;p++){ if((o1[i]==o2[k]&&o1[j]==o2[p])||(o1[j]==o2[k]&&o1[i]==o2[p])){ } } } } } int result=o1[0].compareTo(o2[0]); if(result==0) result=o1[1].compareTo(o2[1]); if(result==0) result=o1[2].compareTo(o2[2]); return result; } }; } public static String reverseString(String s){ StringBuilder input1 = new StringBuilder(); input1.append(s); input1 = input1.reverse(); return input1.toString(); } public static int[] scanArray(int n){ int a[]=new int [n]; for(int i=0;i<n;i++) a[i]=sc.nextInt(); return a; } public static long[] scanLongArray(int n){ long a[]=new long [n]; for(int i=0;i<n;i++) a[i]=sc.nextLong(); return a; } public static String [] scanStrings(int n){ String a[]=new String [n]; for(int i=0;i<n;i++) a[i]=sc.nextLine(); return a; } } class Pair{ int i; long j; Pair(int a,long b){ i=a; j=b; } } 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 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); } } class SegmentTree{//0...n int s[],n; SegmentTree(int a[]){ n=a.length; int l=(int)Math.ceil(Math.log(n)/Math.log(2)); l=2*(int)Math.pow(2,l)-1; s=new int[l]; createSegmentTreeUtil(a, 0, 0, a.length-1); } int createSegmentTreeUtil(int a[],int root,int l,int r){ if(l==r) s[root]=a[l]; else s[root]= Compare(createSegmentTreeUtil(a, 2*root+1, l, (l+r)/2), createSegmentTreeUtil(a,2*root+2, (l+r)/2+1,r)); return s[root]; } int getValue(int gl,int gr){ return getValueUtil(0, 0, n-1, gl, gr); } int getValueUtil(int root,int l,int r,int gl,int gr){ if(l>=gl&&r<=gr){ return s[root]; } if(l>gr||r<gl){ return Integer.MAX_VALUE; } return Compare(getValueUtil(2*root+1, l, (l+r)/2, gl, gr), getValueUtil(2*root+2, (l+r)/2+1, r, gl, gr)); } void update(int p,int k){ updateUtil(p, k,0,0,n-1); } int updateUtil(int p,int k,int root,int l,int r){ if(l==r&&l==k){ return s[root]=p; } else if(l>k||r<k) return s[root]; else{ return s[root]=Compare(updateUtil(p, k, 2*root+1, l, (l+r)/2), updateUtil(p, k, 2*root+2,(l+r)/2+1,r )); } } int Compare(int a,int b){ return a&b; } }
Java
["3 1\n1 3 3", "3 2\n1 3 3\n1 3 2"]
1 second
["YES\n3 3 3", "NO"]
null
Java 8
standard input
[ "data structures", "constructive algorithms", "trees" ]
0b204773f8d06362b7569bd82224b218
The first line contains two integers n, m (1 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≤ li ≤ ri ≤ n, 0 ≤ qi &lt; 230) describing the i-th limit.
1,800
If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≤ a[i] &lt; 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line.
standard output
PASSED
2e1997d022dafaacce91afc92da39854
train_001.jsonl
1414170000
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≤ li ≤ ri ≤ n) meaning that value should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist.Expression x&amp;y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&amp;", in Pascal — as "and".
256 megabytes
import java.io.BufferedInputStream; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { ScanReader scanner = new ScanReader(System.in); PrintWriter out = new PrintWriter(System.out); solve(scanner, out); out.close(); } final static int MAXN = 50005; final static int MAXK = 505; static int N = 0; static int M = 0; static int K = 0; static long[][] dp; static int[][] g; static int[] A; static int[] B; static long curAns = 0L; static int[] ST; static int build(int index, int nodel, int noder) { if (nodel > noder) { return (1 << 31) - 1; } if (nodel == noder) { ST[index] = B[nodel]; return B[nodel]; } int m = (nodel + noder) / 2; int a = build(index * 2, nodel, m); int b = build(index * 2 + 1, m + 1, noder); int c = a & b; ST[index] = c; return c; } static int query(int index, int nodel, int noder, int targetl, int targetr) { if (targetl > targetr) { return (1 << 31) - 1; } if (nodel == targetl && noder == targetr) { return ST[index]; } int m = (nodel + noder) / 2; int a = query(index * 2, nodel, m, targetl, Math.min(m, targetr)); int b = query(index * 2 + 1, m + 1, noder, Math.max(m + 1, targetl), targetr); int c = a & b; return c; } static void solve(ScanReader scanner, PrintWriter out) { N = scanner.nextInt(); M = scanner.nextInt(); int[][] C = new int[M][3]; for (int i = 0; i < M; i++) { int l = scanner.nextInt(); int r = scanner.nextInt(); int v = scanner.nextInt(); l--; r--; C[i][0] = l; C[i][1] = r; C[i][2] = v; } B = new int[N]; Arrays.fill(B,0); int[] add = new int[N]; for (int k = 0; k < 31; k++) { int u = 1 << k; Arrays.fill(add, 0); for (int i = 0; i < M; i++) { int l = C[i][0]; int r = C[i][1]; int v = C[i][2]; if ((v & u) > 0) { add[l] += 1; if (r + 1 < N) { add[r+1] -= 1; } } } int a = 0; for (int i = 0; i < N; i++) { a += add[i]; if (a > 0) { B[i] |= u; } } } ST = new int[N * 4]; Arrays.fill(ST, 0); build(1, 0, N-1); for (int i = 0; i < M; i++) { int l = C[i][0]; int r = C[i][1]; int v = C[i][2]; if (query(1, 0, N-1, l, r) != v) { out.println("NO"); return; } } out.println("YES"); out.println(Arrays.stream(B).mapToObj(String::valueOf).collect(Collectors.joining(" "))); } static int bitlen(int val) { int s = 0; while (val > 0) { s += 1; val >>= 1; } return s; } static int dfs(int index, int pre, List<Integer> vals) { if (vals.isEmpty()) { return Integer.MAX_VALUE; } if (index < 0) { return vals.stream().map(v -> pre ^v).max(Integer::compareTo).get(); } int bv = 1 << index; List<Integer> a = vals.stream().filter(v -> (v & bv) > 0).collect(Collectors.toList()); if (a.isEmpty()) { return dfs(index-1, pre, vals); } else if (a.size() == vals.size()) { return dfs(index-1, pre | bv, vals); } else { List<Integer> b = vals.stream().filter(v -> (v & bv) == 0).collect(Collectors.toList()); return Math.min(dfs(index-1, pre | bv, b), dfs(index-1, pre, a)); } } static int ones(int val) { int count = 0; while (val > 0) { count += (val & 1) > 0 ? 1 : 0; val >>= 1; } return count; } 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 nextInt() { 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; } } } class UnioinSet { private Map<Long, Long> parents = new HashMap<>(); public Long find(Long u) { if (parents.getOrDefault(u, u).equals(u)) { return u; } return find(parents.get(u)); } public void union(Long u, Long v) { Long pu = find(u); Long pv = find(v); parents.put(pu, pv); } } class Pair implements Comparable<Pair> { public int x; public int y; public Pair(int x, int y) { this.x = x; this.y = y; } public int toIndex(int base) { return this.x * base + this.y; } public List<Pair> neighbors() { List<Pair> ans = new ArrayList<>(); ans.add(new Pair(this.x + 1, this.y)); ans.add(new Pair(this.x - 1, this.y)); ans.add(new Pair(this.x, this.y + 1)); ans.add(new Pair(this.x, this.y - 1)); return ans; } @Override public int compareTo(Pair o) { if (o.x != this.x) { return this.x - o.x; } else { return this.y - o.y; } } @Override public int hashCode() { int v = this.x * 100000 + this.y; return Integer.hashCode(v); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof Pair) { Pair op = (Pair) obj; return op.x == this.x && op.y == this.y; } return false; } }
Java
["3 1\n1 3 3", "3 2\n1 3 3\n1 3 2"]
1 second
["YES\n3 3 3", "NO"]
null
Java 8
standard input
[ "data structures", "constructive algorithms", "trees" ]
0b204773f8d06362b7569bd82224b218
The first line contains two integers n, m (1 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≤ li ≤ ri ≤ n, 0 ≤ qi &lt; 230) describing the i-th limit.
1,800
If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≤ a[i] &lt; 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line.
standard output
PASSED
3c15c1e6315894670c1449f66bcd4589
train_001.jsonl
1414170000
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≤ li ≤ ri ≤ n) meaning that value should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist.Expression x&amp;y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&amp;", in Pascal — as "and".
256 megabytes
import java.util.*; public class InterestingArray { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int m = scan.nextInt(); int[][] pre = new int[31][n+1]; int[][] queries = new int[3][m]; for(int q = 1; q <= m; q++) { int l = scan.nextInt()-1; int r = scan.nextInt()-1; int x = scan.nextInt(); queries[0][q-1] = l; queries[1][q-1] = r; queries[2][q-1] = x; for(int i = 30; i >= 0; i--) { int j = (1 << i); if((x & j) > 0) { pre[i][l]++; pre[i][r+1]--; } } } long[] ans = new long[n]; int sum = 0; for(int j = 0; j < 31; j++) { sum = 0; for(int i = 0; i < n; i++) { sum += pre[j][i]; if(sum > 0) ans[i] |= (1 << j); } } ST seg = new ST(n, ans); for(int i = 0; i < m; i++) { int l = queries[0][i]; int r = queries[1][i]; long x = queries[2][i]; long a = seg.and(l, r); if(a != x) { System.out.println("NO"); return; } } System.out.println("YES"); for(int i = 0; i < n; i++) System.out.print(ans[i]+" "); } static class ST { // 0-based indexed queries int n, lo[], hi[]; long[] d, t; public ST(int nn, long[] a) { n = nn; d = new long[n << 2]; t = new long[n << 2]; lo = new int[n << 2]; hi = new int[n << 2]; build(a, 1, 0, n - 1); } void build(long[] arr, int i, int a, int b) { lo[i] = a; hi[i] = b; if(a == b) { t[i] = arr[a]; return; } int m = (a + b) / 2; build(arr, i << 1, a, m); build(arr, i << 1 | 1, m + 1, b); update(i); } void prop(int i) { d[i << 1] += d[i]; d[i << 1 | 1] += d[i]; d[i] = 0; } void update(int i) { t[i] = (t[i << 1] + d[i << 1]) & (t[i << 1 | 1] + d[i << 1 | 1]); } // adds value v over range [a, b] void inc(int a, int b, long v) { inc(1, a, b, v); } private void inc(int i, int a, int b, long v) { if(b < lo[i] || a > hi[i]) return; if(a <= lo[i] && b >= hi[i]) { d[i] += v; return; } prop(i); inc(i << 1, a, b, v); inc(i << 1 | 1, a, b, v); update(i); } // finds minimum value over range [a, b] long and(int a, int b) { return and(1, a, b); } private long and(int i, int a, int b) { if(b < lo[i] || hi[i] < a) return (1 << 30)-1; if(a <= lo[i] && hi[i] <= b) return t[i] + d[i]; prop(i); long res = and(i << 1, a, b) & and(i << 1 | 1, a, b); update(i); return res; } } }
Java
["3 1\n1 3 3", "3 2\n1 3 3\n1 3 2"]
1 second
["YES\n3 3 3", "NO"]
null
Java 8
standard input
[ "data structures", "constructive algorithms", "trees" ]
0b204773f8d06362b7569bd82224b218
The first line contains two integers n, m (1 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≤ li ≤ ri ≤ n, 0 ≤ qi &lt; 230) describing the i-th limit.
1,800
If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≤ a[i] &lt; 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line.
standard output
PASSED
9e27a3408cea9c840e30d8e6510eda4b
train_001.jsonl
1414170000
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≤ li ≤ ri ≤ n) meaning that value should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist.Expression x&amp;y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&amp;", in Pascal — as "and".
256 megabytes
import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.Scanner; import java.util.function.Supplier; public class Application { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); solve(scanner.nextInt(), scanner.nextInt(), scanner::nextInt); // Random rnd = new Random(); // long start = System.currentTimeMillis(); // solve(100000, 100000, () -> Math.abs(rnd.nextInt())); // long end = System.currentTimeMillis(); // System.out.println("Time: " + (end - start) + " ms"); } private static void solve(int n, int m, Supplier<Integer> supplier) { List<Interval> intervals = new ArrayList<>(m); for (int i = 0; i < m; i++) intervals.add(new Interval(supplier.get(), supplier.get(), supplier.get())); Collections.sort(intervals); int[] res = new int[n]; for (int i = 0; i < 31; i++) { int mask = 0x1 << i; List<Interval> mergedIntervals = merge(intervals, mask); // Collections.sort(mergedIntervals); if (!isCorrect(mergedIntervals)) { System.out.println("NO"); return; } fill(res, mergedIntervals, mask); } System.out.println("YES"); print(res); } private static void print(int[] res) { StringBuilder bldr = new StringBuilder(); for (int e : res) bldr.append(e).append(' '); System.out.println(bldr.toString()); } private static void fill(int[] res, List<Interval> intervals, int mask) { for (Interval interval : intervals) { if (interval.val == 1) { for (int i = interval.start; i <= interval.end; i++) res[i - 1] |= mask; } } } private static boolean isCorrect(List<Interval> intervals) { int start = -1, end = -1; Interval lastZero = null; for (Interval interval : intervals) { if (interval.val == 0) { if (interval.start >= start && interval.end <= end) return false; lastZero = interval; } else { start = interval.start; end = interval.end; if (lastZero != null && lastZero.start >= start && lastZero.end <= end) return false; } } return true; } private static List<Interval> merge(List<Interval> intervals, int mask) { List<Interval> res = new ArrayList<>(); int start = -1, end = -1; for (Interval interval : intervals) { if ((interval.val & mask) == 0) { res.add(new Interval(interval.start, interval.end, 0)); continue; } if (interval.start > end) { if (end != -1) res.add(new Interval(start, end, 1)); start = interval.start; end = interval.end; } end = Math.max(end, interval.end); } if (end != -1) res.add(new Interval(start, end, 1)); return res; } private static class Interval implements Comparable<Interval> { private final int start; private final int end; private final int val; public Interval(int start, int end, int val) { this.start = start; this.end = end; this.val = val; } @Override public int compareTo(Interval o) { int res = Integer.compare(start, o.start); return res == 0 ? -Integer.compare(val, o.val) : res; } public String toString() { return "[" + start + ", " + end + "](" + val + ")"; } } }
Java
["3 1\n1 3 3", "3 2\n1 3 3\n1 3 2"]
1 second
["YES\n3 3 3", "NO"]
null
Java 8
standard input
[ "data structures", "constructive algorithms", "trees" ]
0b204773f8d06362b7569bd82224b218
The first line contains two integers n, m (1 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≤ li ≤ ri ≤ n, 0 ≤ qi &lt; 230) describing the i-th limit.
1,800
If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≤ a[i] &lt; 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line.
standard output
PASSED
c9cf3def7acfff6cf9a3737735db644c
train_001.jsonl
1414170000
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≤ li ≤ ri ≤ n) meaning that value should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist.Expression x&amp;y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&amp;", in Pascal — as "and".
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.StreamTokenizer; public class Main { static long Add[] = null; static long Data[] = null; static operation op[] = null; static int n; private static final long MAX = (1 << 31) - 1; public static void main(String[] args) throws IOException { StreamTokenizer cin = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); int m, L, R; long q; while (cin.nextToken() != StreamTokenizer.TT_EOF){ n = (int)cin.nval; cin.nextToken(); m = (int)cin.nval; Data = new long[n * 4]; Add = new long[n * 4]; op = new operation[m + 1]; for (int i = 1; i <= m; i++) { cin.nextToken(); L = (int)cin.nval; cin.nextToken(); R = (int)cin.nval; cin.nextToken(); q = (long)cin.nval; op[i] = new operation(L, R, q); Update(L, R, q, 1, n, 1); } boolean flag = true; for (int i = 1; i <= m; i++) { if (Query(op[i].L, op[i].R, 1, n, 1) != op[i].q) { out.println("NO"); flag = false; break; } } if(flag) { out.println("YES"); print(1, n, 1, n, 1, out); } out.flush(); } } private static void print(int L, int R, int l, int r, int rt, PrintWriter out) { // TODO Auto-generated method stub if (l == r) { out.print(l == n ? Data[rt] + "\n" : Data[rt] + " "); return; } int m = (l + r) >> 1; PushDown(rt); if (L <= m) print(L, R, l, m, rt * 2, out); if (m < R) print(L, R, m + 1, r, rt * 2 + 1, out); } private static void PushUp(int rt) { Data[rt] = Data[rt * 2] & Data[rt * 2 + 1]; } private static void Update(int L, int R, long C, int l, int r, int rt) { if (L <= l && r <= R) { Data[rt] |= C; Add[rt] |= C; return; } int m = (l + r) >> 1; PushDown(rt); if (L <= m) Update(L, R, C, l, m, rt * 2); if (R > m) Update(L, R, C, m + 1, r, rt * 2 + 1); PushUp(rt); } private static void PushDown(int rt) { if (Add[rt] != 0) { Add[rt * 2] |= Add[rt]; Add[rt * 2 + 1] |= Add[rt]; Data[rt * 2] |= Add[rt]; Data[rt * 2 + 1] |= Add[rt]; Add[rt] = 0; } } private static long Query(int L, int R, int l, int r, int rt) { if (L <= l && r <= R) { return Data[rt]; } int m = (l + r) >> 1; PushDown(rt); long ANS = MAX; if (L <= m) ANS &= Query(L, R, l, m, rt * 2); if (R > m) ANS &= Query(L, R, m + 1, r, rt * 2 + 1); PushUp(rt); return ANS; } } class operation { int L; int R; long q; public operation(int L, int R, long q) { // TODO Auto-generated constructor stub this.L = L; this.R = R; this.q = q; } } /* * 3 1 1 3 3 3 2 1 3 3 1 3 2 */
Java
["3 1\n1 3 3", "3 2\n1 3 3\n1 3 2"]
1 second
["YES\n3 3 3", "NO"]
null
Java 8
standard input
[ "data structures", "constructive algorithms", "trees" ]
0b204773f8d06362b7569bd82224b218
The first line contains two integers n, m (1 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≤ li ≤ ri ≤ n, 0 ≤ qi &lt; 230) describing the i-th limit.
1,800
If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≤ a[i] &lt; 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line.
standard output
PASSED
77970e03bb1b3198b2c612c0786e6e45
train_001.jsonl
1414170000
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≤ li ≤ ri ≤ n) meaning that value should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist.Expression x&amp;y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&amp;", in Pascal — as "and".
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.StreamTokenizer; public class Main { static long Add[] = null; static long Data[] = null; static operation op[] = null; static int n; private static final long MAX = (1 << 31) - 1; // public static void main(String[] args) throws IOException { StreamTokenizer cin = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); int m, L, R; long q; while (cin.nextToken() != StreamTokenizer.TT_EOF){ n = (int)cin.nval; cin.nextToken(); m = (int)cin.nval; Data = new long[n * 4]; Add = new long[n * 4]; op = new operation[m + 1]; for (int i = 1; i <= m; i++) { cin.nextToken(); L = (int)cin.nval; cin.nextToken(); R = (int)cin.nval; cin.nextToken(); q = (long)cin.nval; op[i] = new operation(L, R, q); Update(L, R, q, 1, n, 1); } boolean flag = true; for (int i = 1; i <= m; i++) { if (Query(op[i].L, op[i].R, 1, n, 1) != op[i].q) { out.println("NO"); flag = false; break; } } if(flag) { out.println("YES"); print(1, n, 1, n, 1, out); } out.flush(); } } private static void print(int L, int R, int l, int r, int rt, PrintWriter out) { // TODO Auto-generated method stub if (l == r) { out.print(l == n ? Data[rt] + "\n" : Data[rt] + " "); return; } int m = (l + r) >> 1; PushDown(rt); if (L <= m) print(L, R, l, m, rt * 2, out); if (m < R) print(L, R, m + 1, r, rt * 2 + 1, out); } private static void PushUp(int rt) { Data[rt] = Data[rt * 2] & Data[rt * 2 + 1]; } private static void Update(int L, int R, long C, int l, int r, int rt) { if (L <= l && r <= R) { Data[rt] |= C; Add[rt] |= C; return; } int m = (l + r) >> 1; PushDown(rt); if (L <= m) Update(L, R, C, l, m, rt * 2); if (R > m) Update(L, R, C, m + 1, r, rt * 2 + 1); PushUp(rt); } private static void PushDown(int rt) { if (Add[rt] != 0) { Add[rt * 2] |= Add[rt]; Add[rt * 2 + 1] |= Add[rt]; Data[rt * 2] |= Add[rt]; Data[rt * 2 + 1] |= Add[rt]; Add[rt] = 0; } } private static long Query(int L, int R, int l, int r, int rt) { if (L <= l && r <= R) { return Data[rt]; } int m = (l + r) >> 1; PushDown(rt); long ANS = MAX; if (L <= m) ANS &= Query(L, R, l, m, rt * 2); if (R > m) ANS &= Query(L, R, m + 1, r, rt * 2 + 1); PushUp(rt); return ANS; } } class operation { int L; int R; long q; public operation(int L, int R, long q) { // TODO Auto-generated constructor stub this.L = L; this.R = R; this.q = q; } } /* * 3 1 1 3 3 3 2 1 3 3 1 3 2 */
Java
["3 1\n1 3 3", "3 2\n1 3 3\n1 3 2"]
1 second
["YES\n3 3 3", "NO"]
null
Java 8
standard input
[ "data structures", "constructive algorithms", "trees" ]
0b204773f8d06362b7569bd82224b218
The first line contains two integers n, m (1 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≤ li ≤ ri ≤ n, 0 ≤ qi &lt; 230) describing the i-th limit.
1,800
If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≤ a[i] &lt; 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line.
standard output
PASSED
c2df1f1c2c038356a09bccf3961a0d32
train_001.jsonl
1414170000
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≤ li ≤ ri ≤ n) meaning that value should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist.Expression x&amp;y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&amp;", in Pascal — as "and".
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int n = sc.nextInt() , m = sc.nextInt(); SegmentTree tree = new SegmentTree(n); Queue<Query> qu = new LinkedList<>(); while(m-->0) { int l = sc.nextInt() - 1, r = sc.nextInt() -1 , q = sc.nextInt(); qu.add(new Query(l, r, q)); tree.update(l, r, q); } while(!qu.isEmpty()) { Query q = qu.poll(); if(tree.query(q.l, q.r)!=q.v) { System.out.println("NO"); return; } } System.out.println("YES"); System.out.println(tree.printArray()); } static class Query{ int l,r,v; public Query(int lq,int rq,int val) {l=lq;r=rq;v=val;} } static class SegmentTree { int N,len; int[] tree ; int[] lazy; StringBuilder sb; public SegmentTree(int n) { N = 1; len = n; while(N<len)N<<=1; N<<=1; tree = new int[N]; lazy = new int[N]; sb = new StringBuilder(); } void propagate(int n,int l,int r) { if(l==r)return; lazy[n<<1] |= lazy[n]; lazy[n<<1|1] |= lazy[n]; tree[n<<1] |= lazy[n]; tree[n<<1|1] |= lazy[n]; lazy[n] = 0; } void update(int l,int r,int v) {update(1, 0, len-1, l, r, v);} void update(int n,int l,int r,int lq,int rq,int v) { if(l>rq||r<lq)return; propagate(n, l, r); if(l>=lq&&r<=rq) { lazy[n] |= v; tree[n] |= v; } else { int mid = (l+r)>>1; update(n<<1, l, mid, lq, rq, v); update(n<<1|1, mid+1, r, lq, rq, v); tree[n] = tree[n<<1] & tree[n<<1|1]; } } String printArray() { printArray(1,0,len-1); return sb.toString(); } void printArray(int n , int l,int r) { propagate(n, l, r); if(l==r) sb.append(tree[n]+" "); else { int mid = (l+r)>>1; printArray(n<<1, l, mid); printArray(n<<1|1, mid+1, r); } } int query(int l,int r) {return query(1, 0, len-1, l, r);} int query(int n,int l,int r,int lq,int rq) { if(l>rq||r<lq)return Integer.MAX_VALUE; propagate(n, l, r); if(l>=lq&&r<=rq) return tree[n]; else { int mid = (l+r)>>1; return query(n<<1, l, mid, lq, rq) & query(n<<1|1, mid+1, r, lq, rq); } } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public Scanner(String s) throws FileNotFoundException {br = new BufferedReader(new FileReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public String nextLine() throws IOException {return br.readLine();} public long nextLong() throws IOException {return Long.parseLong(next());} public double nextDouble() throws IOException {return Double.parseDouble(next());} public char nextChar() throws IOException{return next().charAt(0);} public boolean ready() throws IOException {return br.ready();} public int[] nextIntArr() throws IOException{ st = new StringTokenizer(br.readLine()); int[] res = new int[st.countTokens()]; for (int i = 0; i < res.length; i++) res[i] = nextInt(); return res; } public char[] nextCharArr() throws IOException{ st = new StringTokenizer(br.readLine()); char[] res = new char[st.countTokens()]; for (int i = 0; i < res.length; i++) res[i] = nextChar(); return res; } } }
Java
["3 1\n1 3 3", "3 2\n1 3 3\n1 3 2"]
1 second
["YES\n3 3 3", "NO"]
null
Java 8
standard input
[ "data structures", "constructive algorithms", "trees" ]
0b204773f8d06362b7569bd82224b218
The first line contains two integers n, m (1 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≤ li ≤ ri ≤ n, 0 ≤ qi &lt; 230) describing the i-th limit.
1,800
If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≤ a[i] &lt; 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line.
standard output
PASSED
7abff981f3ea2f325266e1443c37fcf1
train_001.jsonl
1414170000
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≤ li ≤ ri ≤ n) meaning that value should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist.Expression x&amp;y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&amp;", in Pascal — as "and".
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in Actual solution is at the top * * @author dauom */ 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); BInterestingArray solver = new BInterestingArray(); solver.solve(1, in, out); out.close(); } static class BInterestingArray { public final void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); int[][] set = new int[30][n + 1]; int[][] constrains = in.nextIntMatrix(m, 3); for (int[] c : constrains) { int l = --c[0], r = --c[1], q = c[2]; for (int i = 0; i < 30; i++) { if ((q >> i & 1) == 1) { set[i][l]++; set[i][r + 1]--; } } } int[] ans = new int[n]; for (int i = 0; i < 30; i++) { for (int j = 1; j <= n; j++) { set[i][j] += set[i][j - 1]; } for (int j = 0; j <= n; j++) { if (set[i][j] != 0) { set[i][j] = 1; } if (j > 0) { set[i][j] += set[i][j - 1]; } if (j < n) { ans[j] |= RangeQueriesUtils.get(set[i], j, j) << i; } } } for (int[] c : constrains) { int l = c[0], r = c[1], q = c[2]; for (int i = 0; i < 30; i++) { int cnt = RangeQueriesUtils.get(set[i], l, r); if ((cnt != r - l + 1) == ((q >> i & 1) == 1)) { out.println("NO"); return; } } } out.println("YES"); out.println(StringUtils.join(ans)); } } static final class RangeQueriesUtils { private RangeQueriesUtils() { throw new RuntimeException("DON'T"); } public static final int get(int[] pre, int i, int j) { if (i > j) { return 0; } if (i == 0) { return pre[j]; } return pre[j] - pre[i - 1]; } } static class StringUtils { private StringUtils() { throw new RuntimeException("DON'T"); } public static final String joinRange(String delimiter, int from, int to, int[] a) { if (from > to) { return ""; } StringBuilder sb = new StringBuilder(); sb.append(a[from]); for (int i = from + 1; i <= to; i++) { sb.append(delimiter).append(a[i]); } return sb.toString(); } public static final String join(int... a) { return joinRange(" ", 0, a.length - 1, a); } } static final class InputReader { private final InputStream stream; private final byte[] buf = new byte[1 << 16]; private int curChar; private int numChars; public InputReader() { this.stream = System.in; } public InputReader(final InputStream stream) { this.stream = stream; } private final int read() { if (this.numChars == -1) { throw new UnknownError(); } else { if (this.curChar >= this.numChars) { this.curChar = 0; try { this.numChars = this.stream.read(this.buf); } catch (IOException ex) { throw new InputMismatchException(); } if (this.numChars <= 0) { return -1; } } return this.buf[this.curChar++]; } } public final int nextInt() { int c; for (c = this.read(); isSpaceChar(c); c = this.read()) {} byte sgn = 1; if (c == 45) { // 45 == '-' sgn = -1; c = this.read(); } int res = 0; while (c >= 48 && c <= 57) { // 48 == '0', 57 == '9' res *= 10; res += c - 48; // 48 == '0' c = this.read(); if (isSpaceChar(c)) { return res * sgn; } } throw new InputMismatchException(); } private static final boolean isSpaceChar(final int c) { return c == 32 || c == 10 || c == 13 || c == 9 || c == -1; // 32 == ' ', 10 == '\n', 13 == '\r', 9 == '\t' } public final int[][] nextIntMatrix(final int n, final int m) { int[][] arr = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { arr[i][j] = nextInt(); } } return arr; } } }
Java
["3 1\n1 3 3", "3 2\n1 3 3\n1 3 2"]
1 second
["YES\n3 3 3", "NO"]
null
Java 8
standard input
[ "data structures", "constructive algorithms", "trees" ]
0b204773f8d06362b7569bd82224b218
The first line contains two integers n, m (1 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≤ li ≤ ri ≤ n, 0 ≤ qi &lt; 230) describing the i-th limit.
1,800
If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≤ a[i] &lt; 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line.
standard output
PASSED
5e446f26b6aad277e82a0317411e3d7f
train_001.jsonl
1414170000
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≤ li ≤ ri ≤ n) meaning that value should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist.Expression x&amp;y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&amp;", in Pascal — as "and".
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.PriorityQueue; import java.util.StringTokenizer; import java.util.TreeSet; public class InterestingArray { public static void main(String[] args) throws NumberFormatException, IOException { Scanner sc = new Scanner(); int n = sc.nextInt(), m = sc.nextInt(); int N = 1; while (N < n) N <<= 1; int[] a = new int[N + 1]; int[] l = new int[m]; int[] r = new int[m]; int[] q = new int[m]; for (int i = 0; i < m; i++) { l[i] = sc.nextInt() ; r[i] = sc.nextInt(); q[i] = sc.nextInt(); } /* * for (int bit = 0; bit <= 30; bit++) { int[] sum = new int[n]; for (int i = 0; * i < m; i++) { if ((q[i] & (1 << bit)) > 0) { //out.println("bit is "+bit); * sum[l[i] ]++; if (r[i] < n) sum[r[i]]--; } } for (int i = 0; i < n; i++) { if * (i > 0) sum[i] += sum[i - 1]; if (sum[i] > 0) a[i + 1] |= 1 << bit; } } */ int num=0; for (int i = 0; i < 31; i++) { int [] sum=new int[4*N]; for(int k=0;k<m;k++) { if((q[k]&(1<<i)) >0) { sum[l[k]]++; sum[r[k]+1]--; } } for(int araf=1;araf<=n;araf++) { sum[araf]+=sum[araf-1]; if(sum[araf]>0) a[araf]|=(1<<i); } } /*for (int d : a) System.out.println(d);*/ StringBuilder sb = new StringBuilder(); SegmentTree s = new SegmentTree(a); boolean flag=true; for (int i = 0; i < m; i++) { if (s.query(l[i], r[i]) != q[i]) { flag =false; break; } } if(flag) { sb.append("YES" + "\n"); for (int k = 1; k <=n; k++) sb.append(a[k] + " "); sb.append("\n"); } else { sb.append("NO"); } System.out.println(sb); } static class SegmentTree { // 1-based DS, OOP int N; // the number of elements in the array as a power of 2 (i.e. after padding) int[] array, sTree, lazy; SegmentTree(int[] in) { array = in; N = in.length - 1; sTree = new int[N << 1]; // no. of nodes = 2*N - 1, we add one to cross out index zero lazy = new int[N << 1]; build(1, 1, N); } void build(int node, int b, int e) // O(n) { if (b == e) sTree[node] = array[b]; else { int mid = b + e >> 1; build(node << 1, b, mid); build(node << 1 | 1, mid + 1, e); sTree[node] = sTree[node << 1] & sTree[node << 1 | 1]; } } int query(int i, int j) { return query(1, 1, N, i, j); } int query(int node, int b, int e, int i, int j) // O(log n) { if (i > e || j < b) return ((1 << 30) - 1); if (b >= i && e <= j) return sTree[node]; int mid = b + e >> 1; // propagate(node, b, mid, e); int q1 = query(node << 1, b, mid, i, j); int q2 = query(node << 1 | 1, mid + 1, e, i, j); return q1 & q2; } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner(String file) throws FileNotFoundException { br = new BufferedReader(new FileReader(file)); } public Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } public int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); } public long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } } }
Java
["3 1\n1 3 3", "3 2\n1 3 3\n1 3 2"]
1 second
["YES\n3 3 3", "NO"]
null
Java 8
standard input
[ "data structures", "constructive algorithms", "trees" ]
0b204773f8d06362b7569bd82224b218
The first line contains two integers n, m (1 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≤ li ≤ ri ≤ n, 0 ≤ qi &lt; 230) describing the i-th limit.
1,800
If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≤ a[i] &lt; 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line.
standard output
PASSED
b3f33e08ebe338e4fdf5dc6036444112
train_001.jsonl
1414170000
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≤ li ≤ ri ≤ n) meaning that value should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist.Expression x&amp;y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&amp;", in Pascal — as "and".
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws Exception { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Solver solver = new Solver(); solver.solve(in, out); out.close(); } } class Solver { int n; int m; int[] l; int[] r; int[] need; int[] answer; int[] minEndZero; int[] add; int[] value; public void solve(InputReader in, PrintWriter out) { n = in.nextInt(); m = in.nextInt(); l = new int[m]; r = new int[m]; need = new int[m]; for (int i = 0; i < m; i++) { l[i] = in.nextInt() - 1; r[i] = in.nextInt() - 1; need[i] = in.nextInt(); } answer = new int[n]; minEndZero = new int[n]; add = new int[n + 1]; value = new int[n]; for (int lvl = 0; lvl < 30; lvl++) { Arrays.fill(add, 0); Arrays.fill(minEndZero, Integer.MAX_VALUE); Arrays.fill(value, 0); for (int i = 0; i < m; i++) { int L = l[i]; int R = r[i]; int bit = (need[i] >> lvl) & 1; if (bit == 1) { add[L]++; add[R + 1]--; } else { minEndZero[L] = Math.min(minEndZero[L], R); } } int cur = 0; boolean needZero = false; int mini = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { cur += add[i]; if (minEndZero[i] != Integer.MAX_VALUE) { needZero = true; mini = Math.min(mini, minEndZero[i]); } if (cur > 0) { value[i] = 1; } else if (needZero) { needZero = false; mini = Integer.MAX_VALUE; } if (needZero && mini <= i) { out.println("NO"); return; } } for (int i = 0; i < n; i++) { answer[i] |= (value[i] << lvl); } } out.println("YES"); for (int i = 0; i < n; i++) { out.print(answer[i] + " "); } out.println(); } } class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public int nextInt() { return Integer.parseInt(next()); } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } }
Java
["3 1\n1 3 3", "3 2\n1 3 3\n1 3 2"]
1 second
["YES\n3 3 3", "NO"]
null
Java 8
standard input
[ "data structures", "constructive algorithms", "trees" ]
0b204773f8d06362b7569bd82224b218
The first line contains two integers n, m (1 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≤ li ≤ ri ≤ n, 0 ≤ qi &lt; 230) describing the i-th limit.
1,800
If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≤ a[i] &lt; 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line.
standard output
PASSED
e9a3e2a4bd1bb0b9c288497000590696
train_001.jsonl
1414170000
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≤ li ≤ ri ≤ n) meaning that value should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist.Expression x&amp;y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&amp;", in Pascal — as "and".
256 megabytes
//package Graphs; import java.io.*; import java.util.Arrays; import java.util.StringTokenizer; public class main482B { public static PrintWriter out = new PrintWriter(System.out); public static FastScanner enter = new FastScanner(System.in); public static long mod = (1 << 30) - 1; public static void main(String[] args) throws IOException { int n = enter.nextInt(); int m = enter.nextInt(); int[] l = new int[m]; int[] r = new int[m]; long[] q = new long[m]; long[][] ans = new long[n + 2][30]; for (int i = 0; i < m; i++) { l[i] = enter.nextInt(); r[i] = enter.nextInt(); q[i] = enter.nextLong(); long a = 1; for (int j = 0; j < 30; j++, a = a << 1) { if ((a & q[i]) != 0) { ans[l[i]][j] += 1; ans[r[i] + 1][j] -= 1; } } } for (int j = 0; j < 30; j++) { for (int i = 1; i < n + 2; i++) { ans[i][j] += ans[i - 1][j]; } } for (int j = 0; j < 30; j++) { for (int i = 1; i < n + 1; i++) { ans[i][j] = (ans[i][j] > 0) ? 1 : 0; } } long a[] = new long[n + 1]; for (int i = 1; i < n + 1; i++) { long g = 1; for (int j = 0; j < 30; j++, g = g << 1) { a[i] += ans[i][j] * g; } } //build segtree on mass a[] long t[] = new long[4 * n + 1]; build(t, a, 1, 1, n); for (int i = 0; i < m; i++) { if (sum(t, 1, 1, n, l[i], r[i]) != q[i]) { System.out.println("NO"); return; } } System.out.println("YES"); for (int i = 1; i < n + 1; i++) { System.out.print(a[i] + " "); } } public static void build(long t[], long arr[], int v, int tl, int tr) { //По массиву arr строим if (tl == tr) { t[v] = arr[tl]; return; } int tmp = (tl + tr) >> 1; build(t, arr, v<<1, tl, tmp); build(t, arr, (v<<1) + 1, tmp + 1, tr); t[v] = t[2 * v] & t[2 * v + 1]; //К примеру это построили сумму на отрехке l,r - можно кучу всего другого }//o(n) public static long sum(long t[], int v, int tl, int tr, int l, int r) { if (l > r) return mod; if (l == tl && r == tr) { return t[v]; } int tmp = (tl + tr) >> 1; // Деление на 2 return sum(t, v<<1, tl, tmp, l, Math.min(r, tmp)) & sum(t, (v<<1)+1, tmp + 1, tr, Math.max(l, tmp + 1), r); //Так в e-maxx }//o(logn) static class FastScanner { BufferedReader br; StringTokenizer stok; FastScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } String next() throws IOException { while (stok == null || !stok.hasMoreTokens()) { String s = br.readLine(); if (s == null) { return null; } stok = new StringTokenizer(s); } return stok.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()); } char nextChar() throws IOException { return (char) (br.read()); } String nextLine() throws IOException { return br.readLine(); } } }
Java
["3 1\n1 3 3", "3 2\n1 3 3\n1 3 2"]
1 second
["YES\n3 3 3", "NO"]
null
Java 8
standard input
[ "data structures", "constructive algorithms", "trees" ]
0b204773f8d06362b7569bd82224b218
The first line contains two integers n, m (1 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≤ li ≤ ri ≤ n, 0 ≤ qi &lt; 230) describing the i-th limit.
1,800
If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≤ a[i] &lt; 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line.
standard output
PASSED
f728eba87de4eb3d70a9542fdaa70aa4
train_001.jsonl
1414170000
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≤ li ≤ ri ≤ n) meaning that value should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist.Expression x&amp;y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&amp;", in Pascal — as "and".
256 megabytes
//package Graphs; import java.io.*; import java.util.Arrays; import java.util.StringTokenizer; public class main482B { public static PrintWriter out = new PrintWriter(System.out); public static FastScanner enter = new FastScanner(System.in); public static void main(String[] args) throws IOException { int n = enter.nextInt(); int m = enter.nextInt(); int[] l = new int[m]; int[] r = new int[m]; long[] q = new long[m]; long[][] ans = new long[n + 2][30]; for (int i = 0; i < m; i++) { l[i] = enter.nextInt(); r[i] = enter.nextInt(); q[i] = enter.nextLong(); long a = 1; for (int j = 0; j < 30; j++, a = a << 1) { if ((a & q[i]) != 0) { ans[l[i]][j]+= 1; ans[r[i] + 1][j]-=1; } } } for (int j = 0; j < 30; j++) { for (int i = 1; i < n + 2; i++) { ans[i][j] += ans[i - 1][j]; } } for (int j = 0; j < 30; j++) { for (int i = 1; i < n + 1; i++) { ans[i][j] = (ans[i][j] > 0) ? 1 : 0; } } long a[] = new long[n + 1]; for (int i = 1; i < n + 1; i++) { for (int j = 0; j < 30; j++) { a[i] += ans[i][j] * (1 << j); } } //build segtree on mass a[] /*System.out.println(536870912&1073741823); System.out.println(536870911&1073741823); System.out.println(536870911&536870912); System.out.println(Arrays.toString(a));*/ long t[] = new long[4 * n + 1]; build(t, a, 1, 1, n); /*System.out.println(Arrays.toString(t)); System.out.println(sum(t,1,1,n,5,5)); System.out.println(sum(t,1,1,n,2,2)); System.out.println(sum(t,1,1,n,3,3));*/ for (int i = 0; i <m ; i++) { if(sum(t,1,1, n, l[i], r[i])!=q[i]){ System.out.println("NO"); return; } } System.out.println("YES"); for (int i = 1; i < n + 1; i++) { System.out.print(a[i] + " "); } /*long f[] ={-7,1,2,3,4}; long t[]=new long[20]; build(t,f,1,1,4); System.out.println(sum(t,1,1,4, 1,4)); System.out.println(sum(t,1,1,4, 1,1)); System.out.println(sum(t,1,1,4, 2,2)); System.out.println(sum(t,1,1,4, 3,3)); System.out.println(sum(t,1,1,4, 1,3));*/ } public static void build(long t[], long arr[], int v, int tl, int tr) { //По массиву arr строим if (tl == tr) { t[v] = arr[tl]; return; } int tmp = (tl + tr) / 2; build(t, arr, 2 * v, tl, tmp); build(t, arr, 2 * v + 1, tmp + 1, tr); t[v] = t[2 * v] & t[2 * v + 1]; //К примеру это построили сумму на отрехке l,r - можно кучу всего другого }//o(n) public static long sum(long t[], int v, int tl, int tr, int l, int r) { if (l > r) return (1 << 30) - 1; if (l == tl && r == tr) { return t[v]; } int tmp = (tl + tr) / 2; /*System.out.println(2*v+" "+tl+" "+ tmp); System.out.println((2*v+1)+" "+ (tmp+1)+" "+ tr); System.out.println(sum(t,2*v, tl,tmp, l, tmp)); System.out.println(sum(t,2*v+1, tmp+1, tr, tmp+1,r));*/ //return sum(t,2*v, tl,tmp, l, tmp)&sum(t,2*v+1, tmp+1, tr, tmp+1,r); return sum(t, 2 * v, tl, tmp, l, Math.min(r, tmp)) & sum(t, 2 * v + 1, tmp + 1, tr, Math.max(l, tmp + 1), r); //Так в e-maxx }//o(logn) static class FastScanner { BufferedReader br; StringTokenizer stok; FastScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } String next() throws IOException { while (stok == null || !stok.hasMoreTokens()) { String s = br.readLine(); if (s == null) { return null; } stok = new StringTokenizer(s); } return stok.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()); } char nextChar() throws IOException { return (char) (br.read()); } String nextLine() throws IOException { return br.readLine(); } } }
Java
["3 1\n1 3 3", "3 2\n1 3 3\n1 3 2"]
1 second
["YES\n3 3 3", "NO"]
null
Java 8
standard input
[ "data structures", "constructive algorithms", "trees" ]
0b204773f8d06362b7569bd82224b218
The first line contains two integers n, m (1 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≤ li ≤ ri ≤ n, 0 ≤ qi &lt; 230) describing the i-th limit.
1,800
If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≤ a[i] &lt; 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line.
standard output
PASSED
297042ea1b28b5291f50114bea42e210
train_001.jsonl
1414170000
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≤ li ≤ ri ≤ n) meaning that value should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist.Expression x&amp;y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&amp;", in Pascal — as "and".
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class InterestingArray { public static void main(String[] args) throws NumberFormatException, IOException { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int N = (int) Math.pow(2, Math.ceil(Math.log(n)/Math.log(2))); int m = sc.nextInt(); int a[] = new int[N+1]; SegmentTree tree = new SegmentTree(a); int l[] = new int[m]; int r[] = new int[m]; int q[] = new int[m]; for(int i=0; i<m; i++) { l[i] = sc.nextInt(); r[i] = sc.nextInt(); q[i] = sc.nextInt(); tree.update_range(l[i], r[i], q[i]); } for(int i=0; i<m; i++) { int res = tree.query(l[i], r[i]); if(res != q[i]) { System.out.println("NO"); return; } } PrintWriter out = new PrintWriter(System.out); out.println("YES"); for(int i=1; i<=n; i++) { out.print(tree.query(i, i)+" "); } out.flush(); } static class SegmentTree { int N; int[] array, sTree, lazy; SegmentTree(int[] in) { array = in; N = in.length - 1; sTree = new int[N<<1]; lazy = new int[N<<1]; } void update_range(int i, int j, int val) // O(log n) { update_range(1,1,N,i,j,val); } void update_range(int node, int b, int e, int i, int j, int val) { if(i > e || j < b) return; if(b >= i && e <= j) { sTree[node] |= val; lazy[node] |= val; } else { propagate(node, b, e); update_range(node<<1,b,(b+e)/2,i,j,val); update_range((node<<1)+1,(b+e)/2+1,e,i,j,val); sTree[node] = sTree[node<<1] & sTree[(node<<1)+1]; } } void propagate(int node, int b, int e) { lazy[node<<1] |= lazy[node]; lazy[(node<<1)+1] |= lazy[node]; sTree[node<<1] |= lazy[node]; sTree[(node<<1)+1] |= lazy[node]; lazy[node] = 0; } int query(int i, int j) { return query(1,1,N,i,j); } int query(int node, int b, int e, int i, int j) // O(log n) { if(i>e || j <b) return -1; if(b>= i && e <= j) return sTree[node]; propagate(node, b, e); return query(node<<1,b,(b+e)/2,i,j) & query((node<<1)+1,(b+e)/2+1,e,i,j); } } static class Scanner { BufferedReader br; StringTokenizer st; Scanner(FileReader f) { br = new BufferedReader(f); } public boolean ready() throws IOException { return br.ready(); } Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws IOException { return br.readLine(); } int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } } }
Java
["3 1\n1 3 3", "3 2\n1 3 3\n1 3 2"]
1 second
["YES\n3 3 3", "NO"]
null
Java 8
standard input
[ "data structures", "constructive algorithms", "trees" ]
0b204773f8d06362b7569bd82224b218
The first line contains two integers n, m (1 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≤ li ≤ ri ≤ n, 0 ≤ qi &lt; 230) describing the i-th limit.
1,800
If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≤ a[i] &lt; 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line.
standard output
PASSED
55c199647bd27c6b51ed3526d438591e
train_001.jsonl
1414170000
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≤ li ≤ ri ≤ n) meaning that value should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist.Expression x&amp;y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&amp;", in Pascal — as "and".
256 megabytes
import java.io.*; import java.util.*; public class b implements Runnable{ public static void main (String[] args) {new Thread(null, new b(), "_cf", 1 << 28).start();} public void run() { FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); System.err.println("Go!"); int n = fs.nextInt(); int m = fs.nextInt(); int[][] upd = new int[30][n+1]; int[][] vs = new int[3][m]; for(int i = 0; i < m; i++) { int l = fs.nextInt()-1, r = fs.nextInt()-1; int q = fs.nextInt(); vs[0][i] = l; vs[1][i] = r; vs[2][i] = q; for(int bit = 0; bit < 30; bit++) { upd[bit][l] += (q & (1 << bit)) > 0 ? 1 : 0; upd[bit][r+1] -= (q & (1 << bit)) > 0 ? 1 : 0; } } int curAND = 0; int[] cur = new int[30]; int[] res = new int[n]; for(int i = 0; i < n; i++) { for(int bit = 0; bit < 30; bit++) { int old = cur[bit]; cur[bit] += upd[bit][i]; if(old == 0 && cur[bit] > 0) curAND |= (1 << bit); else if(old > 0 && cur[bit] == 0) curAND ^= (1 << bit); } res[i] = curAND; } int log = Integer.numberOfTrailingZeros(Integer.highestOneBit(n)*2); int[][] sparse = new int[log][n]; for(int i = 0; i < n; i++) sparse[0][i] = res[i]; for(int p = 1, lastRange = 1; p < log; p++, lastRange *= 2) { for(int i = 0; i < n; i++) { sparse[p][i] = sparse[p-1][i] & sparse[p-1][Math.min(n-1, i+lastRange)]; } } for(int i = 0; i < m; i++) { int get = query(sparse, vs[0][i], vs[1][i]); if(get != vs[2][i]) { System.out.println("NO"); return; } } out.println("YES"); for(int i = 0; i < n; i++) { if(i > 0) out.print(" "); out.print(res[i]); } out.close(); } int query(int[][] sparse, int lo, int hi) { int range = hi-lo+1; int exp = Integer.highestOneBit(range); int lg = Integer.numberOfTrailingZeros(exp); return sparse[lg][lo] & sparse[lg][hi-exp+1]; } void sort (int[] a) { int n = a.length; for(int i = 0; i < 50; i++) { Random r = new Random(); int x = r.nextInt(n), y = r.nextInt(n); int temp = a[x]; a[x] = a[y]; a[y] = temp; } Arrays.sort(a); } class FastScanner { public int BS = 1<<16; public char NC = (char)0; byte[] buf = new byte[BS]; int bId = 0, size = 0; char c = NC; double num = 1; BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) throws FileNotFoundException { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } public char nextChar(){ 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 long nextLong() { num=1; boolean neg = false; if(c==NC)c=nextChar(); for(;(c<'0' || c>'9'); c = nextChar()) { if(c=='-')neg=true; } long res = 0; for(; c>='0' && c <='9'; c=nextChar()) { res = (res<<3)+(res<<1)+c-'0'; num*=10; } return neg?-res:res; } public double nextDouble() { double cur = nextLong(); return c!='.' ? cur:cur+nextLong()/num; } public String next() { StringBuilder res = new StringBuilder(); while(c<=32)c=nextChar(); while(c>32) { res.append(c); c=nextChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while(c<=32)c=nextChar(); while(c!='\n') { res.append(c); c=nextChar(); } return res.toString(); } public boolean hasNext() { if(c>32)return true; while(true) { c=nextChar(); if(c==NC)return false; else if(c>32)return true; } } public int[] nextIntArray(int n) { int[] res = new int[n]; for(int i = 0; i < n; i++) res[i] = nextInt(); return res; } } }
Java
["3 1\n1 3 3", "3 2\n1 3 3\n1 3 2"]
1 second
["YES\n3 3 3", "NO"]
null
Java 8
standard input
[ "data structures", "constructive algorithms", "trees" ]
0b204773f8d06362b7569bd82224b218
The first line contains two integers n, m (1 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≤ li ≤ ri ≤ n, 0 ≤ qi &lt; 230) describing the i-th limit.
1,800
If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≤ a[i] &lt; 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line.
standard output
PASSED
b6ccba6201a9488b3405b8f7668853b1
train_001.jsonl
1414170000
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≤ li ≤ ri ≤ n) meaning that value should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist.Expression x&amp;y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&amp;", in Pascal — as "and".
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.*; public class a { public static void main(String[] Args) throws Exception { FS sc = new FS(System.in); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int n = sc.nextInt(); int m = sc.nextInt(); int[] ls = new int[m]; int[] rs = new int[m]; int[] qs = new int[m]; for (int i = 0; i < m; i++){ ls[i] = sc.nextInt() - 1; rs[i] = sc.nextInt() - 1; qs[i] = sc.nextInt(); } int[] ans = new int[n]; int[] tmp = new int[n]; int[] sum = new int[n + 1]; for (int k = 0; k < 30; k++) { for (int i = 0; i < n; i++) sum[i] = 0; sum[n] = 0; for (int i = 0; i < m; i++) { if ((qs[i] & (1<<k)) != 0) { sum[ls[i]]++; sum[rs[i] + 1]--; } } int cc = sum[0]; for (int i = 0; i < n; i++) { tmp[i] = (cc == 0) ? 0 : 1; cc += sum[i + 1]; } sum[0] = 0; for (int i = 0; i < n; i++) { sum[i + 1] = sum[i] + tmp[i]; if (tmp[i] == 1) ans[i] |= (1<<k); } for (int i = 0; i < m; i++){ if ((qs[i] & (1<<k))==0 && sum[rs[i] + 1] - sum[ls[i]] == rs[i] + 1 - ls[i]) { out.println("NO"); out.close(); return; } } } out.println("YES"); for (int i = 0; i < n; i++){ out.print(ans[i] + " "); } out.close(); } public static class Pair implements Comparable<Pair> { int ind, type; Pair(int a, int b) { ind = a; type = b; } public int compareTo(Pair o) { if (ind == o.ind) return o.type - type; return ind - o.ind; } } public static class FS { BufferedReader br; StringTokenizer st; FS(InputStream in) throws Exception { br = new BufferedReader(new InputStreamReader(in)); st = new StringTokenizer(br.readLine()); } FS(File f) throws Exception { br = new BufferedReader(new FileReader(f)); st = new StringTokenizer(br.readLine()); } String next() throws Exception { if (st.hasMoreTokens()) return st.nextToken(); st = new StringTokenizer(br.readLine()); return next(); } int nextInt() throws Exception { return Integer.parseInt(next()); } long nextLong() throws Exception { return Long.parseLong(next()); } double nextDouble() throws Exception { return Double.parseDouble(next()); } } } /* * * 19 2 2 2 2 2 2 2 2 1 1 1 2 1 1 2 1 1 1 2 * * */
Java
["3 1\n1 3 3", "3 2\n1 3 3\n1 3 2"]
1 second
["YES\n3 3 3", "NO"]
null
Java 8
standard input
[ "data structures", "constructive algorithms", "trees" ]
0b204773f8d06362b7569bd82224b218
The first line contains two integers n, m (1 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≤ li ≤ ri ≤ n, 0 ≤ qi &lt; 230) describing the i-th limit.
1,800
If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≤ a[i] &lt; 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line.
standard output
PASSED
00affce4a2120bbe8326190d4b4ed293
train_001.jsonl
1414170000
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≤ li ≤ ri ≤ n) meaning that value should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist.Expression x&amp;y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&amp;", in Pascal — as "and".
256 megabytes
/* If you want to aim high, aim high Don't let that studying and grades consume you Just live life young ****************************** If I'm the sun, you're the moon Because when I go up, you go down ******************************* I'm working for the day I will surpass you https://www.a2oj.com/Ladder16.html */ import java.util.*; import java.io.*; import java.math.*; public class x482B { public static void main(String omkar[]) throws Exception { BufferedReader infile = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(infile.readLine()); int N = Integer.parseInt(st.nextToken()); int M = Integer.parseInt(st.nextToken()); StringBuilder sb = new StringBuilder(); Range[] ranges = new Range[M]; for(int i=0; i < M; i++) { st = new StringTokenizer(infile.readLine()); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); int c = Integer.parseInt(st.nextToken()); ranges[i] = new Range(a,b,c); } int[][] cnt = new int[N][30]; for(Range r: ranges) for(int b=0; b < 30; b++) if((r.val&(1<<b)) > 0) { cnt[r.left][b]++; if(r.right+1 < N) cnt[r.right+1][b]--; } int[] res = new int[N]; for(int b=0; b < 30; b++) { int val = 0; for(int i=0; i < N; i++) { val += cnt[i][b]; if(val > 0) res[i] += (1 << b); } } SegmentTree tree = new SegmentTree(0, N+1); for(int i=0; i < N; i++) tree.update(i, res[i]); for(Range r: ranges) if(tree.query(r.left, r.right) != r.val) { System.out.println("NO"); return; } System.out.println("YES"); for(int x: res) sb.append(x+" "); System.out.println(sb); } } class Range { public int left; public int right; public int val; public Range(int a, int b, int c) { left = a-1; right = b-1; val = c; } } class SegmentTree { //range query, non lazy final int[] val; final int treeFrom; final int length; public SegmentTree(int treeFrom, int treeTo) { this.treeFrom = treeFrom; int length = treeTo - treeFrom + 1; int l; for (l = 0; (1 << l) < length; l++); val = new int[1 << (l + 1)]; this.length = 1 << l; } public void update(int index, int delta) { //replaces value int node = index - treeFrom + length; val[node] = delta; for (node >>= 1; node > 0; node >>= 1) val[node] = comb(val[node << 1], val[(node << 1) + 1]); } public int query(int from, int to) { //inclusive bounds if (to < from) return 0; //0 or 1? from += length - treeFrom; to += length - treeFrom + 1; //0 or 1? int res = (1 << 30)-1; for (; from + (from & -from) <= to; from += from & -from) res = comb(res, val[from / (from & -from)]); for (; to - (to & -to) >= from; to -= to & -to) res = comb(res, val[(to - (to & -to)) / (to & -to)]); return res; } public int comb(int a, int b) { //change this return a&b; } }
Java
["3 1\n1 3 3", "3 2\n1 3 3\n1 3 2"]
1 second
["YES\n3 3 3", "NO"]
null
Java 8
standard input
[ "data structures", "constructive algorithms", "trees" ]
0b204773f8d06362b7569bd82224b218
The first line contains two integers n, m (1 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≤ li ≤ ri ≤ n, 0 ≤ qi &lt; 230) describing the i-th limit.
1,800
If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≤ a[i] &lt; 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line.
standard output
PASSED
7eb5f175ed5999e0c6c29cddd436e62f
train_001.jsonl
1414170000
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≤ li ≤ ri ≤ n) meaning that value should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist.Expression x&amp;y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&amp;", in Pascal — as "and".
256 megabytes
import java.io.*; import java.util.*; public class B { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; void solve() throws IOException { int n = nextInt(); int m = nextInt(); int[] low = new int[m]; int[] high = new int[m]; int[] val = new int[m]; for (int i = 0; i < m; i++) { low[i] = nextInt() - 1; high[i] = nextInt() - 1; val[i] = nextInt(); } int[] ans = new int[n]; for (int bit = 0; bit < 30; bit++) { int[] arr = new int[n + 1]; for (int i = 0; i < m; i++) { if ((val[i] & 1) == 1) { // System.err.println(bit + " " + i); arr[low[i]]++; arr[high[i] + 1]--; } } for (int i = 1; i <= n; i++) { arr[i] += arr[i - 1]; } for (int i = 0; i <= n; i++) { arr[i] = Math.min(arr[i], 1); } int[] sums = new int[n + 1]; sums[0] = arr[0]; for (int i = 1; i <= n; i++) { sums[i] = sums[i - 1] + arr[i]; } for (int i = 0; i < m; i++) { if ((val[i] & 1) == 0) { int sum = sums[high[i]]; if (low[i] > 0) { sum -= sums[low[i] - 1]; } if (sum == high[i] - low[i] + 1) { out.println("NO"); return; } } } for (int i = 0; i < n; i++) { ans[i] |= arr[i] << bit; } for (int i = 0; i < m; i++) { val[i] >>= 1; } } out.println("YES"); for (int i = 0; i < n; i++) { out.print(ans[i] + " "); } } B() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } public static void main(String[] args) throws IOException { new B(); } String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } String nextString() { try { return br.readLine(); } catch (IOException e) { eof = true; return null; } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
Java
["3 1\n1 3 3", "3 2\n1 3 3\n1 3 2"]
1 second
["YES\n3 3 3", "NO"]
null
Java 8
standard input
[ "data structures", "constructive algorithms", "trees" ]
0b204773f8d06362b7569bd82224b218
The first line contains two integers n, m (1 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≤ li ≤ ri ≤ n, 0 ≤ qi &lt; 230) describing the i-th limit.
1,800
If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≤ a[i] &lt; 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line.
standard output
PASSED
1cbd79e3270fbc1c9455c64f9c1948d1
train_001.jsonl
1414170000
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≤ li ≤ ri ≤ n) meaning that value should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist.Expression x&amp;y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&amp;", in Pascal — as "and".
256 megabytes
import java.io.*; import java.util.*; public class Main implements Runnable { private class Query { private int id; private int l; private int r; private int q; Query(int l,int r,int q,int id) { this.l=l; this.r=r; this.q=q; this.id=id; } } public static void main(String args[]) { new Main().run(); } public void run() { try { solve(); } catch (IOException e) { e.printStackTrace(); } out.flush(); } private void solve() throws IOException { int n=in.nextInt(); int m=in.nextInt(); int ds=getds(n); int v[]=new int[2*ds]; // Query q[]=new Query[m]; int l[]=new int[m]; int r[]=new int[m]; int q[]=new int[m]; for(int i=0;i<m;i++) { l[i]=in.nextInt()-1; r[i]=in.nextInt()-1; q[i]=in.nextInt(); } for(int i=0;i<m;i++) inc(l[i],r[i],q[i], v, ds); push(v,ds); int arr[]=new int[n]; for(int i=0;i<n;i++) arr[i]=v[i+ds]; boolean ok=true; for(int i=ds-1;i>0;i--) v[i]=v[2*i]&v[2*i+1]; for(int i=0;i<m;i++) ok&=(accumulate(l[i],r[i],v,ds)==q[i]); if(ok) { out.println("YES"); for(int i:arr) { out.print(i); out.print(' '); } out.println(); } else out.println("NO"); } private void push(int [] v, int ds) { for(int i=1;i<ds;i++) { v[2*i]|=v[i]; v[2*i+1]|=v[i]; } } private void inc(int l, int r, int val, int[] v, int ds) { l+=ds; r+=ds; while(l<=r) { if((l&1)==1) v[l++]|=val; if((r&1)==0) v[r--]|=val; l>>=1; r>>=1; } } private int accumulate(int l, int r, int[] v, int ds) { l+=ds; r+=ds; int res=(1<<30)-1; while(l<=r) { if((l&1)==1) res=res&v[l++]; if((r&1)==0) res=res&v[r--]; l>>=1; r>>=1; } return res; } private int getds(int n) { n--; n|=n>>1; n|=n>>2; n|=n>>4; n|=n>>8; n|=n>>16; return n+1; } private boolean testbit(int q, int i) { return ((q>>i)&1)==1; } class Scanner { BufferedReader in; StringTokenizer token; String delim; Scanner(Reader reader) { in=new BufferedReader(reader); token=new StringTokenizer(""); this.delim=" \n"; } Scanner(Reader reader, String delimeters) { in=new BufferedReader(reader); token=new StringTokenizer(""); this.delim=delimeters; } public boolean hasNext() throws IOException { while(!token.hasMoreTokens()) { String line=in.readLine(); if(line==null) return false; token=new StringTokenizer(line); } return true; } String next() throws IOException { return hasNext()?token.nextToken():null; } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } int[] nextInts(int n) throws IOException { int[] res=new int[n]; for(int i=0;i<n;i++) res[i]=nextInt(); return res; } } private Scanner in=new Scanner(new InputStreamReader(System.in),"\n\r\t "); private PrintWriter out=new PrintWriter(new BufferedWriter( new OutputStreamWriter(System.out))); }
Java
["3 1\n1 3 3", "3 2\n1 3 3\n1 3 2"]
1 second
["YES\n3 3 3", "NO"]
null
Java 8
standard input
[ "data structures", "constructive algorithms", "trees" ]
0b204773f8d06362b7569bd82224b218
The first line contains two integers n, m (1 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≤ li ≤ ri ≤ n, 0 ≤ qi &lt; 230) describing the i-th limit.
1,800
If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≤ a[i] &lt; 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line.
standard output
PASSED
0e96ba2cd6bbec7a5993f6984a5ceafb
train_001.jsonl
1414170000
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≤ li ≤ ri ≤ n) meaning that value should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist.Expression x&amp;y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&amp;", in Pascal — as "and".
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.math.BigDecimal; import java.math.MathContext; import java.math.RoundingMode; import java.util.*; public class Main implements Runnable { private class Query { private int id; private int l; private int r; private int q; Query(int l,int r,int q,int id) { this.l=l; this.r=r; this.q=q; this.id=id; } } public static void main(String args[]) { new Main().run(); } public void run() { try { solve(); } catch (IOException e) { e.printStackTrace(); } out.flush(); } private void solve() throws IOException { int n=in.nextInt(); int m=in.nextInt(); Query q[]=new Query[m]; for(int i=0;i<m;i++) q[i]=new Query(in.nextInt()-1, in.nextInt()-1, in.nextInt(), i); int arr[]=new int[n]; Arrays.fill(arr, 0); int inc[]=new int[n+1]; for(int i=0;i<30;i++) { Arrays.fill(inc, 0); for(int j=0;j<m;j++) { if(testbit(q[j].q,i)) { inc[q[j].l]++; inc[q[j].r+1]--; } } int val=0; for(int j=0;j<n;j++) { val+=inc[j]; if(val!=0) arr[j]|=(1<<i); } } int ds=getds(n); int v[]=new int[2*ds]; boolean ok=true; Arrays.fill(v, 0); for(int i=0;i<n;i++) v[i+ds]=arr[i]; for(int i=ds-1;i>0;i--) v[i]=v[2*i]&v[2*i+1]; for(int i=0;i<m;i++) ok&=(accumulate(q[i].l,q[i].r,v,ds)==q[i].q); if(ok) { out.println("YES"); for(int i:arr) { out.print(i); out.print(' '); } out.println(); } else out.println("NO"); } private int accumulate(int l, int r, int[] v, int ds) { l+=ds; r+=ds; int res=(1<<30)-1; while(l<=r) { if((l&1)==1) res=res&v[l++]; if((r&1)==0) res=res&v[r--]; l>>=1; r>>=1; } return res; } private int getds(int n) { n--; n|=n>>1; n|=n>>2; n|=n>>4; n|=n>>8; n|=n>>16; return n+1; } private boolean testbit(int q, int i) { return ((q>>i)&1)==1; } class Scanner { BufferedReader in; StringTokenizer token; String delim; Scanner(Reader reader) { in=new BufferedReader(reader); token=new StringTokenizer(""); this.delim=" \n"; } Scanner(Reader reader, String delimeters) { in=new BufferedReader(reader); token=new StringTokenizer(""); this.delim=delimeters; } public boolean hasNext() throws IOException { while(!token.hasMoreTokens()) { String line=in.readLine(); if(line==null) return false; token=new StringTokenizer(line,delim); } return true; } String next() throws IOException { return hasNext()?token.nextToken():null; } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } int[] nextInts(int n) throws IOException { int[] res=new int[n]; for(int i=0;i<n;i++) res[i]=nextInt(); return res; } } private Scanner in=new Scanner(new InputStreamReader(System.in),"\n\r\t "); private PrintWriter out=new PrintWriter(new BufferedWriter( new OutputStreamWriter(System.out))); }
Java
["3 1\n1 3 3", "3 2\n1 3 3\n1 3 2"]
1 second
["YES\n3 3 3", "NO"]
null
Java 8
standard input
[ "data structures", "constructive algorithms", "trees" ]
0b204773f8d06362b7569bd82224b218
The first line contains two integers n, m (1 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≤ li ≤ ri ≤ n, 0 ≤ qi &lt; 230) describing the i-th limit.
1,800
If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≤ a[i] &lt; 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line.
standard output
PASSED
a73fe24cdfc5ce70c1a2a7c934a115f8
train_001.jsonl
1414170000
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≤ li ≤ ri ≤ n) meaning that value should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist.Expression x&amp;y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&amp;", in Pascal — as "and".
256 megabytes
import java.io.*; import java.util.Arrays; import java.util.StringTokenizer; public class B { final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); class Triple implements Comparable<Triple> { int l; int r; int res; Triple(int l, int r, int res) { this.l = l; this.r = r; this.res = res; } @Override public int compareTo(Triple o) { return l - o.l; } } void solve() throws IOException { int n = readInt(); int q = readInt(); Triple[] qs = new Triple[q]; for (int i = 0; i < q; i++) { qs[i] = new Triple(readInt() - 1, readInt() - 1, readInt()); } Arrays.sort(qs); int[] res = new int[n]; int[] prefix = new int[n]; for (int i = 0; i < 30; i++) { int lastOne = -1; int lastZero = -1; for (int j = 0; j < q; j++) { if ((qs[j].res & (1 << i)) != 0) { int from = Math.max(qs[j].l, lastOne); int to = Math.max(qs[j].r, lastOne); for (int k = from; k <= to; k++) { res[k] |= (1 << i); } lastOne = Math.max(lastOne, to); } } Arrays.fill(prefix, 0); prefix[0] = (res[0] & (1 << i)) == 0 ? 1 : 0; for(int j = 1; j < n; j++) { prefix[j] = prefix[j-1] + ((res[j] & (1 << i)) == 0 ? 1 : 0); } for (int j = 0; j < q; j++) { if ((qs[j].res & (1 << i)) == 0) { int r = prefix[qs[j].r]; int l = qs[j].l == 0 ? 0 : prefix[qs[j].l-1]; if(r-l == 0) { out.print("NO"); return; } } } } out.println("YES"); for (int i = 0; i < n; i++) { out.print(res[i] + " "); } } void init() throws FileNotFoundException { if (ONLINE_JUDGE) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } } String readString() throws IOException { while (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } int[] readArr(int n) throws IOException { int[] res = new int[n]; for (int i = 0; i < n; i++) { res[i] = readInt(); } return res; } long[] readArrL(int n) throws IOException { long[] res = new long[n]; for (int i = 0; i < n; i++) { res[i] = readLong(); } return res; } public static void main(String[] args) { new B().run(); } public void run() { try { long t1 = System.currentTimeMillis(); init(); solve(); out.close(); long t2 = System.currentTimeMillis(); System.err.println("Time = " + (t2 - t1)); } catch (Exception e) { e.printStackTrace(System.err); System.exit(-1); } } }
Java
["3 1\n1 3 3", "3 2\n1 3 3\n1 3 2"]
1 second
["YES\n3 3 3", "NO"]
null
Java 8
standard input
[ "data structures", "constructive algorithms", "trees" ]
0b204773f8d06362b7569bd82224b218
The first line contains two integers n, m (1 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≤ li ≤ ri ≤ n, 0 ≤ qi &lt; 230) describing the i-th limit.
1,800
If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≤ a[i] &lt; 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line.
standard output
PASSED
d37a209ae6e6f534ffc7a197f5f8643f
train_001.jsonl
1414170000
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≤ li ≤ ri ≤ n) meaning that value should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist.Expression x&amp;y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&amp;", in Pascal — as "and".
256 megabytes
//package DSU; import java.io.*; import java.util.Arrays; import java.util.StringTokenizer; public class B482 { public static void main(String[] args) throws IOException, InterruptedException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(); SegmentTree st = new SegmentTree(n); boolean flag = true; int m = sc.nextInt(); Triple q[] = new Triple[m]; for (int i = 0; i < m; i++) q[i] = new Triple(sc.nextInt(), sc.nextInt(), sc.nextInt()); for (int i = 0; i < m; i++) { // System.out.println(q[i].l+" "+q[i].r+" "+q[i].q); st.update_range(q[i].l, q[i].r, q[i].q); } for (int i = 0; i < m; i++) { if (st.query(q[i].l, q[i].r) != q[i].q) { // System.out.println(st.query(q[i].l, q[i].r)+" "+q[i].q); // System.out.println(q[i].l+" "+q[i].r); // System.out.println(Arrays.toString(st.sTree)); // System.out.println(0|3); flag = false; break; } } if (!flag) pw.println("NO"); else { pw.println("YES"); for(int i=1;i<st.N;i++) st.propagate(i, 1, 100000, st.N); for (int i = 1; i <= n; i++) pw.print(st.sTree[st.N + i - 1] + " "); } pw.flush(); } static class Triple { int l, r, q; Triple(int a, int b, int c) { l = a; r = b; q = c; } } static class SegmentTree { int N; int[] array, sTree, lazy; SegmentTree(int in) { N = 1; while (N < in) N <<= 1; sTree = new int[N << 1]; lazy = new int[N << 1]; } void update_range(int i, int j, int val) { update_range(1, 1, N, i, j, val); } void update_range(int node, int b, int e, int i, int j, int val) { // System.out.println(N); // System.out.println(b+" "+e+" "+i+" "+j+" "+val); if (i > e || j < b) { // System.out.println(" in first if statement "); return; } if (b >= i && e <= j) { sTree[node] |= val; // System.out.println(sTree[node]+" "+val); lazy[node] |= val; return; } else { // System.out.println(" in else "); int mid = b + e >> 1; propagate(node, b, mid, e); update_range(node << 1, b, mid, i, j, val); update_range(node << 1 | 1, mid + 1, e, i, j, val); sTree[node] = sTree[node << 1] & sTree[node << 1 | 1]; } } void propagate(int node, int b, int mid, int e) { lazy[node << 1] |= lazy[node]; lazy[node << 1 | 1] |= lazy[node]; sTree[node << 1] |= lazy[node]; sTree[node << 1 | 1] |= lazy[node]; lazy[node] = 0; } int query(int i, int j) { return query(1, 1, N, i, j); } int query(int node, int b, int e, int i, int j) { if (i > e || j < b) return -1; if (b >= i && e <= j) return sTree[node]; int mid = b + e >> 1; propagate(node, b, mid, e); int q1 = query(node << 1, b, mid, i, j); int q2 = query(node << 1 | 1, mid + 1, e, i, j); return q1 & q2; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public 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(4000); } } }
Java
["3 1\n1 3 3", "3 2\n1 3 3\n1 3 2"]
1 second
["YES\n3 3 3", "NO"]
null
Java 8
standard input
[ "data structures", "constructive algorithms", "trees" ]
0b204773f8d06362b7569bd82224b218
The first line contains two integers n, m (1 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≤ li ≤ ri ≤ n, 0 ≤ qi &lt; 230) describing the i-th limit.
1,800
If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≤ a[i] &lt; 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line.
standard output
PASSED
e9198d1ffd3691578100fbc78936b965
train_001.jsonl
1414170000
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≤ li ≤ ri ≤ n) meaning that value should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist.Expression x&amp;y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&amp;", in Pascal — as "and".
256 megabytes
//package SegmentFenwick; import java.io.*; import java.util.StringTokenizer; public class practice { public static void main(String[] args) throws IOException, InterruptedException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); PrintWriter pw = new PrintWriter(System.out); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); int N = 1; while (N < n) N <<= 1; Triple in[] = new Triple[m]; for (int i = 0; i < m; i++) { st = new StringTokenizer(br.readLine()); int l = Integer.parseInt(st.nextToken()); int r = Integer.parseInt(st.nextToken()); int q = Integer.parseInt(st.nextToken()); in[i] = new Triple(l, r, q); } SegmentTree stt = new SegmentTree(N); for (int i = 0; i < m; i++) stt.update_range(in[i].a, in[i].b, in[i].c); for (int i = 0; i < m; i++) if (stt.query(in[i].a, in[i].b) != in[i].c) { System.out.println("NO"); return; } pw.println("YES"); for (int i = 1; i < stt.N; i++) stt.propagate(i, 1, 100000, stt.N); for (int i = 1; i <= n; i++) pw.print(stt.sTree[stt.N + i - 1] + " "); pw.flush(); } static class Triple { int a, b, c; Triple(int x, int y, int z) { a = x; b = y; c = z; } } static class SegmentTree { // 1-based DS, OOP int N; // the number of elements in the array as a power of 2 (i.e. after padding) int[] array, sTree, lazy; SegmentTree(int in) { N = 1; while (N < in) N <<= 1; sTree = new int[N << 1]; // no. of nodes = 2*N - 1, we add one to cross out index zero lazy = new int[N << 1]; } void update_range(int i, int j, int val) // O(log n) { update_range(1, 1, N, i, j, val); } void update_range(int node, int b, int e, int i, int j, int val) { if (i > e || j < b) return; if (b >= i && e <= j) { sTree[node] |= val; lazy[node] |= val; } else { int mid = b + e >> 1; propagate(node, b, mid, e); update_range(node << 1, b, mid, i, j, val); update_range(node << 1 | 1, mid + 1, e, i, j, val); sTree[node] = sTree[node << 1] & sTree[node << 1 | 1]; } } void propagate(int node, int b, int mid, int e) { lazy[node << 1] |= lazy[node]; lazy[node << 1 | 1] |= lazy[node]; sTree[node << 1] |= lazy[node]; sTree[node << 1 | 1] |= lazy[node]; lazy[node] = 0; } int query(int i, int j) { return query(1, 1, N, i, j); } int query(int node, int b, int e, int i, int j) // O(log n) { if (i > e || j < b) return -1; if (b >= i && e <= j) return sTree[node]; int mid = b + e >> 1; propagate(node, b, mid, e); int q1 = query(node << 1, b, mid, i, j); int q2 = query(node << 1 | 1, mid + 1, e, i, j); return q1 & q2; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public 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(4000); } } }
Java
["3 1\n1 3 3", "3 2\n1 3 3\n1 3 2"]
1 second
["YES\n3 3 3", "NO"]
null
Java 8
standard input
[ "data structures", "constructive algorithms", "trees" ]
0b204773f8d06362b7569bd82224b218
The first line contains two integers n, m (1 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≤ li ≤ ri ≤ n, 0 ≤ qi &lt; 230) describing the i-th limit.
1,800
If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≤ a[i] &lt; 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line.
standard output
PASSED
2cd78059d14916aa4308cde6db2f02a2
train_001.jsonl
1414170000
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≤ li ≤ ri ≤ n) meaning that value should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist.Expression x&amp;y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&amp;", in Pascal — as "and".
256 megabytes
import java.util.*; import java.io.*; public class abc{ static void Construct(int seg[],int l,int r,int pos,int a[]){ if(l==r){ seg[pos]=a[l]; return; } int m=(l+r)/2; Construct(seg,l,m,2*pos+1,a); Construct(seg,m+1,r,2*pos+2,a); seg[pos]=(seg[2*pos+1]&seg[2*pos+2]); } static int Query(int seg[],int l,int r,int ql,int qr,int pos){ if(qr<l||ql>r) return(-1); else if(ql<=l&&qr>=r) return(seg[pos]); int m=(l+r)/2; int x1= Query(seg,l,m,ql,qr,2*pos+1); int x2= Query(seg,m+1,r,ql,qr,2*pos+2); return(x1&x2); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int MAXBIT=30; int n = sc.nextInt(); int m = sc.nextInt(); int L[] = new int[m]; int R[] = new int[m]; int q[] = new int[m]; for(int i=0;i<m;i++){ L[i]=sc.nextInt(); R[i]=sc.nextInt(); q[i]=sc.nextInt(); L[i]--; } int sum[] = new int[n+2]; int a[] = new int[n]; int seg[] = new int[4*n]; for(int bit = 0; bit <= MAXBIT; bit++) { for(int i = 0; i < n; i++) sum[i] = 0; for(int i = 0; i < m; i++) { if (((q[i] >> bit)&1)>0) { sum[L[i]]++; sum[R[i]]--; } } for(int i = 0; i < n; i++) { if (i > 0) sum[i] += sum[i - 1]; if (sum[i] > 0) a[i] |= (1 << bit); } } Construct(seg,0,n-1,0,a); int flag=1; for(int i=0;i<m;i++){ if(Query(seg,0,n-1,L[i],R[i]-1,0)!=q[i]){ flag=0; break; } } if(flag==0) out.println("NO"); else{ out.println("YES"); for(int i=0;i<n;i++) out.print(a[i]+" "); } out.flush(); } }
Java
["3 1\n1 3 3", "3 2\n1 3 3\n1 3 2"]
1 second
["YES\n3 3 3", "NO"]
null
Java 8
standard input
[ "data structures", "constructive algorithms", "trees" ]
0b204773f8d06362b7569bd82224b218
The first line contains two integers n, m (1 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≤ li ≤ ri ≤ n, 0 ≤ qi &lt; 230) describing the i-th limit.
1,800
If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≤ a[i] &lt; 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line.
standard output
PASSED
696e6683b3a70930721781fc95144e35
train_001.jsonl
1414170000
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≤ li ≤ ri ≤ n) meaning that value should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist.Expression x&amp;y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&amp;", in Pascal — as "and".
256 megabytes
import java.util.List; import java.io.InputStreamReader; import java.io.IOException; import java.util.Arrays; import java.util.ArrayList; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Tifuera */ 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); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { public static final int BITS = 30; public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); int[] L = new int[m]; int[] R = new int[m]; int[] Q = new int[m]; List<Condition> conditions = new ArrayList<>(m); for (int i = 0; i < m; i++) { L[i] = in.nextInt() - 1; R[i] = in.nextInt() - 1; Q[i] = in.nextInt(); conditions.add(new Condition(L[i], R[i], Q[i])); } int[] answer = new int[n]; int[] bits = new int[n]; for (int i = 0; i <= BITS; i++) { Arrays.fill(bits, 0); constructBits(conditions, i, bits); for (int j = 0; j < n; j++) { if (bits[j] > 0) { answer[j] += (bits[j] << i); } } } if (isSolutionCorrect(conditions, answer)) { out.println("YES"); for (int a : answer) { out.print(a + " "); } } else { out.println("NO"); } } //TODO use segment tree to verify solution private boolean isSolutionCorrect(List<Condition> conditions, int[] answer) { SimpleSegmentTree segmentTree = new SimpleSegmentTree(answer); for (Condition cond : conditions) { if (segmentTree.logicalAnd(cond.l, cond.r) != cond.q) { return false; } } return true; } private void constructBits(List<Condition> conditions, int pos, int[] bits) { int[] arr = new int[bits.length + 1]; for (Condition cond : conditions) { int cur = (cond.q >> pos) & 1; if (cur == 1) { arr[cond.l]++; arr[cond.r + 1]--; } } int s = 0; for (int i = 0; i < bits.length; i++) { s += arr[i]; if (s > 0) { bits[i] = 1; } } } private static class Condition { int l; int r; int q; private Condition(int l, int r, int q) { this.l = l; this.r = r; this.q = q; } } private static class SimpleSegmentTree { private int n; private int[] tree; private int[] initialValues; private SimpleSegmentTree(int[] initialValues) { this.initialValues = initialValues; this.n = initialValues.length; tree = new int[4 * n]; init(0, n - 1, 1); } private void init(int left, int right, int v) { if (left == right) { tree[v] = initialValues[left]; } else { int mid = (left + right) / 2; init(left, mid, 2 * v); init(mid + 1, right, 2 * v + 1); tree[v] = tree[2 * v] & tree[2 * v + 1]; } } private int logicalAnd(int left, int right) { return logicalAnd(1, 0, n - 1, left, right); } private int logicalAnd(int v, int vLeft, int vRight, int left, int right) { if (left > right) { return (2 << BITS) - 1; } else { if (vLeft == left && vRight == right) { return tree[v]; } int vMid = (vLeft + vRight) / 2; int leftAns = logicalAnd(2 * v, vLeft, vMid, left, Math.min(right, vMid)); int rightAns = logicalAnd(2 * v + 1, vMid + 1, vRight, Math.max(left, vMid + 1), right); return leftAns & rightAns; } } } } class InputReader { private BufferedReader reader; private String[] currentArray; private int curPointer; public InputReader(InputStream inputStream) { reader = new BufferedReader(new InputStreamReader(inputStream)); } public int nextInt() { if ((currentArray == null) || (curPointer >= currentArray.length)) { try { currentArray = reader.readLine().split(" "); } catch (IOException e) { throw new RuntimeException(e); } curPointer = 0; } return Integer.parseInt(currentArray[curPointer++]); } }
Java
["3 1\n1 3 3", "3 2\n1 3 3\n1 3 2"]
1 second
["YES\n3 3 3", "NO"]
null
Java 8
standard input
[ "data structures", "constructive algorithms", "trees" ]
0b204773f8d06362b7569bd82224b218
The first line contains two integers n, m (1 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≤ li ≤ ri ≤ n, 0 ≤ qi &lt; 230) describing the i-th limit.
1,800
If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≤ a[i] &lt; 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line.
standard output
PASSED
a3144e25730c3d0d9283bc4e25a2fb37
train_001.jsonl
1414170000
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≤ li ≤ ri ≤ n) meaning that value should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist.Expression x&amp;y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&amp;", in Pascal — as "and".
256 megabytes
import java.util.List; import java.io.InputStreamReader; import java.io.IOException; import java.util.Arrays; import java.util.ArrayList; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Tifuera */ 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); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { public static final int BITS = 29; public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); int[] L = new int[m]; int[] R = new int[m]; int[] Q = new int[m]; List<Condition> conditions = new ArrayList<>(m); for (int i = 0; i < m; i++) { L[i] = in.nextInt() - 1; R[i] = in.nextInt() - 1; Q[i] = in.nextInt(); conditions.add(new Condition(L[i], R[i], Q[i])); } int[] answer = new int[n]; int[] bits = new int[n]; for (int i = 0; i <= BITS; i++) { Arrays.fill(bits, 0); constructBits(conditions, i, bits); for (int j = 0; j < n; j++) { if (bits[j] > 0) { answer[j] += (bits[j] << i); } } } if (isSolutionCorrect(conditions, answer)) { out.println("YES"); for (int a : answer) { out.print(a + " "); } } else { out.println("NO"); } } //TODO use segment tree to verify solution private boolean isSolutionCorrect(List<Condition> conditions, int[] answer) { SimpleSegmentTree segmentTree = new SimpleSegmentTree(answer); for (Condition cond : conditions) { if (segmentTree.logicalAnd(cond.l, cond.r) != cond.q) { return false; } } return true; } private void constructBits(List<Condition> conditions, int pos, int[] bits) { int[] arr = new int[bits.length + 1]; for (Condition cond : conditions) { int cur = (cond.q >> pos) & 1; if (cur == 1) { arr[cond.l]++; arr[cond.r + 1]--; } } int s = 0; for (int i = 0; i < bits.length; i++) { s += arr[i]; if (s > 0) { bits[i] = 1; } } } private static class Condition { int l; int r; int q; private Condition(int l, int r, int q) { this.l = l; this.r = r; this.q = q; } } private static class SimpleSegmentTree { private int n; private int[] tree; private int[] initialValues; private SimpleSegmentTree(int[] initialValues) { this.initialValues = initialValues; this.n = initialValues.length; tree = new int[4 * n]; init(0, n - 1, 1); } private void init(int left, int right, int v) { if (left == right) { tree[v] = initialValues[left]; } else { int mid = (left + right) / 2; init(left, mid, 2 * v); init(mid + 1, right, 2 * v + 1); tree[v] = tree[2 * v] & tree[2 * v + 1]; } } private int logicalAnd(int left, int right) { return logicalAnd(1, 0, n - 1, left, right); } private int logicalAnd(int v, int vLeft, int vRight, int left, int right) { if (left > right) { return (2 << BITS) - 1; } else { if (vLeft == left && vRight == right) { return tree[v]; } int vMid = (vLeft + vRight) / 2; int leftAns = logicalAnd(2 * v, vLeft, vMid, left, Math.min(right, vMid)); int rightAns = logicalAnd(2 * v + 1, vMid + 1, vRight, Math.max(left, vMid + 1), right); return leftAns & rightAns; } } } } class InputReader { private BufferedReader reader; private String[] currentArray; private int curPointer; public InputReader(InputStream inputStream) { reader = new BufferedReader(new InputStreamReader(inputStream)); } public int nextInt() { if ((currentArray == null) || (curPointer >= currentArray.length)) { try { currentArray = reader.readLine().split(" "); } catch (IOException e) { throw new RuntimeException(e); } curPointer = 0; } return Integer.parseInt(currentArray[curPointer++]); } }
Java
["3 1\n1 3 3", "3 2\n1 3 3\n1 3 2"]
1 second
["YES\n3 3 3", "NO"]
null
Java 8
standard input
[ "data structures", "constructive algorithms", "trees" ]
0b204773f8d06362b7569bd82224b218
The first line contains two integers n, m (1 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≤ li ≤ ri ≤ n, 0 ≤ qi &lt; 230) describing the i-th limit.
1,800
If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≤ a[i] &lt; 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line.
standard output
PASSED
d85fbba5a71855ddabf5504c29b2dde6
train_001.jsonl
1288440000
On a number axis directed from the left rightwards, n marbles with coordinates x1, x2, ..., xn are situated. Let's assume that the sizes of the marbles are infinitely small, that is in this task each of them is assumed to be a material point. You can stick pins in some of them and the cost of sticking in the marble number i is equal to ci, number ci may be negative. After you choose and stick the pins you need, the marbles will start to roll left according to the rule: if a marble has a pin stuck in it, then the marble doesn't move, otherwise the marble rolls all the way up to the next marble which has a pin stuck in it and stops moving there. If there is no pinned marble on the left to the given unpinned one, it is concluded that the marble rolls to the left to infinity and you will pay an infinitely large fine for it. If no marble rolled infinitely to the left, then the fine will consist of two summands: the sum of the costs of stuck pins; the sum of the lengths of the paths of each of the marbles, that is the sum of absolute values of differences between their initial and final positions. Your task is to choose and pin some marbles in the way that will make the fine for you to pay as little as possible.
256 megabytes
import java.io.BufferedReader; import java.util.Comparator; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Collection; import java.util.List; import java.io.InputStreamReader; import java.io.IOException; import java.util.Arrays; import java.util.ArrayList; import java.util.StringTokenizer; import java.math.BigInteger; import java.util.Collections; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author AlexFetisov */ 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); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } } class TaskE { public static final long INF = Long.MAX_VALUE / 2; public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); final int[] x = new int[n]; final int[] cost = new int[n]; Integer[] idx = new Integer[n]; for (int i = 0; i < n; ++i) { x[i] = in.nextInt(); cost[i] = in.nextInt(); idx[i] = i; } Arrays.sort(idx, new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { if (x[o1] != x[o2]) { return x[o1] - x[o2]; } return cost[o1] - cost[o2]; } }); long[][] dp = new long[2][n]; ArrayUtils.fill(dp, INF); dp[0][0] = cost[idx[0]]; for (int i = 0; i < n-1; ++i) { Arrays.fill(dp[1], INF); for (int j = 0; j <= i; ++j) { if (dp[0][j] < INF) { dp[1][i + 1] = Math.min(dp[1][i + 1], dp[0][j] + cost[idx[i + 1]]); dp[1][j] = Math.min(dp[1][j], dp[0][j] + x[idx[i + 1]] - x[idx[j]]); } } long[] tmp = dp[0]; dp[0] = dp[1]; dp[1] = tmp; } long res = INF; for (long xx : dp[0]) { res = Math.min(res, xx); } out.println(res); } } class InputReader { private BufferedReader reader; private StringTokenizer stt; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); } public String nextLine() { try { return reader.readLine().trim(); } catch (IOException e) { return null; } } public String nextString() { while (stt == null || !stt.hasMoreTokens()) { stt = new StringTokenizer(nextLine()); } return stt.nextToken(); } public int nextInt() { return Integer.parseInt(nextString()); } } class ArrayUtils { public static void fill(long[][] a, long value) { for (int i = 0; i < a.length; ++i) { Arrays.fill(a[i], value); } } }
Java
["3\n2 3\n3 4\n1 2", "4\n1 7\n3 1\n5 10\n6 1"]
2 seconds
["5", "11"]
null
Java 8
standard input
[ "dp", "sortings" ]
334d2bcb32d88a7037bcf262f49938cf
The first input line contains an integer n (1 ≤ n ≤ 3000) which is the number of marbles. The next n lines contain the descriptions of the marbles in pairs of integers xi, ci ( - 109 ≤ xi, ci ≤ 109). The numbers are space-separated. Each description is given on a separate line. No two marbles have identical initial positions.
1,800
Output the single number — the least fine you will have to pay.
standard output
PASSED
fb9d19adfe37d9c6b7720c5fd6ab2e96
train_001.jsonl
1288440000
On a number axis directed from the left rightwards, n marbles with coordinates x1, x2, ..., xn are situated. Let's assume that the sizes of the marbles are infinitely small, that is in this task each of them is assumed to be a material point. You can stick pins in some of them and the cost of sticking in the marble number i is equal to ci, number ci may be negative. After you choose and stick the pins you need, the marbles will start to roll left according to the rule: if a marble has a pin stuck in it, then the marble doesn't move, otherwise the marble rolls all the way up to the next marble which has a pin stuck in it and stops moving there. If there is no pinned marble on the left to the given unpinned one, it is concluded that the marble rolls to the left to infinity and you will pay an infinitely large fine for it. If no marble rolled infinitely to the left, then the fine will consist of two summands: the sum of the costs of stuck pins; the sum of the lengths of the paths of each of the marbles, that is the sum of absolute values of differences between their initial and final positions. Your task is to choose and pin some marbles in the way that will make the fine for you to pay as little as possible.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Solution { public static void main (String[] args) throws java.lang.Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int n = Integer.parseInt(br.readLine()); int[][] a = new int[n][2]; for(int i=0; i<n; i++){ StringTokenizer st = new StringTokenizer(br.readLine()); a[i][0] = Integer.parseInt(st.nextToken()); a[i][1] = Integer.parseInt(st.nextToken()); } Arrays.sort(a,(int[] x,int[] y)->(x[0]-y[0])); long[] dp = new long[n]; dp[0] = a[0][1]; long min = dp[0]; for(int i=1; i<n; i++){ dp[i] = min+a[i][1]; min = dp[i]; for(int j=i-1; j>=0; j--){ dp[j]+=a[i][0]-a[j][0]; min = Math.min(min, dp[j]); } } out.println(min); out.close(); } }
Java
["3\n2 3\n3 4\n1 2", "4\n1 7\n3 1\n5 10\n6 1"]
2 seconds
["5", "11"]
null
Java 8
standard input
[ "dp", "sortings" ]
334d2bcb32d88a7037bcf262f49938cf
The first input line contains an integer n (1 ≤ n ≤ 3000) which is the number of marbles. The next n lines contain the descriptions of the marbles in pairs of integers xi, ci ( - 109 ≤ xi, ci ≤ 109). The numbers are space-separated. Each description is given on a separate line. No two marbles have identical initial positions.
1,800
Output the single number — the least fine you will have to pay.
standard output
PASSED
6f328b3042cb690a9cfa2fff6e048ed2
train_001.jsonl
1288440000
On a number axis directed from the left rightwards, n marbles with coordinates x1, x2, ..., xn are situated. Let's assume that the sizes of the marbles are infinitely small, that is in this task each of them is assumed to be a material point. You can stick pins in some of them and the cost of sticking in the marble number i is equal to ci, number ci may be negative. After you choose and stick the pins you need, the marbles will start to roll left according to the rule: if a marble has a pin stuck in it, then the marble doesn't move, otherwise the marble rolls all the way up to the next marble which has a pin stuck in it and stops moving there. If there is no pinned marble on the left to the given unpinned one, it is concluded that the marble rolls to the left to infinity and you will pay an infinitely large fine for it. If no marble rolled infinitely to the left, then the fine will consist of two summands: the sum of the costs of stuck pins; the sum of the lengths of the paths of each of the marbles, that is the sum of absolute values of differences between their initial and final positions. Your task is to choose and pin some marbles in the way that will make the fine for you to pay as little as possible.
256 megabytes
/** * DA-IICT * Author : PARTH PATEL */ import java.io.*; import java.math.*; import java.util.*; import static java.util.Arrays.fill; import static java.lang.Math.*; import static java.util.Arrays.sort; import static java.util.Collections.sort; public class E38 { public static long mod = 1000000007; public static long INF = (1L << 60); static FastScanner2 in = new FastScanner2(); static OutputWriter out = new OutputWriter(System.out); static class Pair implements Comparable<Pair> { int x,c; Pair(int x,int c) { this.x=x; this.c=c; } @Override public int compareTo(Pair o) { // TODO Auto-generated method stub return this.x-o.x; } } public static void main(String[] args) { int n=in.nextInt(); Pair[] arr=new Pair[n]; int[] x=new int[n+1]; int[] c=new int[n+1]; for(int i=0;i<n;i++) { int xx=in.nextInt(); int cc=in.nextInt(); arr[i]=new Pair(xx, cc); } sort(arr); for(int i=0;i<n;i++) { x[i+1]=arr[i].x; c[i+1]=arr[i].c; } long[][] dp=new long[n+5][n+5]; //dp[i][j] is the minimum fine when we are at index i and last stucked pin is at marble j for(int i=0;i<n+5;i++) { fill(dp[i], INF); } dp[1][1]=c[1]; for(int i=2;i<=n;i++) { //two choices //stuck pin at this marble //don't stuck at this marble for(int j=1;j<i;j++) { //stuck at this dp[i][i]=min(dp[i][i], dp[i-1][j]+c[i]); //do not stuck dp[i][j]=min(dp[i][j], dp[i-1][j]+abs(x[i]-x[j])); } } long answer=INF; for(int j=1;j<=n;j++) { answer=min(answer, dp[n][j]); } out.println(answer); out.close(); } public static long pow(long x, long n, long mod) { long res = 1; for (long p = x; n > 0; n >>= 1, p = (p * p) % mod) { if ((n & 1) != 0) { res = (res * p % mod); } } return res; } public static long gcd(long n1, long n2) { long r; while (n2 != 0) { r = n1 % n2; n1 = n2; n2 = r; } return n1; } public static long lcm(long n1, long n2) { long answer = (n1 * n2) / (gcd(n1, n2)); return answer; } static class FastScanner2 { private byte[] buf = new byte[1024]; private int curChar; private int snumChars; public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = System.in.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 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; } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream inputstream) { reader = new BufferedReader(new InputStreamReader(inputstream)); tokenizer = null; } public String nextLine() { String fullLine = null; while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { fullLine = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return fullLine; } return fullLine; } 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 long nextLong() { return Long.parseLong(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 int nextInt() { return Integer.parseInt(next()); } } 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(); } public void flush() { writer.flush(); } } }
Java
["3\n2 3\n3 4\n1 2", "4\n1 7\n3 1\n5 10\n6 1"]
2 seconds
["5", "11"]
null
Java 8
standard input
[ "dp", "sortings" ]
334d2bcb32d88a7037bcf262f49938cf
The first input line contains an integer n (1 ≤ n ≤ 3000) which is the number of marbles. The next n lines contain the descriptions of the marbles in pairs of integers xi, ci ( - 109 ≤ xi, ci ≤ 109). The numbers are space-separated. Each description is given on a separate line. No two marbles have identical initial positions.
1,800
Output the single number — the least fine you will have to pay.
standard output
PASSED
5665953f8b31c2158e82fb566f0cca25
train_001.jsonl
1288440000
On a number axis directed from the left rightwards, n marbles with coordinates x1, x2, ..., xn are situated. Let's assume that the sizes of the marbles are infinitely small, that is in this task each of them is assumed to be a material point. You can stick pins in some of them and the cost of sticking in the marble number i is equal to ci, number ci may be negative. After you choose and stick the pins you need, the marbles will start to roll left according to the rule: if a marble has a pin stuck in it, then the marble doesn't move, otherwise the marble rolls all the way up to the next marble which has a pin stuck in it and stops moving there. If there is no pinned marble on the left to the given unpinned one, it is concluded that the marble rolls to the left to infinity and you will pay an infinitely large fine for it. If no marble rolled infinitely to the left, then the fine will consist of two summands: the sum of the costs of stuck pins; the sum of the lengths of the paths of each of the marbles, that is the sum of absolute values of differences between their initial and final positions. Your task is to choose and pin some marbles in the way that will make the fine for you to pay as little as possible.
256 megabytes
import java.io.*; import java.util.*; import java.util.stream.IntStream; import java.util.stream.Stream; public class Main implements Runnable { static final int MOD = (int) 1e9 + 7; static final int MI = (int) 1e9; static final long ML = (long) 1e18; static final Reader in = new Reader(); static final PrintWriter out = new PrintWriter(System.out); StringBuilder answer = new StringBuilder(); public static void main(String[] args) { new Thread(null, new Main(), "persefone", 1 << 32).start(); } @Override public void run() { solve(); printf(); flush(); } void solve() { int n = in.nextInt(); Marble[] marbles = new Marble[n + 1]; for (int i = 1; i <= n; i++) { marbles[i] = new Marble(in.nextInt(), in.nextInt()); } Arrays.sort(marbles, 1, n + 1); long[] dp = new long[n + 1]; for (int i = 1; i <= n; i++) { long distance = 0; dp[i] = Long.MAX_VALUE; for (int j = i; j > 0; j--) { dp[i] = Math.min(dp[i], dp[j - 1] + marbles[j].cost + distance - 1l * (i - j) * marbles[j].pos); distance += marbles[j].pos; } } printf(dp[n]); } static class Marble implements Comparable<Marble> { private int pos, cost; public Marble(int pos, int cost) { this.pos = pos; this.cost = cost; } @Override public int compareTo(Marble o) { return Integer.compare(pos, o.pos); } } void printf() { out.print(answer); } void close() { out.close(); } void flush() { out.flush(); } void printf(Stream<?> str) { str.forEach(o -> add(o, " ")); add("\n"); } void printf(Object... obj) { printf(false, obj); } void printfWithDescription(Object... obj) { printf(true, obj); } private void printf(boolean b, Object... obj) { if (obj.length > 1) { for (int i = 0; i < obj.length; i++) { if (b) add(obj[i].getClass().getSimpleName(), " - "); if (obj[i] instanceof Collection<?>) { printf((Collection<?>) obj[i]); } else if (obj[i] instanceof int[][]) { printf((int[][]) obj[i]); } else if (obj[i] instanceof long[][]) { printf((long[][]) obj[i]); } else if (obj[i] instanceof double[][]) { printf((double[][]) obj[i]); } else printf(obj[i]); } return; } if (b) add(obj[0].getClass().getSimpleName(), " - "); printf(obj[0]); } void printf(Object o) { if (o instanceof int[]) printf(Arrays.stream((int[]) o).boxed()); else if (o instanceof char[]) printf(new String((char[]) o)); else if (o instanceof long[]) printf(Arrays.stream((long[]) o).boxed()); else if (o instanceof double[]) printf(Arrays.stream((double[]) o).boxed()); else if (o instanceof boolean[]) { for (boolean b : (boolean[]) o) add(b, " "); add("\n"); } else add(o, "\n"); } void printf(int[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(long[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(double[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(boolean[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(Collection<?> col) { printf(col.stream()); } <T, K> void add(T t, K k) { if (t instanceof Collection<?>) { ((Collection<?>) t).forEach(i -> add(i, " ")); } else if (t instanceof Object[]) { Arrays.stream((Object[]) t).forEach(i -> add(i, " ")); } else add(t); add(k); } <T> void add(T t) { answer.append(t); } static class Reader { private BufferedReader br; private StringTokenizer st; Reader() { br = new BufferedReader(new InputStreamReader(System.in)); } Reader(String fileName) throws FileNotFoundException { br = new BufferedReader(new FileReader(fileName)); } boolean isReady() throws IOException { return br.ready(); } String next() { try { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } long nextLong() { return Long.parseLong(next()); } String nextLine() { String s = ""; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return s; } } }
Java
["3\n2 3\n3 4\n1 2", "4\n1 7\n3 1\n5 10\n6 1"]
2 seconds
["5", "11"]
null
Java 8
standard input
[ "dp", "sortings" ]
334d2bcb32d88a7037bcf262f49938cf
The first input line contains an integer n (1 ≤ n ≤ 3000) which is the number of marbles. The next n lines contain the descriptions of the marbles in pairs of integers xi, ci ( - 109 ≤ xi, ci ≤ 109). The numbers are space-separated. Each description is given on a separate line. No two marbles have identical initial positions.
1,800
Output the single number — the least fine you will have to pay.
standard output
PASSED
f0df4ff447e0ab4cbf4ad80699a924a8
train_001.jsonl
1288440000
On a number axis directed from the left rightwards, n marbles with coordinates x1, x2, ..., xn are situated. Let's assume that the sizes of the marbles are infinitely small, that is in this task each of them is assumed to be a material point. You can stick pins in some of them and the cost of sticking in the marble number i is equal to ci, number ci may be negative. After you choose and stick the pins you need, the marbles will start to roll left according to the rule: if a marble has a pin stuck in it, then the marble doesn't move, otherwise the marble rolls all the way up to the next marble which has a pin stuck in it and stops moving there. If there is no pinned marble on the left to the given unpinned one, it is concluded that the marble rolls to the left to infinity and you will pay an infinitely large fine for it. If no marble rolled infinitely to the left, then the fine will consist of two summands: the sum of the costs of stuck pins; the sum of the lengths of the paths of each of the marbles, that is the sum of absolute values of differences between their initial and final positions. Your task is to choose and pin some marbles in the way that will make the fine for you to pay as little as possible.
256 megabytes
import java.util.*; public class Test { static long dp[][]; public static void main(String args[]) { Scanner in = new Scanner(System.in); int n = in.nextInt(); Marble marbles[] = new Marble[n]; dp = new long[n][n]; for(int i=0;i<n;i++){ marbles[i] = new Marble(in.nextInt(),in.nextInt()); Arrays.fill(dp[i],Long.MAX_VALUE/1000); } if(n==1) { System.out.println(marbles[0].c); return; } Arrays.sort(marbles); System.out.println(solve(0,0,n,marbles)); } private static long solve(int pos,int prev,int n,Marble marbles[]){ if(pos==n-1){ return Math.min(marbles[n-1].x-marbles[prev].x,marbles[n-1].c); } if(dp[pos][prev]!=Long.MAX_VALUE/1000) return dp[pos][prev]; if(pos==0) return marbles[0].c+solve(1,0,n,marbles); dp[pos][prev] = Math.min(marbles[pos].c+solve(pos+1,pos,n,marbles), marbles[pos].x-marbles[prev].x+solve(pos+1,prev,n,marbles)); return dp[pos][prev]; } static class Marble implements Comparable<Marble>{ int x; int c; public Marble(int x,int c){ this.x = x; this.c = c; } public int compareTo(Marble m){ return this.x - m.x; } } }
Java
["3\n2 3\n3 4\n1 2", "4\n1 7\n3 1\n5 10\n6 1"]
2 seconds
["5", "11"]
null
Java 8
standard input
[ "dp", "sortings" ]
334d2bcb32d88a7037bcf262f49938cf
The first input line contains an integer n (1 ≤ n ≤ 3000) which is the number of marbles. The next n lines contain the descriptions of the marbles in pairs of integers xi, ci ( - 109 ≤ xi, ci ≤ 109). The numbers are space-separated. Each description is given on a separate line. No two marbles have identical initial positions.
1,800
Output the single number — the least fine you will have to pay.
standard output
PASSED
7289531f728b9cfa54ef291e7a6cb293
train_001.jsonl
1288440000
On a number axis directed from the left rightwards, n marbles with coordinates x1, x2, ..., xn are situated. Let's assume that the sizes of the marbles are infinitely small, that is in this task each of them is assumed to be a material point. You can stick pins in some of them and the cost of sticking in the marble number i is equal to ci, number ci may be negative. After you choose and stick the pins you need, the marbles will start to roll left according to the rule: if a marble has a pin stuck in it, then the marble doesn't move, otherwise the marble rolls all the way up to the next marble which has a pin stuck in it and stops moving there. If there is no pinned marble on the left to the given unpinned one, it is concluded that the marble rolls to the left to infinity and you will pay an infinitely large fine for it. If no marble rolled infinitely to the left, then the fine will consist of two summands: the sum of the costs of stuck pins; the sum of the lengths of the paths of each of the marbles, that is the sum of absolute values of differences between their initial and final positions. Your task is to choose and pin some marbles in the way that will make the fine for you to pay as little as possible.
256 megabytes
import java.io.*; import java.util.*; public class C { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); int[] x = new int[n], c = new int[n]; Integer[] idx = new Integer[n]; for(int i = 0; i < n; ++i) { x[idx[i] = i] = sc.nextInt(); c[i] = sc.nextInt(); } Arrays.sort(idx, Comparator.comparingInt(a -> x[a])); long[][] dp = new long[n + 1][n]; for(int i = n - 1; i > 0; --i) for(int j = 0; j < i; ++j) { dp[i][j] = Math.min(dp[i+1][i] + c[idx[i]], dp[i+1][j] + x[idx[i]] - x[idx[j]]); } out.println(dp[1][0] + c[idx[0]]); out.close(); } 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 boolean ready() throws IOException {return br.ready();} } }
Java
["3\n2 3\n3 4\n1 2", "4\n1 7\n3 1\n5 10\n6 1"]
2 seconds
["5", "11"]
null
Java 8
standard input
[ "dp", "sortings" ]
334d2bcb32d88a7037bcf262f49938cf
The first input line contains an integer n (1 ≤ n ≤ 3000) which is the number of marbles. The next n lines contain the descriptions of the marbles in pairs of integers xi, ci ( - 109 ≤ xi, ci ≤ 109). The numbers are space-separated. Each description is given on a separate line. No two marbles have identical initial positions.
1,800
Output the single number — the least fine you will have to pay.
standard output
PASSED
f2d571336a28afe622f8835245e6be11
train_001.jsonl
1546613100
One day, Yuhao came across a problem about checking if some bracket sequences are correct bracket sequences.A bracket sequence is any non-empty sequence of opening and closing parentheses. A bracket sequence is called a correct bracket sequence if it's possible to obtain a correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, the sequences "(())()", "()" and "(()(()))" are correct, while the bracket sequences ")(", "(()" and "(()))(" are not correct.Yuhao found this problem too simple for him so he decided to make the problem harder. You are given many (not necessarily correct) bracket sequences. The task is to connect some of them into ordered pairs so that each bracket sequence occurs in at most one pair and the concatenation of the bracket sequences in each pair is a correct bracket sequence. The goal is to create as many pairs as possible.This problem unfortunately turned out to be too difficult for Yuhao. Can you help him and solve it?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); CYuhaoAndAParenthesis solver = new CYuhaoAndAParenthesis(); solver.solve(1, in, out); out.close(); } static class CYuhaoAndAParenthesis { public void solve(int testNumber, InputReader in, PrintWriter out) { int num = in.nextInt(), m = (int) 5e5 + 1; int p[] = new int[m]; int n[] = new int[m]; for (int i = 0; i < num; i++) { char c[] = in.next().toCharArray(); int ct = 0, min = 0; for (int j = 0; j < c.length; j++) { if (c[j] == '(') ct++; else ct--; min = Math.min(min, ct); } //System.out.println(min+" "+ct); if (ct > 0) { if (min >= 0) { p[ct]++; } } else if (ct < 0) { if (min >= ct) { n[-ct]++; } } else { if (min >= 0) { p[ct]++; } } } int ans = 0; for (int i = 1; i < p.length; i++) { ans += Math.min(p[i], n[i]); } out.println(ans + (p[0] / 2)); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String 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); } } }
Java
["7\n)())\n)\n((\n((\n(\n)\n)", "4\n(\n((\n(((\n(())", "2\n(())\n()"]
2 seconds
["2", "0", "1"]
NoteIn the first example, it's optimal to construct two pairs: "((     )())" and "(     )".
Java 8
standard input
[ "implementation", "greedy" ]
2cfb08b2269dbf5417c1758def4c035f
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of bracket sequences. Each of the following $$$n$$$ lines contains one bracket sequence — a non-empty string which consists only of characters "(" and ")". The sum of lengths of all bracket sequences in the input is at most $$$5 \cdot 10^5$$$. Note that a bracket sequence may appear in the input multiple times. In this case, you can use each copy of the sequence separately. Also note that the order in which strings appear in the input doesn't matter.
1,400
Print a single integer — the maximum number of pairs which can be made, adhering to the conditions in the statement.
standard output
PASSED
dd1cbefd26055456731a57c98d3f269e
train_001.jsonl
1546613100
One day, Yuhao came across a problem about checking if some bracket sequences are correct bracket sequences.A bracket sequence is any non-empty sequence of opening and closing parentheses. A bracket sequence is called a correct bracket sequence if it's possible to obtain a correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, the sequences "(())()", "()" and "(()(()))" are correct, while the bracket sequences ")(", "(()" and "(()))(" are not correct.Yuhao found this problem too simple for him so he decided to make the problem harder. You are given many (not necessarily correct) bracket sequences. The task is to connect some of them into ordered pairs so that each bracket sequence occurs in at most one pair and the concatenation of the bracket sequences in each pair is a correct bracket sequence. The goal is to create as many pairs as possible.This problem unfortunately turned out to be too difficult for Yuhao. Can you help him and solve it?
256 megabytes
import java.io.*; import java.util.*; public class Typo { public static void main(String[] args)throws IOException { BufferedReader ob=new BufferedReader(new InputStreamReader(System.in)); int n=Integer.parseInt(ob.readLine()); Map<Integer,Integer> pos=new HashMap<>(); Map<Integer,Integer> neg=new HashMap<>(); for(int i=0;i<n;i++) { int sum=0; int ne=0; String s=ob.readLine(); for(char c: s.toCharArray()) { if(c=='(') { sum += 1; } else { sum -= 1; } ne=Math.min(ne, sum); } if(ne<sum && ne<0) { continue; } if(sum>=0) { if(pos.containsKey(sum)) pos.put(sum, pos.get(sum)+1); else pos.put(sum, 1); } else { if(neg.containsKey(-sum)) neg.put(-sum, neg.get(-sum)+1); else neg.put(-sum, 1); } // System.out.println("sum = "+sum); } // System.out.println(pos); // System.out.println(neg); int ans = 0; for(Map.Entry<Integer,Integer> e:pos.entrySet()) { Integer key = e.getKey(); if(neg.containsKey(key)) { ans += Math.min(e.getValue(), neg.get(key)); } // System.out.println("ans = "+ans); } if(pos.containsKey(0)) { ans += pos.get(0)/2; } System.out.println(ans); } }
Java
["7\n)())\n)\n((\n((\n(\n)\n)", "4\n(\n((\n(((\n(())", "2\n(())\n()"]
2 seconds
["2", "0", "1"]
NoteIn the first example, it's optimal to construct two pairs: "((     )())" and "(     )".
Java 8
standard input
[ "implementation", "greedy" ]
2cfb08b2269dbf5417c1758def4c035f
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of bracket sequences. Each of the following $$$n$$$ lines contains one bracket sequence — a non-empty string which consists only of characters "(" and ")". The sum of lengths of all bracket sequences in the input is at most $$$5 \cdot 10^5$$$. Note that a bracket sequence may appear in the input multiple times. In this case, you can use each copy of the sequence separately. Also note that the order in which strings appear in the input doesn't matter.
1,400
Print a single integer — the maximum number of pairs which can be made, adhering to the conditions in the statement.
standard output
PASSED
6feafb476e90c3e3cd9796229b5e5faf
train_001.jsonl
1546613100
One day, Yuhao came across a problem about checking if some bracket sequences are correct bracket sequences.A bracket sequence is any non-empty sequence of opening and closing parentheses. A bracket sequence is called a correct bracket sequence if it's possible to obtain a correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, the sequences "(())()", "()" and "(()(()))" are correct, while the bracket sequences ")(", "(()" and "(()))(" are not correct.Yuhao found this problem too simple for him so he decided to make the problem harder. You are given many (not necessarily correct) bracket sequences. The task is to connect some of them into ordered pairs so that each bracket sequence occurs in at most one pair and the concatenation of the bracket sequences in each pair is a correct bracket sequence. The goal is to create as many pairs as possible.This problem unfortunately turned out to be too difficult for Yuhao. Can you help him and solve it?
256 megabytes
import java.io.*; import java.util.HashMap; import java.util.Scanner; public class ProblemC { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); int tests = Integer.parseInt(br.readLine()); HashMap<Integer,Integer> balance = new HashMap<>(110000); for (int i = 0; i < tests; i++) { String line = br.readLine(); int opened = 0; boolean openToLeft = false; for (int j = 0; j < line.length(); j++) { if (line.charAt(j)=='('){ opened++; } else{ opened--; if (opened<0)openToLeft=true; } } boolean openToRight = false; int openedRight = 0; for (int j = line.length()-1; j >= 0 ; j--) { if (line.charAt(j)=='('){ openedRight++; if (openedRight>0)openToRight=true; } else{ openedRight--; } } if (openToLeft&&openToRight) { }else if ((!openToLeft&&!openToRight&&opened==0)||(openToLeft&&opened<0)||(openToRight&&opened>0)){ balance.putIfAbsent(opened, 0); balance.computeIfPresent(opened, (integer, integer2) -> integer2 + 1); } } int pairs = 0; for (Integer integer : balance.keySet()) { Integer v1 = balance.get(integer); Integer v2 = balance.get(-integer); if (v2 == null) v2 = 0; int sol = Math.min(v1,v2); if (integer == 0)sol/=2; pairs = pairs + sol; balance.computeIfPresent(integer,(integer1, integer2) -> 0); balance.computeIfPresent(-integer,(integer1, integer2) -> 0); } bw.write(pairs+"\n"); bw.flush(); bw.close(); } }
Java
["7\n)())\n)\n((\n((\n(\n)\n)", "4\n(\n((\n(((\n(())", "2\n(())\n()"]
2 seconds
["2", "0", "1"]
NoteIn the first example, it's optimal to construct two pairs: "((     )())" and "(     )".
Java 8
standard input
[ "implementation", "greedy" ]
2cfb08b2269dbf5417c1758def4c035f
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of bracket sequences. Each of the following $$$n$$$ lines contains one bracket sequence — a non-empty string which consists only of characters "(" and ")". The sum of lengths of all bracket sequences in the input is at most $$$5 \cdot 10^5$$$. Note that a bracket sequence may appear in the input multiple times. In this case, you can use each copy of the sequence separately. Also note that the order in which strings appear in the input doesn't matter.
1,400
Print a single integer — the maximum number of pairs which can be made, adhering to the conditions in the statement.
standard output
PASSED
245a7eb6e4e4cd546e2e4d264787417e
train_001.jsonl
1546613100
One day, Yuhao came across a problem about checking if some bracket sequences are correct bracket sequences.A bracket sequence is any non-empty sequence of opening and closing parentheses. A bracket sequence is called a correct bracket sequence if it's possible to obtain a correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, the sequences "(())()", "()" and "(()(()))" are correct, while the bracket sequences ")(", "(()" and "(()))(" are not correct.Yuhao found this problem too simple for him so he decided to make the problem harder. You are given many (not necessarily correct) bracket sequences. The task is to connect some of them into ordered pairs so that each bracket sequence occurs in at most one pair and the concatenation of the bracket sequences in each pair is a correct bracket sequence. The goal is to create as many pairs as possible.This problem unfortunately turned out to be too difficult for Yuhao. Can you help him and solve it?
256 megabytes
import java.io.*; import java.util.*; public class Bracket{ static final int MAXN = 500005; static public void main(String[] args) { InputReader in = new InputReader (System.in); PrintWriter out = new PrintWriter (System.out); int n = in.nextInt(), ans = 0; int[] left = new int [MAXN]; int[] right = new int [MAXN]; for (int i = 0; i < n; ++i) { StringBuffer s = new StringBuffer (in.next()); int v = check(s, '('); if (v >= 0) left[v]++; s.reverse(); v = check(s, ')'); if (v >= 0) right[v]++; } ans = left[0] / 2; for (int i = 1; i < MAXN; ++i) ans += Math.min(left[i], right[i]); out.println(ans); out.close(); } static public int check(StringBuffer s, char l) { int n = s.length(); int cnt = 0; for (int i = 0; i < n; ++i) { if (s.charAt(i) == l) ++cnt; else --cnt; if (cnt < 0) return -1; } return cnt; } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["7\n)())\n)\n((\n((\n(\n)\n)", "4\n(\n((\n(((\n(())", "2\n(())\n()"]
2 seconds
["2", "0", "1"]
NoteIn the first example, it's optimal to construct two pairs: "((     )())" and "(     )".
Java 8
standard input
[ "implementation", "greedy" ]
2cfb08b2269dbf5417c1758def4c035f
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of bracket sequences. Each of the following $$$n$$$ lines contains one bracket sequence — a non-empty string which consists only of characters "(" and ")". The sum of lengths of all bracket sequences in the input is at most $$$5 \cdot 10^5$$$. Note that a bracket sequence may appear in the input multiple times. In this case, you can use each copy of the sequence separately. Also note that the order in which strings appear in the input doesn't matter.
1,400
Print a single integer — the maximum number of pairs which can be made, adhering to the conditions in the statement.
standard output
PASSED
2005a6c1c687252905ae3b2b6f480d82
train_001.jsonl
1546613100
One day, Yuhao came across a problem about checking if some bracket sequences are correct bracket sequences.A bracket sequence is any non-empty sequence of opening and closing parentheses. A bracket sequence is called a correct bracket sequence if it's possible to obtain a correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, the sequences "(())()", "()" and "(()(()))" are correct, while the bracket sequences ")(", "(()" and "(()))(" are not correct.Yuhao found this problem too simple for him so he decided to make the problem harder. You are given many (not necessarily correct) bracket sequences. The task is to connect some of them into ordered pairs so that each bracket sequence occurs in at most one pair and the concatenation of the bracket sequences in each pair is a correct bracket sequence. The goal is to create as many pairs as possible.This problem unfortunately turned out to be too difficult for Yuhao. Can you help him and solve it?
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Scanner; public class FirstStep { static int[] in1; static int[]in2; static int n; static boolean solve(int sum,int id){ if(id==n){ if (sum==0||sum%360==0){ return true; } else return false; } return solve(sum+in1[id],id+1)||solve(sum+in2[id],id+1); } public static void main(String args[]) { Scanner input = new Scanner(System.in); n = Integer.parseInt(input.nextLine()); String[]in=new String[n]; for(int i =0;i<n;i++){ in[i]= input.nextLine(); } ArrayList<Integer>l= new ArrayList<Integer>(n); HashMap<Integer,Integer>hm=new HashMap<Integer, Integer>(); //System.out.println(Arrays.toString(in)); for(int i=0;i<n;i++){ int k=0; for(int j=0;j<in[i].length();j++){ if (in[i].charAt(j)=='(') { k++; } else{ k--; } } int z=0; for(int v =0;v<in[i].length();v++){ if(in[i].charAt(v)=='(')z++; else z--; if(z<0)break; } int w=0; for(int v =in[i].length()-1;v>=0;v--){ if(in[i].charAt(v)==')')w++; else w--; if(w<0)break; } if(w<0&&z<0)continue; l.add(k); hm.put(k, hm.getOrDefault(k, 0)+1); } int ans =0; for(int i =0;i<l.size();i++){ if(hm.get(l.get(i))==0)continue; hm.put(l.get(i),hm.get(l.get(i))-1); int a = -1*l.get(i); if(hm.containsKey(a)&&hm.get(a)>0){ hm.put(a, hm.get(a)-1); ans++; } } System.out.println(ans); } }
Java
["7\n)())\n)\n((\n((\n(\n)\n)", "4\n(\n((\n(((\n(())", "2\n(())\n()"]
2 seconds
["2", "0", "1"]
NoteIn the first example, it's optimal to construct two pairs: "((     )())" and "(     )".
Java 8
standard input
[ "implementation", "greedy" ]
2cfb08b2269dbf5417c1758def4c035f
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of bracket sequences. Each of the following $$$n$$$ lines contains one bracket sequence — a non-empty string which consists only of characters "(" and ")". The sum of lengths of all bracket sequences in the input is at most $$$5 \cdot 10^5$$$. Note that a bracket sequence may appear in the input multiple times. In this case, you can use each copy of the sequence separately. Also note that the order in which strings appear in the input doesn't matter.
1,400
Print a single integer — the maximum number of pairs which can be made, adhering to the conditions in the statement.
standard output
PASSED
e56f63bccfffff56b2c56f96ec5e145d
train_001.jsonl
1546613100
One day, Yuhao came across a problem about checking if some bracket sequences are correct bracket sequences.A bracket sequence is any non-empty sequence of opening and closing parentheses. A bracket sequence is called a correct bracket sequence if it's possible to obtain a correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, the sequences "(())()", "()" and "(()(()))" are correct, while the bracket sequences ")(", "(()" and "(()))(" are not correct.Yuhao found this problem too simple for him so he decided to make the problem harder. You are given many (not necessarily correct) bracket sequences. The task is to connect some of them into ordered pairs so that each bracket sequence occurs in at most one pair and the concatenation of the bracket sequences in each pair is a correct bracket sequence. The goal is to create as many pairs as possible.This problem unfortunately turned out to be too difficult for Yuhao. Can you help him and solve it?
256 megabytes
import java.io.*; import java.util.*; public class C { static StringBuilder st = new StringBuilder(); public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); TreeMap<Integer , Integer> map = new TreeMap<>(); while(n-->0) { char[] c = sc.next().toCharArray() ; int open = 0 , close = 0 ; boolean left = true , right = true ; for(int i = 0 ; i < c.length ; i++) { if(c[i] == '(') open++; else open -- ; if(c[c.length - i - 1] == '(') close --; else close ++ ; left &= open >= 0 ; right &= close >= 0 ; } if(left || right) map.put(open, map.getOrDefault(open, 0) + 1) ; } int ans = map.getOrDefault(0, 0)/2; for(int x : map.keySet()) if(map.containsKey(-x)) ans += x < 0 ? Math.min(map.get(x), map.get(-x)) : 0; out.println(ans); out.flush(); out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner(InputStream in) { br = new BufferedReader(new InputStreamReader(System.in)); } String next() throws Exception { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws Exception { return Integer.parseInt(next()); } long nextLong() throws Exception { return Long.parseLong(next()); } double nextDouble() throws Exception { return Double.parseDouble(next()); } } static void shuffle(int[] a) { int n = a.length; for (int i = 0; i < n; i++) { int r = i + (int) (Math.random() * (n - i)); int tmp = a[i]; a[i] = a[r]; a[r] = tmp; } } }
Java
["7\n)())\n)\n((\n((\n(\n)\n)", "4\n(\n((\n(((\n(())", "2\n(())\n()"]
2 seconds
["2", "0", "1"]
NoteIn the first example, it's optimal to construct two pairs: "((     )())" and "(     )".
Java 8
standard input
[ "implementation", "greedy" ]
2cfb08b2269dbf5417c1758def4c035f
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of bracket sequences. Each of the following $$$n$$$ lines contains one bracket sequence — a non-empty string which consists only of characters "(" and ")". The sum of lengths of all bracket sequences in the input is at most $$$5 \cdot 10^5$$$. Note that a bracket sequence may appear in the input multiple times. In this case, you can use each copy of the sequence separately. Also note that the order in which strings appear in the input doesn't matter.
1,400
Print a single integer — the maximum number of pairs which can be made, adhering to the conditions in the statement.
standard output
PASSED
b535ab7531ecc3bf301b2a298352be0c
train_001.jsonl
1546613100
One day, Yuhao came across a problem about checking if some bracket sequences are correct bracket sequences.A bracket sequence is any non-empty sequence of opening and closing parentheses. A bracket sequence is called a correct bracket sequence if it's possible to obtain a correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, the sequences "(())()", "()" and "(()(()))" are correct, while the bracket sequences ")(", "(()" and "(()))(" are not correct.Yuhao found this problem too simple for him so he decided to make the problem harder. You are given many (not necessarily correct) bracket sequences. The task is to connect some of them into ordered pairs so that each bracket sequence occurs in at most one pair and the concatenation of the bracket sequences in each pair is a correct bracket sequence. The goal is to create as many pairs as possible.This problem unfortunately turned out to be too difficult for Yuhao. Can you help him and solve it?
256 megabytes
import java.io.*; import java.util.*; public class C { static StringBuilder st = new StringBuilder(); public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); TreeMap<Integer , Integer> map = new TreeMap<>(); while(n-->0) { char[] c = sc.next().toCharArray() ; int open = 0 ; boolean remove = true ; for(char ch : c) { if(ch == '(') { open++; } else open -- ; if(open < 0)remove = false; } if(remove) map.put(open, map.getOrDefault(open, 0) + 1) ; boolean r2 = true ; open = 0 ; for(int i = c.length - 1 ; i >= 0 ; i--) { char ch = c[i] ; if(ch == '(') { open++; } else open -- ; if(open >0)r2 = false; } if(r2 && !remove) map.put(open, map.getOrDefault(open, 0) + 1) ; } int ans = 0 ; for(int x : map.keySet()) { if(x > 0)break ; int closed = map.get(x); if(!map.containsKey(-x))continue; int open = map.get(-x) ; if(x == 0) { open/=2 ; closed /= 2 ; } ans += Math.min(open, closed); } out.println(ans); out.flush(); out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner(InputStream in) { br = new BufferedReader(new InputStreamReader(System.in)); } String next() throws Exception { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws Exception { return Integer.parseInt(next()); } long nextLong() throws Exception { return Long.parseLong(next()); } double nextDouble() throws Exception { return Double.parseDouble(next()); } } static void shuffle(int[] a) { int n = a.length; for (int i = 0; i < n; i++) { int r = i + (int) (Math.random() * (n - i)); int tmp = a[i]; a[i] = a[r]; a[r] = tmp; } } }
Java
["7\n)())\n)\n((\n((\n(\n)\n)", "4\n(\n((\n(((\n(())", "2\n(())\n()"]
2 seconds
["2", "0", "1"]
NoteIn the first example, it's optimal to construct two pairs: "((     )())" and "(     )".
Java 8
standard input
[ "implementation", "greedy" ]
2cfb08b2269dbf5417c1758def4c035f
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of bracket sequences. Each of the following $$$n$$$ lines contains one bracket sequence — a non-empty string which consists only of characters "(" and ")". The sum of lengths of all bracket sequences in the input is at most $$$5 \cdot 10^5$$$. Note that a bracket sequence may appear in the input multiple times. In this case, you can use each copy of the sequence separately. Also note that the order in which strings appear in the input doesn't matter.
1,400
Print a single integer — the maximum number of pairs which can be made, adhering to the conditions in the statement.
standard output
PASSED
98bb299ed5dc7fc1b507b4f792473661
train_001.jsonl
1546613100
One day, Yuhao came across a problem about checking if some bracket sequences are correct bracket sequences.A bracket sequence is any non-empty sequence of opening and closing parentheses. A bracket sequence is called a correct bracket sequence if it's possible to obtain a correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, the sequences "(())()", "()" and "(()(()))" are correct, while the bracket sequences ")(", "(()" and "(()))(" are not correct.Yuhao found this problem too simple for him so he decided to make the problem harder. You are given many (not necessarily correct) bracket sequences. The task is to connect some of them into ordered pairs so that each bracket sequence occurs in at most one pair and the concatenation of the bracket sequences in each pair is a correct bracket sequence. The goal is to create as many pairs as possible.This problem unfortunately turned out to be too difficult for Yuhao. Can you help him and solve it?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Stack; import java.util.StringTokenizer; public class c { public static void main(String[] args) { // TODO Auto-generated method stub FastReader s = new FastReader(); int N = s.nextInt(); String[] str = new String[N]; ArrayList<Integer> val = new ArrayList<>(); for(int i=0;i<N;i++) { str[i] = s.next(); int count = 0; if(bothOpen(str[i])) continue; for(int j=0;j<str[i].length();j++) { if(str[i].charAt(j)=='(') count++; else count--; } val.add(count); } int[] val2 = new int[val.size()]; for(int j=0;j<val2.length;j++) val2[j] = val.get(j); Arrays.sort(val2); int ans = 0; int i=0,j = val2.length-1; while(i<j) { int sum = val2[i] + val2[j]; if(sum==0) { ans++; i++; j--; } else if(sum>0) j--; else i++; } System.out.println(ans); } public static boolean bothOpen(String str) { Stack<Character> stack = new Stack<>(); boolean ans = false; for(int i=0;i<str.length();i++) { if(str.charAt(i)=='(') stack.push('('); else { if(stack.isEmpty()) ans = true; else stack.pop(); } } if(ans&&!stack.isEmpty()) return true; return false; } static boolean getAns(int[] arr, int index, int sum) { if(index == arr.length) { if(sum == 0) return true; else return false; } int sum1 = (arr[index] + sum)%360; int sum2 = (-arr[index] + sum+ 360)%360; return getAns(arr, index + 1,sum1) || getAns(arr, index + 1, sum2); } 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
["7\n)())\n)\n((\n((\n(\n)\n)", "4\n(\n((\n(((\n(())", "2\n(())\n()"]
2 seconds
["2", "0", "1"]
NoteIn the first example, it's optimal to construct two pairs: "((     )())" and "(     )".
Java 8
standard input
[ "implementation", "greedy" ]
2cfb08b2269dbf5417c1758def4c035f
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of bracket sequences. Each of the following $$$n$$$ lines contains one bracket sequence — a non-empty string which consists only of characters "(" and ")". The sum of lengths of all bracket sequences in the input is at most $$$5 \cdot 10^5$$$. Note that a bracket sequence may appear in the input multiple times. In this case, you can use each copy of the sequence separately. Also note that the order in which strings appear in the input doesn't matter.
1,400
Print a single integer — the maximum number of pairs which can be made, adhering to the conditions in the statement.
standard output
PASSED
b192e8fc57294a2bc70b617e99ae0888
train_001.jsonl
1546613100
One day, Yuhao came across a problem about checking if some bracket sequences are correct bracket sequences.A bracket sequence is any non-empty sequence of opening and closing parentheses. A bracket sequence is called a correct bracket sequence if it's possible to obtain a correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, the sequences "(())()", "()" and "(()(()))" are correct, while the bracket sequences ")(", "(()" and "(()))(" are not correct.Yuhao found this problem too simple for him so he decided to make the problem harder. You are given many (not necessarily correct) bracket sequences. The task is to connect some of them into ordered pairs so that each bracket sequence occurs in at most one pair and the concatenation of the bracket sequences in each pair is a correct bracket sequence. The goal is to create as many pairs as possible.This problem unfortunately turned out to be too difficult for Yuhao. Can you help him and solve it?
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.*; public class gr1 { static class InputReader { public BufferedReader br; public StringTokenizer token; public InputReader(InputStream stream) { br=new BufferedReader(new InputStreamReader(stream),32768); token=null; } public String next() { while(token==null || !token.hasMoreTokens()) { try { token=new StringTokenizer(br.readLine()); } catch(IOException e) { throw new RuntimeException(e); } } return token.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } static class card{ long a; int cnt; int i; public card(long a,int cnt,int i) { this.a=a; this.cnt=cnt; this.i=i; } } static class ascend implements Comparator<pair> { public int compare(pair o1,pair o2) { if(o1.b!=o2.b) return (int)(o1.b-o2.b); else return (int)(o1.a-o2.a); } } /*static class descend implements Comparator<pair> { public int compare(pair o1,pair o2) { if(o1.a!=o2.a){ return (o1.a-o2.a)*-1; } else { return (o1.b-o2.b); } } }*/ static class extra { static void shuffle(long a[]) { List<Long> l=new ArrayList<>(); for(int i=0;i<a.length;i++) l.add(a[i]); Collections.shuffle(l); for(int i=0;i<a.length;i++) a[i]=l.get(i); } static long gcd(long a,long b) { if(b==0) return a; else return gcd(b,a%b); } static boolean valid(int i,int j,int r,int c) { if(i>=0 && i<r && j>=0 && j<c) return true; else return false; } static boolean v[]=new boolean[100001]; static List<Integer> l=new ArrayList<>(); static int t; static void seive() { for(int i=2;i<100001;i++) { if(!v[i]) { t++; l.add(i); for(int j=2*i;j<100001;j+=i) v[j]=true; } } } static int binary(pair a[],int val,int n) { int mid=0,l=0,r=n-1,ans=0; while(l<=r) { mid=(l+r)>>1; if(a[mid].a==val) { r=mid-1; ans=mid; } else if(a[mid].a>val) r=mid-1; else { l=mid+1; ans=l; } } return (ans); } } static class pair{ long a; int b; public pair(long a,int n) { this.a=a; this.b=n; } } static InputReader sc=new InputReader(System.in); static PrintWriter out=new PrintWriter(System.out); public static void main(String[] args) { solver s=new solver(); int t=1; while(t>0) { s.solve(); t--; } } static class solver { void solve() { int n=sc.nextInt(); int left[]=new int[500005]; int right[]=new int[500005]; int bal=0,max=0; for(int i=0;i<n;i++) { Stack<Character> s=new Stack<>(); char c[]=sc.next().toCharArray(); int l1=c.length,le=0,ri=0; for(int j=0;j<l1;j++) { if(s.isEmpty()) { s.push(c[j]); if(c[j]=='(') ri++; else le++; } else if(s.peek()=='(' && c[j]==')') { char ch=s.pop(); if(ch=='(') ri--; else le--; } else { s.push(c[j]); if(c[j]=='(') ri++; else le++; } } if(le==0 && ri==0) bal++; else { if(ri==0 && le>0) left[le]++; else if(ri>0 && le==0) right[ri]++; max=Math.max(max,Math.max(le,ri)); } } long ans=0; for(int i=1;i<=max;i++) { ans+=Math.min(left[i],right[i]); } ans+=bal/2; System.out.println(ans); } } }
Java
["7\n)())\n)\n((\n((\n(\n)\n)", "4\n(\n((\n(((\n(())", "2\n(())\n()"]
2 seconds
["2", "0", "1"]
NoteIn the first example, it's optimal to construct two pairs: "((     )())" and "(     )".
Java 8
standard input
[ "implementation", "greedy" ]
2cfb08b2269dbf5417c1758def4c035f
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of bracket sequences. Each of the following $$$n$$$ lines contains one bracket sequence — a non-empty string which consists only of characters "(" and ")". The sum of lengths of all bracket sequences in the input is at most $$$5 \cdot 10^5$$$. Note that a bracket sequence may appear in the input multiple times. In this case, you can use each copy of the sequence separately. Also note that the order in which strings appear in the input doesn't matter.
1,400
Print a single integer — the maximum number of pairs which can be made, adhering to the conditions in the statement.
standard output
PASSED
1e8fe0f91ec70e88e3f96ae4e6d4b5c9
train_001.jsonl
1546613100
One day, Yuhao came across a problem about checking if some bracket sequences are correct bracket sequences.A bracket sequence is any non-empty sequence of opening and closing parentheses. A bracket sequence is called a correct bracket sequence if it's possible to obtain a correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, the sequences "(())()", "()" and "(()(()))" are correct, while the bracket sequences ")(", "(()" and "(()))(" are not correct.Yuhao found this problem too simple for him so he decided to make the problem harder. You are given many (not necessarily correct) bracket sequences. The task is to connect some of them into ordered pairs so that each bracket sequence occurs in at most one pair and the concatenation of the bracket sequences in each pair is a correct bracket sequence. The goal is to create as many pairs as possible.This problem unfortunately turned out to be too difficult for Yuhao. Can you help him and solve it?
256 megabytes
import java.util.*; import java.io.*; public class CodeForces { public static void main(String[] args)throws IOException { Scanner sc=new Scanner(System.in); //Scanner sc=new Scanner(new File("ip.txt")); int i,count=0,temp,n,k; n=sc.nextInt(); String out[]=new String[n]; int p[]=new int[n]; for(i=0;i<n;i++) out[i]=sc.next(); int h1[]=new int[500005];//pos int h2[]=new int[500005];//neg for(i=0;i<500005;i++) { h1[i]=0; h2[i]=0; } for(i=0;i<n;i++) { k=countB(out[i]); p[i]=k; if(k==Integer.MAX_VALUE) continue; if(k<0) h2[-k]++; else h1[k]++; } for(i=0;i<n;i++) { temp=0; if(p[i]==Integer.MAX_VALUE) continue; if(p[i]>0&&h1[p[i]]>=1) { temp=Math.min(h1[p[i]],h2[p[i]]); count+=temp; h1[p[i]]-=temp; h2[p[i]]-=temp; } else if(p[i]<0&&h2[-p[i]]>=1) { temp=Math.min(h1[-p[i]],h2[-p[i]]); count+=temp; h1[-p[i]]-=temp; h2[-p[i]]-=temp; } } System.out.println(count+(h1[0]/2)); } static int countB(String s) { int l=s.length(),k=0,i,j; for(j=0;j<l;j++) { if(s.charAt(j)=='(') break; } for(i=j;i<l;i++) { if(s.charAt(i)=='(') { if(k<0) { j-=k; k=0; } k++; } else if (s.charAt(i)==')') k--; } if(j==0) return k; if(k<=0) return k-j; else return Integer.MAX_VALUE; } }
Java
["7\n)())\n)\n((\n((\n(\n)\n)", "4\n(\n((\n(((\n(())", "2\n(())\n()"]
2 seconds
["2", "0", "1"]
NoteIn the first example, it's optimal to construct two pairs: "((     )())" and "(     )".
Java 8
standard input
[ "implementation", "greedy" ]
2cfb08b2269dbf5417c1758def4c035f
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of bracket sequences. Each of the following $$$n$$$ lines contains one bracket sequence — a non-empty string which consists only of characters "(" and ")". The sum of lengths of all bracket sequences in the input is at most $$$5 \cdot 10^5$$$. Note that a bracket sequence may appear in the input multiple times. In this case, you can use each copy of the sequence separately. Also note that the order in which strings appear in the input doesn't matter.
1,400
Print a single integer — the maximum number of pairs which can be made, adhering to the conditions in the statement.
standard output
PASSED
3ce1ed66a8e032fd8e74b2dc2e884473
train_001.jsonl
1546613100
One day, Yuhao came across a problem about checking if some bracket sequences are correct bracket sequences.A bracket sequence is any non-empty sequence of opening and closing parentheses. A bracket sequence is called a correct bracket sequence if it's possible to obtain a correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, the sequences "(())()", "()" and "(()(()))" are correct, while the bracket sequences ")(", "(()" and "(()))(" are not correct.Yuhao found this problem too simple for him so he decided to make the problem harder. You are given many (not necessarily correct) bracket sequences. The task is to connect some of them into ordered pairs so that each bracket sequence occurs in at most one pair and the concatenation of the bracket sequences in each pair is a correct bracket sequence. The goal is to create as many pairs as possible.This problem unfortunately turned out to be too difficult for Yuhao. Can you help him and solve it?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class C { private static class FastReader { private static BufferedReader br; private static StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { String s = ""; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return s; } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } } private static class Pair { int a, b; public Pair(int a, int b) { this.a = a; this.b = b; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Pair)) return false; Pair p = (Pair) o; return (a == p.a) && (b == p.b); } @Override public int hashCode() { return 31 * Integer.valueOf(a).hashCode() + Integer.valueOf(b).hashCode(); } } private static int min(int a, int b) { return a > b ? b : a; } private static int max(int a, int b) { return a < b ? b : a; } public static void main(String[] args) { FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); String[] ss = new String[n]; for (int i = 0; i < n; ss[i++] = in.next()); int mx = 0; List<Pair> l = new ArrayList<>(); for (int i = 0; i < n; i++) { int d0 = 0, d = 0; for (int j = 0; j < ss[i].length(); j++) { if (d == 0) { if (ss[i].charAt(j) == '(') d++; else d0++; } else { if (ss[i].charAt(j) == '(') d++; else d--; if (d < 0) { d0++; d = 0; } } } if ((d0 > 0 && d == 0) || (d0 == 0 && d > 0)) l.add(new Pair(d0, d)); else if (d0 == 0 && d == 0) mx++; } mx /= 2; Map<Integer, Integer> mp1 = new HashMap<>(); Map<Integer, Integer> mp2 = new HashMap<>(); for (Pair p : l) { if (p.a == 0) { mp1.putIfAbsent(p.b, 0); mp1.put(p.b, mp1.get(p.b) + 1); } else { mp2.putIfAbsent(p.a, 0); mp2.put(p.a, mp2.get(p.a) + 1); } } for (Map.Entry<Integer, Integer> e : mp1.entrySet()) { if (mp2.containsKey(e.getKey())) mx += min(e.getValue(), mp2.get(e.getKey())); } out.println(mx); out.close(); } }
Java
["7\n)())\n)\n((\n((\n(\n)\n)", "4\n(\n((\n(((\n(())", "2\n(())\n()"]
2 seconds
["2", "0", "1"]
NoteIn the first example, it's optimal to construct two pairs: "((     )())" and "(     )".
Java 8
standard input
[ "implementation", "greedy" ]
2cfb08b2269dbf5417c1758def4c035f
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of bracket sequences. Each of the following $$$n$$$ lines contains one bracket sequence — a non-empty string which consists only of characters "(" and ")". The sum of lengths of all bracket sequences in the input is at most $$$5 \cdot 10^5$$$. Note that a bracket sequence may appear in the input multiple times. In this case, you can use each copy of the sequence separately. Also note that the order in which strings appear in the input doesn't matter.
1,400
Print a single integer — the maximum number of pairs which can be made, adhering to the conditions in the statement.
standard output
PASSED
63ec3a2c74c6a40b4c17e3a88b2eaac6
train_001.jsonl
1546613100
One day, Yuhao came across a problem about checking if some bracket sequences are correct bracket sequences.A bracket sequence is any non-empty sequence of opening and closing parentheses. A bracket sequence is called a correct bracket sequence if it's possible to obtain a correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, the sequences "(())()", "()" and "(()(()))" are correct, while the bracket sequences ")(", "(()" and "(()))(" are not correct.Yuhao found this problem too simple for him so he decided to make the problem harder. You are given many (not necessarily correct) bracket sequences. The task is to connect some of them into ordered pairs so that each bracket sequence occurs in at most one pair and the concatenation of the bracket sequences in each pair is a correct bracket sequence. The goal is to create as many pairs as possible.This problem unfortunately turned out to be too difficult for Yuhao. Can you help him and solve it?
256 megabytes
//package CodeForces; import java.util.HashMap; import java.util.Scanner; import java.util.Stack; public class YuhaoAndParanthesis { static boolean isBalanced(String str,HashMap<Integer,Integer> left,HashMap<Integer,Integer> right) { Stack<Character> st=new Stack<Character>(); int a=0;int b=0; for(int i=0;i<str.length();i++) { if(str.charAt(i)=='(') { st.push('('); } else { if(st.isEmpty()) { st.push(')'); } else if(st.peek()=='(') { st.pop(); } else { st.push(')'); } } } while(!st.isEmpty()) { if(st.peek()=='(') { a++; } else { b++; } st.pop(); } if(a==0&&b==0) { return true; } else if(a==0) { if(!right.containsKey(b)) { right.put(b,1); } else { right.put(b,right.get(b)+1); } } else if(b==0) { if(!left.containsKey(a)) { left.put(a,1); } else { left.put(a,left.get(a)+1); } } return false; } public static void main(String[] args) { // TODO Auto-generated method stub Scanner s=new Scanner(System.in); int n=s.nextInt(); String str[]=new String[n]; for(int i=0;i<n;i++) { str[i]=s.next(); } HashMap<Integer,Integer> left=new HashMap<>(); HashMap<Integer,Integer> right=new HashMap<>(); int count=0; for(int i=0;i<n;i++) { if(isBalanced(str[i],left,right)) { count++; } } count=count/2; for(int x:left.keySet()) { if(right.containsKey(x)) { count=count+Math.min(left.get(x),right.get(x)); } } System.out.println(count); } }
Java
["7\n)())\n)\n((\n((\n(\n)\n)", "4\n(\n((\n(((\n(())", "2\n(())\n()"]
2 seconds
["2", "0", "1"]
NoteIn the first example, it's optimal to construct two pairs: "((     )())" and "(     )".
Java 8
standard input
[ "implementation", "greedy" ]
2cfb08b2269dbf5417c1758def4c035f
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of bracket sequences. Each of the following $$$n$$$ lines contains one bracket sequence — a non-empty string which consists only of characters "(" and ")". The sum of lengths of all bracket sequences in the input is at most $$$5 \cdot 10^5$$$. Note that a bracket sequence may appear in the input multiple times. In this case, you can use each copy of the sequence separately. Also note that the order in which strings appear in the input doesn't matter.
1,400
Print a single integer — the maximum number of pairs which can be made, adhering to the conditions in the statement.
standard output
PASSED
39328190474b82ea53fa9865f58034f8
train_001.jsonl
1546613100
One day, Yuhao came across a problem about checking if some bracket sequences are correct bracket sequences.A bracket sequence is any non-empty sequence of opening and closing parentheses. A bracket sequence is called a correct bracket sequence if it's possible to obtain a correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, the sequences "(())()", "()" and "(()(()))" are correct, while the bracket sequences ")(", "(()" and "(()))(" are not correct.Yuhao found this problem too simple for him so he decided to make the problem harder. You are given many (not necessarily correct) bracket sequences. The task is to connect some of them into ordered pairs so that each bracket sequence occurs in at most one pair and the concatenation of the bracket sequences in each pair is a correct bracket sequence. The goal is to create as many pairs as possible.This problem unfortunately turned out to be too difficult for Yuhao. Can you help him and solve it?
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; public class Main { static class Task { int NN = 1000006; int MOD = 998244353; int INF = 2000000000; long INFINITY = 1000000000000000000L; int [] a; public void solve(InputReader in, PrintWriter out) { int n = in.nextInt(); a = new int [n]; Map<Integer, Integer> freq = new HashMap<>(); for(int i=0;i<n;++i) { String s = in.next(); int val = f(s);a[i] = val; int cnt = 0; if(freq.containsKey(val)) { cnt = freq.get(val); } ++cnt; freq.put(val, cnt); } int ans = 0; for(int k:freq.keySet()) { if(k == -INF) continue; if(k == 0) { ans += freq.get(0)/2; } else if(k > 0 && freq.containsKey(k) && freq.containsKey(-k)){ int c1 = freq.get(k); int c2 = freq.get(-k); ans += Math.min(c1, c2); } } out.println(ans); } int f(String s) { int n = s.length(); int ret = 0; for(int i=0;i<n;++i) { ret += (s.charAt(i) == '('?1:-1); } if(!valid(s, ret)) return -INF; return ret; } boolean valid(String s, int ret) { if(ret == 0) return isBalanced(s); int n = s.length(); if(ret > 0) { int b = 0; for(int i=0;i<n;++i) { b += (s.charAt(i) == '('?1:-1); if(b < 0) return false; } return true; } else { int b = 0; for(int i=n-1;i>=0;--i) { b += (s.charAt(i) == '('?1:-1); if(b > 0) return false; } return true; } } boolean isBalanced(String s) { int n = s.length(); int b = 0; for(int i=0;i<n;++i) { b += (s.charAt(i) == '('?1:-1); if(b < 0) return false; } return true; } } static void prepareIO(boolean isFileIO) { Task solver = new Task(); // Standard IO if(!isFileIO) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); solver.solve(in, out); out.close(); } // File IO else { String IPfilePath = System.getProperty("user.home") + "/Downloads/ip.in"; String OPfilePath = System.getProperty("user.home") + "/Downloads/op.out"; InputReader fin = new InputReader(IPfilePath); PrintWriter fout = null; try { fout = new PrintWriter(new File(OPfilePath)); } catch (FileNotFoundException e) { e.printStackTrace(); } solver.solve(fin, fout); fout.close(); } } public static void main(String[] args) { prepareIO(false); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public InputReader(String filePath) { File file = new File(filePath); try { reader = new BufferedReader(new FileReader(file)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } tokenizer = null; } public String nextLine() { String str = ""; try { str = reader.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return str; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["7\n)())\n)\n((\n((\n(\n)\n)", "4\n(\n((\n(((\n(())", "2\n(())\n()"]
2 seconds
["2", "0", "1"]
NoteIn the first example, it's optimal to construct two pairs: "((     )())" and "(     )".
Java 8
standard input
[ "implementation", "greedy" ]
2cfb08b2269dbf5417c1758def4c035f
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of bracket sequences. Each of the following $$$n$$$ lines contains one bracket sequence — a non-empty string which consists only of characters "(" and ")". The sum of lengths of all bracket sequences in the input is at most $$$5 \cdot 10^5$$$. Note that a bracket sequence may appear in the input multiple times. In this case, you can use each copy of the sequence separately. Also note that the order in which strings appear in the input doesn't matter.
1,400
Print a single integer — the maximum number of pairs which can be made, adhering to the conditions in the statement.
standard output