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
f8da26a320ecc25a2801c3d87d58dc7d
train_002.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; import java.io.*; public final class Main { public static void main (String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-->0) { int n = sc.nextInt(); int[] arr = new int[n]; PriorityQueue<int[]> pq = new PriorityQueue<>( (a, b) -> a[1] - a[0] == b[1] - b[0] ? Integer.compare(a[0], b[0]) : Integer.compare(b[1] - b[0], a[1] - a[0])); pq.add(new int[]{0, n-1}); int x = 0; while(!pq.isEmpty()) { int[] curr = pq.poll(); int l = curr[0]; int r = curr[1]; int mid = (l+r)/2; arr[mid] = ++x; if(l<=mid-1) pq.add(new int[]{l, mid-1}); if(r>=mid+1) pq.add(new int[]{mid+1, r}); } for(int i: arr) System.out.print(i + " "); System.out.println(); } } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
34299b84b1eedfc288ccb27e5fd73e80
train_002.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; import java.io.*; public final class Main { static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } public static void main (String[] args) throws Exception { Reader sc = new Reader(); int t = sc.nextInt(); while(t-->0) { int n = sc.nextInt(); int[] arr = new int[n]; PriorityQueue<int[]> pq = new PriorityQueue<>((a, b)->((b[1]-b[0])==(a[1]-a[0]))?(a[0]-b[0]):(b[1]-b[0]-(a[1]-a[0]))); pq.add(new int[]{1, n}); int x = 0; while(!pq.isEmpty()) { int[] curr = pq.poll(); int l = curr[0]; int r = curr[1]; int mid = (l+r)/2; if((r-l+1)%2==0) mid = (l+r-1)/2; arr[mid-1] = ++x; if(l<=mid-1) pq.add(new int[]{l, mid-1}); if(r>=mid+1) pq.add(new int[]{mid+1, r}); } for(int i: arr) System.out.print(i + " "); System.out.println(); } } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
0389e8c7c5aad1e47e9c17d2dc5f5850
train_002.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; import java.io.*; /** * @author Azuz * */ public class Main { void solve(Scanner in, PrintWriter out) { int tt = in.nextInt(); while (tt-->0) { int n = in.nextInt(); PriorityQueue<Tuple> q = new PriorityQueue<>(); q.offer(new Tuple(0, n - 1, n)); int[] ans = new int[n]; int cur = 0; while (!q.isEmpty()) { Tuple t = q.poll(); if (t.f > t.s) continue; if (t.f == t.s) { ans[t.f] = ++cur; continue; } int mid = (t.s + t.f - 1) >> 1; if (t.t % 2 == 1) { mid = (t.f + t.s) >> 1; } ans[mid] = ++cur; q.offer(new Tuple(t.f, mid - 1, mid - t.f)); q.offer(new Tuple(mid + 1, t.s, t.s - mid)); } for (int i = 0; i < n; ++i) { out.print(ans[i] + " "); } out.println(); } } public static void main(String[] args) { try(Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out)) { new Main().solve(in, out); } } private class Tuple implements Comparable<Tuple> { int f, s, t; public Tuple(int f, int s, int t) { this.f = f; this.s = s; this.t = t; } @Override public int compareTo(Tuple t) { if (t.t == this.t) return this.f - t.f; return t.t - this.t; } } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
be0eedad3fd51ae9d53e695088c3ed79
train_002.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.*; import javax.management.Query; import javax.swing.Box.Filler; public class prop { static Scanner sc; static PrintWriter pw; static int a[]; static int n; static boolean v[]; static int x = 1; static class pair implements Comparable<pair> { int x, y; pair(int i, int j) { x = i; y = j; } @Override public int compareTo(pair o) { int q = y - x; int w = o.y - o.x; if (q == w) return x - o.x; return w - q; } } public static void fill(int i, int j) { PriorityQueue<pair> q = new PriorityQueue<>(); q.add(new pair(i, j)); while (!q.isEmpty()) { pair p = q.poll(); a[(p.x + p.y) / 2] = x++; if (p.y != (p.x + p.y) / 2) q.add(new pair((p.x + p.y) / 2 + 1, p.y)); if (p.x != (p.x + p.y) / 2) q.add(new pair(p.x, (p.x + p.y) / 2 - 1)); } } public static void main(String[] args) throws IOException { sc = new Scanner(System.in); pw = new PrintWriter(System.out); int t = sc.nextInt(); while (t-- > 0) { n = sc.nextInt(); a = new int[n]; x = 1; fill(0, n - 1); for(int x:a) pw.print(x+" "); pw.println(); } pw.flush(); } ////////////////////////////////////////////////////////////////////////////////////////////////// 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
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
a0fe6b13f4738711704a890f14d14834
train_002.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; import java.io.*; public class ConstructingTheArray { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); int t = Integer.parseInt(br.readLine()); while (--t >= 0) { int n = Integer.parseInt(br.readLine()); int[] res = new int[n]; TreeMap<Integer, TreeSet<Integer>> chains = new TreeMap<>(); chains.put(n, new TreeSet<>()); chains.get(n).add((n-1)/2); for (int i = 1; i <= n; ++i) { Map.Entry<Integer, TreeSet<Integer>> e = chains.lastEntry(); int index = e.getValue().first(); e.getValue().remove(index); res[index] = i; int sizeA, sizeB, a, b; if ((e.getKey() & 1) == 0) { sizeB = e.getKey() / 2; sizeA = sizeB - 1; a = (index * 2 - sizeA - 1) / 2; b = (index * 2 + sizeB + 1) / 2; } else { sizeA = e.getKey() / 2; sizeB = sizeA; a = (index * 2 - sizeA - 1) / 2; b = (index * 2 + sizeB + 1) / 2; } if (sizeA >= 0) { if (!chains.containsKey(sizeA)) { chains.put(sizeA, new TreeSet<>()); } chains.get(sizeA).add(a); } if (sizeB >= 0) { if (!chains.containsKey(sizeB)) { chains.put(sizeB, new TreeSet<>()); } chains.get(sizeB).add(b); } if (e.getValue().isEmpty()) { chains.remove(e.getKey()); } } for (int i : res) { bw.write(Integer.toString(i)); bw.write(' '); } bw.newLine(); } br.close(); bw.close(); } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
a048afc32183cda9b4389601b816a9bf
train_002.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for(int i = 0; i < t; i++) { int n = sc.nextInt(); int l = 1, r = n; Queue<int[]> q = new PriorityQueue<>((a,b) -> b[2] == a[2] ? a[0] - b[0] : b[2] - a[2]); int[] res = new int[n + 1]; q.offer(new int[] {l, r, r - l}); for(int j = 1; j <= n; j++) { int[] curr = q.poll(); int left = curr[0]; int right = curr[1]; if(left == right) { res[left] = j; continue; } int mid = 0; if((right - left + 1) % 2 == 1) { mid = (left + right) / 2; res[mid] = j; }else { mid = (left + right - 1) / 2; res[mid] = j; } q.offer(new int[] {left, mid - 1, mid - left - 1}); q.offer(new int[] {mid + 1, right, right - mid - 1}); } for(int j = 1; j <= n; j++) { System.out.print(res[j] + " "); } System.out.println(); } } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
0fd711fbc30d299ec0d49192f25c1332
train_002.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*;import java.io.*;import java.math.*; public class Main { static class Node{ int l,r,dist; public Node(int l,int r){ this.l=l; this.r=r; dist=(r-l+1); } } static public class sortByDist implements Comparator<Node>{ public int compare(Node A,Node B){ if(A.dist==B.dist) return A.l-B.l; return -(A.dist-B.dist); } } public static void process()throws IOException { int n=ni(),arr[]=new int[n+1]; PriorityQueue<Node> pq = new PriorityQueue<>(new sortByDist()); pq.add(new Node(1,n)); int ele=1; while(!pq.isEmpty()){ Node nn=pq.poll(); int l=nn.l,r=nn.r,dist=nn.dist,idx=0; if(dist%2==0) idx=(r+l-1)/2; else idx=(r+l)/2; arr[idx]=ele; ele++; if(l<=idx-1){ pq.add(new Node(l,idx-1)); } if(idx+1<=r) pq.add(new Node(idx+1,r)); } StringBuilder res = new StringBuilder(); for(int i=1;i<=n;i++) res.append(String.valueOf(arr[i])+" "); pn(res); } static AnotherReader sc; static PrintWriter out; public static void main(String[]args)throws IOException { out = new PrintWriter(System.out); sc=new AnotherReader(); boolean oj = true; oj = System.getProperty("ONLINE_JUDGE") != null; if(!oj) sc=new AnotherReader(100); long s = System.currentTimeMillis(); int t=1; t=ni(); while(t-->0) process(); out.flush(); if(!oj) System.out.println(System.currentTimeMillis()-s+"ms"); System.out.close(); } static void pn(Object o){out.println(o);} static void p(Object o){out.print(o);} static void pni(Object o){out.println(o);System.out.flush();} static int ni()throws IOException{return sc.nextInt();} static long nl()throws IOException{return sc.nextLong();} static double nd()throws IOException{return sc.nextDouble();} static String nln()throws IOException{return sc.nextLine();} static long gcd(long a, long b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int gcd(int a, int b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int bit(long n)throws IOException{return (n==0)?0:(1+bit(n&(n-1)));} static boolean multipleTC=false; static long mod=(long)1e9+7l; static void r_sort(int arr[],int n){ Random r = new Random(); for (int i = n-1; i > 0; i--){ int j = r.nextInt(i+1); int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } Arrays.sort(arr); } static long mpow(long x, long n) { if(n == 0) return 1; if(n % 2 == 0) { long root = mpow(x, n / 2); return root * root % mod; }else { return x * mpow(x, n - 1) % mod; } } static long mcomb(long a, long b) { if(b > a - b) return mcomb(a, a - b); long m = 1; long d = 1; long i; for(i = 0; i < b; i++) { m *= (a - i); m %= mod; d *= (i + 1); d %= mod; } long ans = m * mpow(d, mod - 2) % mod; return ans; } ///////////////////////////////////////////////////////////////////////////////////////////////////////// static class AnotherReader{BufferedReader br; StringTokenizer st; AnotherReader()throws FileNotFoundException{ br=new BufferedReader(new InputStreamReader(System.in));} AnotherReader(int a)throws FileNotFoundException{ br = new BufferedReader(new FileReader("input.txt"));} String next()throws IOException{ while (st == null || !st.hasMoreElements()) {try{ st = new StringTokenizer(br.readLine());} catch (IOException e){ e.printStackTrace(); }} return st.nextToken(); } int nextInt() throws IOException{ return Integer.parseInt(next());} long nextLong() throws IOException {return Long.parseLong(next());} double nextDouble()throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException{ String str = ""; try{ str = br.readLine();} catch (IOException e){ e.printStackTrace();} return str;}} ///////////////////////////////////////////////////////////////////////////////////////////////////////////// }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
06ba355b3239fed7a8f2f69ee771a3e3
train_002.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class D { static class Pair{ int l,r,len; public Pair(int l,int r){ this.l = l; this.r = r; len = r - l +1; } } public static void process()throws IOException { int n = ni(), arr[] = new int[n+1], cnt = 1; PriorityQueue<Pair> pq = new PriorityQueue<>( (A, B)-> (A.len == B.len) ? (A.l - B.l) : (B.len - A.len)); pq.add(new Pair(1,n)); while(!pq.isEmpty()){ Pair node = pq.poll(); int l = node.l, r = node.r, mid = l + (r-l)/2; arr[mid] = cnt; cnt++; if(l==r) continue; if(l <= mid-1) pq.add(new Pair(l,mid-1)); if(mid+1 <= r) pq.add(new Pair(mid+1,r)); } StringBuilder res = new StringBuilder(); for(int i = 1; i<=n; i++) res.append(arr[i]+" "); pn(res); } static FastReader sc; static PrintWriter out; public static void main(String[]args)throws IOException { out = new PrintWriter(System.out); sc=new FastReader(); long s = System.currentTimeMillis(); int t=1; t=ni(); while(t-->0) process(); out.flush(); System.err.println(System.currentTimeMillis()-s+"ms"); } static void pn(Object o){out.println(o);} static void p(Object o){out.print(o);} static int ni()throws IOException{return Integer.parseInt(sc.next());} static long nl()throws IOException{return Long.parseLong(sc.next());} static double nd()throws IOException{return Double.parseDouble(sc.next());} static String nln()throws IOException{return sc.nextLine();} static long gcd(long a, long b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int gcd(int a, int b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int bit(long n)throws IOException{return (n==0)?0:(1+bit(n&(n-1)));} static long mod=(long)1e9+7l; ///////////////////////////////////////////////////////////////////////////////////////////////////////// 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(); } String nextLine(){ String str = ""; try{ str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////// }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
ed3d884a736344c84f977c3b4d8b78b1
train_002.jsonl
1589466900
You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.math.BigInteger; import java.util.*; public class Main { public static void main(final String[] args) { final Scanner in = new Scanner(System.in); int num = in.nextInt(); while (num-- != 0) { int n = in.nextInt(); int[] dt = new int[n+1]; PriorityQueue<D> pq = new PriorityQueue<>(n); pq.add(new D(1, n)); int k = 1; while (!pq.isEmpty()) { D d = pq.poll(); if (d.x == d.y) { dt[d.x] = k++; continue; } int mid = ((d.x + d.y - 1) % 2 == 1 ? (d.x + d.y) / 2 : (d.x + d.y - 1) / 2); dt[mid] = k++; if (mid - 1 > 0 && dt[mid - 1] == 0) pq.add(new D(d.x, mid -1)); if (mid < n && dt[mid + 1] == 0) pq.add(new D(mid+1, d.y)); } for (int i = 1; i <= n; i++) { System.out.print(dt[i] + " "); } System.out.println(); } } } class D implements Comparable<D>{ int x; int y; int d; D (int a, int b) { x = a; y = b; d = b-a; } @Override public int compareTo(D o) { if (d != o.d) return o.d - d; else return x - o.x; } }
Java
["6\n1\n2\n3\n4\n5\n6"]
1 second
["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"]
null
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings" ]
25fbe21a449c1ab3eb4bdd95a171d093
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).
1,600
For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.
standard output
PASSED
3956c0c19c7ec947420409911e062559
train_002.jsonl
1463416500
There are n banks in the city where Vasya lives, they are located in a circle, such that any two banks are neighbouring if their indices differ by no more than 1. Also, bank 1 and bank n are neighbours if n &gt; 1. No bank is a neighbour of itself.Vasya has an account in each bank. Its balance may be negative, meaning Vasya owes some money to this bank.There is only one type of operations available: transfer some amount of money from any bank to account in any neighbouring bank. There are no restrictions on the size of the sum being transferred or balance requirements to perform this operation.Vasya doesn't like to deal with large numbers, so he asks you to determine the minimum number of operations required to change the balance of each bank account to zero. It's guaranteed, that this is possible to achieve, that is, the total balance of Vasya in all banks is equal to zero.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class cf675c { public static void main(String[] args) throws IOException { int n = ri(), a[] = ria(n), db[] = new int[n * 2], seg[] = new int[n], ans = n - 1; for (int i = 0; i < n; ++i) { db[i] = db[n + i] = a[i]; } Map<Long, Integer> last = new HashMap<>(); last.put(0L, -1); long sum = 0; for (int i = 0; i < 2 * n; ++i) { sum += db[i]; if (last.containsKey(sum)) { if (last.get(sum) < n - 1) { seg[last.get(sum) + 1] = i - last.get(sum) - 1; } } last.put(sum, i); } boolean vis[] = new boolean[n]; for (int i = 0; i < n; ++i) { if (!vis[i]) { int j = i, cnt = 0; while (j < n) { vis[j] = true; cnt += seg[j]; j += seg[j] + 1; } ans = min(ans, cnt); } } prln(ans); close(); } static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out)); static StringTokenizer input; static Random __rand = new Random(); // references // IBIG = 1e9 + 7 // IMAX ~= 2e9 // LMAX ~= 9e18 // constants static final int IBIG = 1000000007; static final int IMAX = 2147483647; static final int IMIN = -2147483648; static final long LMAX = 9223372036854775807L; static final long LMIN = -9223372036854775808L; // math util static int minof(int a, int b, int c) {return min(a, min(b, c));} static int minof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;} static long minof(long a, long b, long c) {return min(a, min(b, c));} static long minof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;} static int maxof(int a, int b, int c) {return max(a, max(b, c));} static int maxof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;} static long maxof(long a, long b, long c) {return max(a, max(b, c));} static long maxof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;} static int powi(int a, int b) {if (a == 0) return 0; int ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static long powl(long a, int b) {if (a == 0) return 0; long ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static int fli(double d) {return (int) d;} static int cei(double d) {return (int) ceil(d);} static long fll(double d) {return (long) d;} static long cel(double d) {return (long) ceil(d);} static int gcf(int a, int b) {return b == 0 ? a : gcf(b, a % b);} static long gcf(long a, long b) {return b == 0 ? a : gcf(b, a % b);} static int lcm(int a, int b) {return a * b / gcf(a, b);} static long lcm(long a, long b) {return a * b / gcf(a, b);} static int randInt(int min, int max) {return __rand.nextInt(max - min + 1) + min;} static long mix(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);} // array util static void reverse(int[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(long[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(double[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(char[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void shuffle(int[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(long[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(double[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void rsort(int[] a) {shuffle(a); sort(a);} static void rsort(long[] a) {shuffle(a); sort(a);} static void rsort(double[] a) {shuffle(a); sort(a);} static int[] copy(int[] a) {int[] ans = new int[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static long[] copy(long[] a) {long[] ans = new long[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static double[] copy(double[] a) {double[] ans = new double[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static char[] copy(char[] a) {char[] ans = new char[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} // input static void r() throws IOException {input = new StringTokenizer(rline());} static int ri() throws IOException {return Integer.parseInt(rline());} static long rl() throws IOException {return Long.parseLong(rline());} static double rd() throws IOException {return Double.parseDouble(rline());} static int[] ria(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni(); return a;} static int[] riam1(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni() - 1; return a;} static long[] rla(int n) throws IOException {long[] a = new long[n]; r(); for (int i = 0; i < n; ++i) a[i] = nl(); return a;} static double[] rda(int n) throws IOException {double[] a = new double[n]; r(); for (int i = 0; i < n; ++i) a[i] = nd(); return a;} static char[] rcha() throws IOException {return rline().toCharArray();} static String rline() throws IOException {return __in.readLine();} static String n() {return input.nextToken();} static int rni() throws IOException {r(); return ni();} static int ni() {return Integer.parseInt(n());} static long rnl() throws IOException {r(); return nl();} static long nl() {return Long.parseLong(n());} static double rnd() throws IOException {r(); return nd();} static double nd() {return Double.parseDouble(n());} // output static void pr(int i) {__out.print(i);} static void prln(int i) {__out.println(i);} static void pr(long l) {__out.print(l);} static void prln(long l) {__out.println(l);} static void pr(double d) {__out.print(d);} static void prln(double d) {__out.println(d);} static void pr(char c) {__out.print(c);} static void prln(char c) {__out.println(c);} static void pr(char[] s) {__out.print(new String(s));} static void prln(char[] s) {__out.println(new String(s));} static void pr(String s) {__out.print(s);} static void prln(String s) {__out.println(s);} static void pr(Object o) {__out.print(o);} static void prln(Object o) {__out.println(o);} static void prln() {__out.println();} static void pryes() {prln("yes");} static void pry() {prln("Yes");} static void prY() {prln("YES");} static void prno() {prln("no");} static void prn() {prln("No");} static void prN() {prln("NO");} static boolean pryesno(boolean b) {prln(b ? "yes" : "no"); return b;}; static boolean pryn(boolean b) {prln(b ? "Yes" : "No"); return b;} static boolean prYN(boolean b) {prln(b ? "YES" : "NO"); return b;} static void prln(int... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static void prln(long... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static void prln(double... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for (int i = 0; i < n; pr(iter.next()), pr(' '), ++i); if (n >= 0) prln(iter.next()); else prln();} static void h() {prln("hlfd"); flush();} static void flush() {__out.flush();} static void close() {__out.close();} }
Java
["3\n5 0 -5", "4\n-1 0 1 0", "4\n1 2 3 -6"]
1 second
["1", "2", "3"]
NoteIn the first sample, Vasya may transfer 5 from the first bank to the third.In the second sample, Vasya may first transfer 1 from the third bank to the second, and then 1 from the second to the first.In the third sample, the following sequence provides the optimal answer: transfer 1 from the first bank to the second bank; transfer 3 from the second bank to the third; transfer 6 from the third bank to the fourth.
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings", "greedy" ]
be12bb8148708f9ad3dc33b83b55eb1e
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of banks. The second line contains n integers ai ( - 109 ≤ ai ≤ 109), the i-th of them is equal to the initial balance of the account in the i-th bank. It's guaranteed that the sum of all ai is equal to 0.
2,100
Print the minimum number of operations required to change balance in each bank to zero.
standard output
PASSED
2de7111787676004c3d59ba8de0bea29
train_002.jsonl
1463416500
There are n banks in the city where Vasya lives, they are located in a circle, such that any two banks are neighbouring if their indices differ by no more than 1. Also, bank 1 and bank n are neighbours if n &gt; 1. No bank is a neighbour of itself.Vasya has an account in each bank. Its balance may be negative, meaning Vasya owes some money to this bank.There is only one type of operations available: transfer some amount of money from any bank to account in any neighbouring bank. There are no restrictions on the size of the sum being transferred or balance requirements to perform this operation.Vasya doesn't like to deal with large numbers, so he asks you to determine the minimum number of operations required to change the balance of each bank account to zero. It's guaranteed, that this is possible to achieve, that is, the total balance of Vasya in all banks is equal to zero.
256 megabytes
import java.io.BufferedOutputStream; import java.io.Closeable; import java.io.DataInputStream; import java.io.Flushable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import java.util.HashMap; import java.util.InputMismatchException; import java.util.Map.Entry; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { static class TaskAdapter implements Runnable { @Override public void run() { long startTime = System.currentTimeMillis(); InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); Output out = new Output(outputStream); CMoneyTransfers solver = new CMoneyTransfers(); solver.solve(1, in, out); out.close(); System.err.println(System.currentTimeMillis()-startTime+"ms"); } } public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1<<28); thread.start(); thread.join(); } static class CMoneyTransfers { public CMoneyTransfers() { } public void solve(int kase, InputReader in, Output pw) { int n = in.nextInt(); long[] arr = in.nextLong(n); Arrays.parallelPrefix(arr, Long::sum); HashMap<Long, Integer> count = new HashMap<>(); for(long i: arr) { count.put(i, count.getOrDefault(i, 0)+1); } int ans = 0; for(var v: count.entrySet()) { ans = Math.max(ans, v.getValue()); } pw.println(n-ans); } } static interface InputReader { int nextInt(); long nextLong(); default long[] nextLong(int n) { long[] ret = new long[n]; for(int i = 0; i<n; i++) { ret[i] = nextLong(); } return ret; } } static class Output implements Closeable, Flushable { public StringBuilder sb; public OutputStream os; public int BUFFER_SIZE; public String lineSeparator; public Output(OutputStream os) { this(os, 1<<16); } public Output(OutputStream os, int bs) { BUFFER_SIZE = bs; sb = new StringBuilder(BUFFER_SIZE); this.os = new BufferedOutputStream(os, 1<<17); lineSeparator = System.lineSeparator(); } public void println(int i) { println(String.valueOf(i)); } public void println(String s) { sb.append(s); println(); } public void println() { sb.append(lineSeparator); } private void flushToBuffer() { try { os.write(sb.toString().getBytes()); }catch(IOException e) { e.printStackTrace(); } sb = new StringBuilder(BUFFER_SIZE); } public void flush() { try { flushToBuffer(); os.flush(); }catch(IOException e) { e.printStackTrace(); } } public void close() { flush(); try { os.close(); }catch(IOException e) { e.printStackTrace(); } } } static class FastReader implements InputReader { final private int BUFFER_SIZE = 1<<16; private DataInputStream din; private byte[] buffer; private int bufferPointer; private int bytesRead; public FastReader(InputStream is) { din = new DataInputStream(is); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public int nextInt() { int ret = 0; byte c = skipToDigit(); 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() { long ret = 0; byte c = skipToDigit(); 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; } private boolean isDigit(byte b) { return b>='0'&&b<='9'; } private byte skipToDigit() { byte ret; while(!isDigit(ret = read())&&ret!='-') ; return ret; } private void fillBuffer() { try { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); }catch(IOException e) { e.printStackTrace(); throw new InputMismatchException(); } if(bytesRead==-1) { buffer[0] = -1; } } private byte read() { if(bytesRead==-1) { throw new InputMismatchException(); }else if(bufferPointer==bytesRead) { fillBuffer(); } return buffer[bufferPointer++]; } } }
Java
["3\n5 0 -5", "4\n-1 0 1 0", "4\n1 2 3 -6"]
1 second
["1", "2", "3"]
NoteIn the first sample, Vasya may transfer 5 from the first bank to the third.In the second sample, Vasya may first transfer 1 from the third bank to the second, and then 1 from the second to the first.In the third sample, the following sequence provides the optimal answer: transfer 1 from the first bank to the second bank; transfer 3 from the second bank to the third; transfer 6 from the third bank to the fourth.
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings", "greedy" ]
be12bb8148708f9ad3dc33b83b55eb1e
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of banks. The second line contains n integers ai ( - 109 ≤ ai ≤ 109), the i-th of them is equal to the initial balance of the account in the i-th bank. It's guaranteed that the sum of all ai is equal to 0.
2,100
Print the minimum number of operations required to change balance in each bank to zero.
standard output
PASSED
96b9c802bec378fe3cd11623a1127565
train_002.jsonl
1463416500
There are n banks in the city where Vasya lives, they are located in a circle, such that any two banks are neighbouring if their indices differ by no more than 1. Also, bank 1 and bank n are neighbours if n &gt; 1. No bank is a neighbour of itself.Vasya has an account in each bank. Its balance may be negative, meaning Vasya owes some money to this bank.There is only one type of operations available: transfer some amount of money from any bank to account in any neighbouring bank. There are no restrictions on the size of the sum being transferred or balance requirements to perform this operation.Vasya doesn't like to deal with large numbers, so he asks you to determine the minimum number of operations required to change the balance of each bank account to zero. It's guaranteed, that this is possible to achieve, that is, the total balance of Vasya in all banks is equal to zero.
256 megabytes
import java.io.BufferedOutputStream; import java.io.Closeable; import java.io.DataInputStream; import java.io.Flushable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import java.util.HashMap; import java.util.InputMismatchException; import java.util.Map.Entry; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { static class TaskAdapter implements Runnable { @Override public void run() { long startTime = System.currentTimeMillis(); InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); Output out = new Output(outputStream); CMoneyTransfers solver = new CMoneyTransfers(); solver.solve(1, in, out); out.close(); System.err.println(System.currentTimeMillis()-startTime+"ms"); } } public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1<<28); thread.start(); thread.join(); } static class CMoneyTransfers { public CMoneyTransfers() { } public void solve(int kase, InputReader in, Output pw) { int n = in.nextInt(); long[] arr = in.nextLong(n); Arrays.parallelPrefix(arr, (o1, o2) -> o1+o2); HashMap<Long, Integer> count = new HashMap<>(); for(long i: arr) { count.put(i, count.getOrDefault(i, 0)+1); } int ans = 0; for(var v: count.entrySet()) { ans = Math.max(ans, v.getValue()); } pw.println(n-ans); } } static interface InputReader { int nextInt(); long nextLong(); default long[] nextLong(int n) { long[] ret = new long[n]; for(int i = 0; i<n; i++) { ret[i] = nextLong(); } return ret; } } static class Output implements Closeable, Flushable { public StringBuilder sb; public OutputStream os; public int BUFFER_SIZE; public String lineSeparator; public Output(OutputStream os) { this(os, 1<<16); } public Output(OutputStream os, int bs) { BUFFER_SIZE = bs; sb = new StringBuilder(BUFFER_SIZE); this.os = new BufferedOutputStream(os, 1<<17); lineSeparator = System.lineSeparator(); } public void println(int i) { println(String.valueOf(i)); } public void println(String s) { sb.append(s); println(); } public void println() { sb.append(lineSeparator); } private void flushToBuffer() { try { os.write(sb.toString().getBytes()); }catch(IOException e) { e.printStackTrace(); } sb = new StringBuilder(BUFFER_SIZE); } public void flush() { try { flushToBuffer(); os.flush(); }catch(IOException e) { e.printStackTrace(); } } public void close() { flush(); try { os.close(); }catch(IOException e) { e.printStackTrace(); } } } static class FastReader implements InputReader { final private int BUFFER_SIZE = 1<<16; private DataInputStream din; private byte[] buffer; private int bufferPointer; private int bytesRead; public FastReader(InputStream is) { din = new DataInputStream(is); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public int nextInt() { int ret = 0; byte c = skipToDigit(); 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() { long ret = 0; byte c = skipToDigit(); 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; } private boolean isDigit(byte b) { return b>='0'&&b<='9'; } private byte skipToDigit() { byte ret; while(!isDigit(ret = read())&&ret!='-') ; return ret; } private void fillBuffer() { try { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); }catch(IOException e) { e.printStackTrace(); throw new InputMismatchException(); } if(bytesRead==-1) { buffer[0] = -1; } } private byte read() { if(bytesRead==-1) { throw new InputMismatchException(); }else if(bufferPointer==bytesRead) { fillBuffer(); } return buffer[bufferPointer++]; } } }
Java
["3\n5 0 -5", "4\n-1 0 1 0", "4\n1 2 3 -6"]
1 second
["1", "2", "3"]
NoteIn the first sample, Vasya may transfer 5 from the first bank to the third.In the second sample, Vasya may first transfer 1 from the third bank to the second, and then 1 from the second to the first.In the third sample, the following sequence provides the optimal answer: transfer 1 from the first bank to the second bank; transfer 3 from the second bank to the third; transfer 6 from the third bank to the fourth.
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings", "greedy" ]
be12bb8148708f9ad3dc33b83b55eb1e
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of banks. The second line contains n integers ai ( - 109 ≤ ai ≤ 109), the i-th of them is equal to the initial balance of the account in the i-th bank. It's guaranteed that the sum of all ai is equal to 0.
2,100
Print the minimum number of operations required to change balance in each bank to zero.
standard output
PASSED
4e24f984ceebe75e71242947ed5dbf34
train_002.jsonl
1463416500
There are n banks in the city where Vasya lives, they are located in a circle, such that any two banks are neighbouring if their indices differ by no more than 1. Also, bank 1 and bank n are neighbours if n &gt; 1. No bank is a neighbour of itself.Vasya has an account in each bank. Its balance may be negative, meaning Vasya owes some money to this bank.There is only one type of operations available: transfer some amount of money from any bank to account in any neighbouring bank. There are no restrictions on the size of the sum being transferred or balance requirements to perform this operation.Vasya doesn't like to deal with large numbers, so he asks you to determine the minimum number of operations required to change the balance of each bank account to zero. It's guaranteed, that this is possible to achieve, that is, the total balance of Vasya in all banks is equal to zero.
256 megabytes
import java.io.BufferedOutputStream; import java.io.Closeable; import java.io.DataInputStream; import java.io.Flushable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.HashMap; import java.util.InputMismatchException; import java.util.Map.Entry; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { static class TaskAdapter implements Runnable { @Override public void run() { long startTime = System.currentTimeMillis(); InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); Output out = new Output(outputStream); CMoneyTransfers solver = new CMoneyTransfers(); solver.solve(1, in, out); out.close(); System.err.println(System.currentTimeMillis()-startTime+"ms"); } } public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1<<28); thread.start(); thread.join(); } static class CMoneyTransfers { public CMoneyTransfers() { } public void solve(int kase, InputReader in, Output pw) { int n = in.nextInt(); long[] arr = in.nextLong(n); long[] psum = new long[n]; psum[0] = arr[0]; for(int i = 1; i<n; i++) { psum[i] = psum[i-1]+arr[i]; } HashMap<Long, Integer> count = new HashMap<>(); for(long i: psum) { count.put(i, count.getOrDefault(i, 0)+1); } int ans = 0; for(var v: count.entrySet()) { ans = Math.max(ans, v.getValue()); } pw.println(n-ans); } } static interface InputReader { int nextInt(); long nextLong(); default long[] nextLong(int n) { long[] ret = new long[n]; for(int i = 0; i<n; i++) { ret[i] = nextLong(); } return ret; } } static class Output implements Closeable, Flushable { public StringBuilder sb; public OutputStream os; public int BUFFER_SIZE; public String lineSeparator; public Output(OutputStream os) { this(os, 1<<16); } public Output(OutputStream os, int bs) { BUFFER_SIZE = bs; sb = new StringBuilder(BUFFER_SIZE); this.os = new BufferedOutputStream(os, 1<<17); lineSeparator = System.lineSeparator(); } public void println(int i) { println(String.valueOf(i)); } public void println(String s) { sb.append(s); println(); } public void println() { sb.append(lineSeparator); } private void flushToBuffer() { try { os.write(sb.toString().getBytes()); }catch(IOException e) { e.printStackTrace(); } sb = new StringBuilder(BUFFER_SIZE); } public void flush() { try { flushToBuffer(); os.flush(); }catch(IOException e) { e.printStackTrace(); } } public void close() { flush(); try { os.close(); }catch(IOException e) { e.printStackTrace(); } } } static class FastReader implements InputReader { final private int BUFFER_SIZE = 1<<16; private DataInputStream din; private byte[] buffer; private int bufferPointer; private int bytesRead; public FastReader(InputStream is) { din = new DataInputStream(is); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public int nextInt() { int ret = 0; byte c = skipToDigit(); 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() { long ret = 0; byte c = skipToDigit(); 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; } private boolean isDigit(byte b) { return b>='0'&&b<='9'; } private byte skipToDigit() { byte ret; while(!isDigit(ret = read())&&ret!='-') ; return ret; } private void fillBuffer() { try { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); }catch(IOException e) { e.printStackTrace(); throw new InputMismatchException(); } if(bytesRead==-1) { buffer[0] = -1; } } private byte read() { if(bytesRead==-1) { throw new InputMismatchException(); }else if(bufferPointer==bytesRead) { fillBuffer(); } return buffer[bufferPointer++]; } } }
Java
["3\n5 0 -5", "4\n-1 0 1 0", "4\n1 2 3 -6"]
1 second
["1", "2", "3"]
NoteIn the first sample, Vasya may transfer 5 from the first bank to the third.In the second sample, Vasya may first transfer 1 from the third bank to the second, and then 1 from the second to the first.In the third sample, the following sequence provides the optimal answer: transfer 1 from the first bank to the second bank; transfer 3 from the second bank to the third; transfer 6 from the third bank to the fourth.
Java 11
standard input
[ "data structures", "constructive algorithms", "sortings", "greedy" ]
be12bb8148708f9ad3dc33b83b55eb1e
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of banks. The second line contains n integers ai ( - 109 ≤ ai ≤ 109), the i-th of them is equal to the initial balance of the account in the i-th bank. It's guaranteed that the sum of all ai is equal to 0.
2,100
Print the minimum number of operations required to change balance in each bank to zero.
standard output
PASSED
580a877f0797c35d4b9d42532a102267
train_002.jsonl
1418833800
You are an assistant director in a new musical play. The play consists of n musical parts, each part must be performed by exactly one actor. After the casting the director chose m actors who can take part in the play. Your task is to assign the parts to actors. However, there are several limitations.First, each actor has a certain voice range and there are some parts that he cannot sing. Formally, there are two integers for each actor, ci and di (ci ≤ di) — the pitch of the lowest and the highest note that the actor can sing. There also are two integers for each part — aj and bj (aj ≤ bj) — the pitch of the lowest and the highest notes that are present in the part. The i-th actor can perform the j-th part if and only if ci ≤ aj ≤ bj ≤ di, i.e. each note of the part is in the actor's voice range.According to the contract, the i-th actor can perform at most ki parts. Besides, you are allowed not to give any part to some actors (then they take part in crowd scenes).The rehearsal starts in two hours and you need to do the assignment quickly!
256 megabytes
import java.util.List; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.SortedSet; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.NoSuchElementException; import java.util.TreeSet; import java.util.StringTokenizer; import java.util.Collections; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Kartik Singal (ka4tik) */ 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 { class Tuple implements Comparable<Tuple>{ int x,y,k,index; public Tuple(int x, int y, int k,int index) { this.x=x; this.y=y; this.k=k; this.index=index; } public int compareTo(Tuple other) { if(y<other.y) return -1; else if(y>other.y) return 1; else if(index<other.index) return -1; else if(index>other.index) return 1; else return 0; } } class Event implements Comparable<Event>{ int x,y,type,index; public Event(int x, int y, int type, int index) { this.x=x; this.y=y; this.type=type; this.index=index; } public int compareTo(Event other) { if(x<other.x) return -1; else if(x>other.x) return 1; else if(type<other.type) return -1; else if(type>other.type) return 1; else if(y<other.y) return -1; else if(y>other.y) return 1; else if(index<other.index) return -1; else if(index>other.index) return 1; else return 0; } } class Pair implements Comparable<Pair>{ int x,y; public Pair(int x, int y) { this.x=x; this.y=y; } public int compareTo(Pair other) { if(x<other.x) return -1; else if(x>other.x) return 1; else if(y<other.y) return -1; else if(y>other.y) return 1; else return 0; } } public void solve(int testNumber, InputReader in, PrintWriter out) { int n=in.nextInt(); ArrayList<Event> events=new ArrayList<Event>(); Pair[] parts=new Pair[n]; for(int i=0;i<n;i++) { parts[i] = new Pair(in.nextInt(), in.nextInt()); events.add(new Event(parts[i].x,parts[i].y,1,i+1)); } int m=in.nextInt(); Event[] actors=new Event[m]; for(int i=0;i<m;i++) { actors[i] = new Event(in.nextInt(), in.nextInt(), in.nextInt(),i+1); events.add(new Event(actors[i].x,actors[i].y,-actors[i].type,i+1)); } Collections.sort(events); TreeSet<Tuple> set=new TreeSet<Tuple>(); boolean valid=true; int answers[]=new int[n]; for(Event event:events) { int x=event.x;int y=event.y; int type=event.type; int index=event.index; if(type<0)//means actor set.add(new Tuple(x,y,-type,index)); else { boolean flag=false; while(set.size()>0) { try { Tuple temp = set.tailSet(new Tuple(x, y, 0, 0)).first(); if (temp.k > 0) { set.remove(temp); temp.k--; answers[index - 1] = temp.index; if(temp.k>0) set.add(temp); flag = true; break; } else set.remove(temp); } catch(NoSuchElementException e) { valid=false; break; } } if (!flag) valid = false; } } if(!valid) out.println("NO"); else { out.println("YES"); for(int i=0;i<answers.length;i++) out.print(answers[i]+ " "); } } } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["3\n1 3\n2 4\n3 5\n2\n1 4 2\n2 5 1", "3\n1 3\n2 4\n3 5\n2\n1 3 2\n2 5 1"]
2 seconds
["YES\n1 1 2", "NO"]
null
Java 8
standard input
[ "greedy", "two pointers", "implementation", "sortings", "data structures" ]
7fdcfe1a45994e051345cb6462253ef7
The first line contains a single integer n — the number of parts in the play (1 ≤ n ≤ 105). Next n lines contain two space-separated integers each, aj and bj — the range of notes for the j-th part (1 ≤ aj ≤ bj ≤ 109). The next line contains a single integer m — the number of actors (1 ≤ m ≤ 105). Next m lines contain three space-separated integers each, ci, di and ki — the range of the i-th actor and the number of parts that he can perform (1 ≤ ci ≤ di ≤ 109, 1 ≤ ki ≤ 109).
2,100
If there is an assignment that meets all the criteria aboce, print a single word "YES" (without the quotes) in the first line. In the next line print n space-separated integers. The i-th integer should be the number of the actor who should perform the i-th part. If there are multiple correct assignments, print any of them. If there is no correct assignment, print a single word "NO" (without the quotes).
standard output
PASSED
cc16887fc4aa108b6844822fff2fbec4
train_002.jsonl
1418833800
You are an assistant director in a new musical play. The play consists of n musical parts, each part must be performed by exactly one actor. After the casting the director chose m actors who can take part in the play. Your task is to assign the parts to actors. However, there are several limitations.First, each actor has a certain voice range and there are some parts that he cannot sing. Formally, there are two integers for each actor, ci and di (ci ≤ di) — the pitch of the lowest and the highest note that the actor can sing. There also are two integers for each part — aj and bj (aj ≤ bj) — the pitch of the lowest and the highest notes that are present in the part. The i-th actor can perform the j-th part if and only if ci ≤ aj ≤ bj ≤ di, i.e. each note of the part is in the actor's voice range.According to the contract, the i-th actor can perform at most ki parts. Besides, you are allowed not to give any part to some actors (then they take part in crowd scenes).The rehearsal starts in two hours and you need to do the assignment quickly!
256 megabytes
import java.io.*; import java.util.*; public class CF { FastScanner in; PrintWriter out; class Party implements Comparable<Party> { int from, to; int id; public Party(int from, int to, int id) { super(); this.from = from; this.to = to; this.id = id; } @Override public int compareTo(Party o) { return Integer.compare(from, o.from); } } class Actor implements Comparable<Actor> { int from, to, id; int cnt; public Actor(int from, int to, int id, int cnt) { super(); this.from = from; this.to = to; this.id = id; this.cnt = cnt; } @Override public int compareTo(Actor o) { if (to == o.to) { return Integer.compare(id, o.id); } return Integer.compare(to, o.to); } } void solve() { int n = in.nextInt(); Party[] a = new Party[n]; for (int i = 0; i < n; i++) { a[i] = new Party(in.nextInt(), in.nextInt(), i); } int m = in.nextInt(); Actor[] b = new Actor[m]; for (int i = 0; i < m; i++) { b[i] = new Actor(in.nextInt(), in.nextInt(), i, in.nextInt()); } Arrays.sort(b, new Comparator<Actor>() { @Override public int compare(Actor o1, Actor o2) { return Integer.compare(o1.from, o2.from); } }); int[] ans = new int[n]; Arrays.sort(a); int it = 0; TreeSet<Actor> actors = new TreeSet<>(); for (int i = 0; i < a.length; i++) { Party p = a[i]; while (it != b.length && b[it].from <= p.from) { actors.add(b[it++]); } Actor use = actors.higher(new Actor(-1, p.to, -1, -1)); if (use == null) { out.println("NO"); return; } actors.remove(use); ans[p.id] = use.id; use.cnt--; if (use.cnt > 0) { actors.add(use); } } out.println("YES"); for (int i = 0; i < ans.length; i++) { out.print(ans[i] + 1); out.print(" "); } } void runIO() { in = new FastScanner(System.in); out = new PrintWriter(System.out); solve(); out.close(); } void run() { try { in = new FastScanner(new File("test.in")); out = new PrintWriter(new File("test.out")); solve(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } 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()); } } public static void main(String[] args) { new CF().runIO(); } }
Java
["3\n1 3\n2 4\n3 5\n2\n1 4 2\n2 5 1", "3\n1 3\n2 4\n3 5\n2\n1 3 2\n2 5 1"]
2 seconds
["YES\n1 1 2", "NO"]
null
Java 8
standard input
[ "greedy", "two pointers", "implementation", "sortings", "data structures" ]
7fdcfe1a45994e051345cb6462253ef7
The first line contains a single integer n — the number of parts in the play (1 ≤ n ≤ 105). Next n lines contain two space-separated integers each, aj and bj — the range of notes for the j-th part (1 ≤ aj ≤ bj ≤ 109). The next line contains a single integer m — the number of actors (1 ≤ m ≤ 105). Next m lines contain three space-separated integers each, ci, di and ki — the range of the i-th actor and the number of parts that he can perform (1 ≤ ci ≤ di ≤ 109, 1 ≤ ki ≤ 109).
2,100
If there is an assignment that meets all the criteria aboce, print a single word "YES" (without the quotes) in the first line. In the next line print n space-separated integers. The i-th integer should be the number of the actor who should perform the i-th part. If there are multiple correct assignments, print any of them. If there is no correct assignment, print a single word "NO" (without the quotes).
standard output
PASSED
3647862cdd7c392df7673736feeee915
train_002.jsonl
1418833800
You are an assistant director in a new musical play. The play consists of n musical parts, each part must be performed by exactly one actor. After the casting the director chose m actors who can take part in the play. Your task is to assign the parts to actors. However, there are several limitations.First, each actor has a certain voice range and there are some parts that he cannot sing. Formally, there are two integers for each actor, ci and di (ci ≤ di) — the pitch of the lowest and the highest note that the actor can sing. There also are two integers for each part — aj and bj (aj ≤ bj) — the pitch of the lowest and the highest notes that are present in the part. The i-th actor can perform the j-th part if and only if ci ≤ aj ≤ bj ≤ di, i.e. each note of the part is in the actor's voice range.According to the contract, the i-th actor can perform at most ki parts. Besides, you are allowed not to give any part to some actors (then they take part in crowd scenes).The rehearsal starts in two hours and you need to do the assignment quickly!
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.InputStreamReader; import java.util.TreeSet; import java.util.ArrayList; import java.util.StringTokenizer; import java.io.BufferedReader; import java.util.Comparator; import java.util.Collections; 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); DistributingParts solver = new DistributingParts(); solver.solve(1, in, out); out.close(); } static class DistributingParts { public void solve(int testNumber, InputReader in, PrintWriter out) { int N = in.nextInt(); ArrayList<int[]> parts = new ArrayList<>(); for (int i = 0; i < N; i++) { parts.add(new int[]{in.nextInt(), in.nextInt(), i, 1}); //0 stands for part } int M = in.nextInt(); int[][] store_parts = new int[M][4]; int[] max_parts = new int[M]; for (int i = 0; i < M; i++) { parts.add(new int[]{in.nextInt(), in.nextInt(), i, 0}); store_parts[i] = parts.get(parts.size() - 1).clone(); max_parts[i] = in.nextInt(); } Collections.sort(parts, new Comparator<int[]>() { public int compare(int[] ints, int[] t1) { if (ints[0] == t1[0]) { return Integer.compare(ints[3], t1[3]); } return Integer.compare(ints[0], t1[0]); } }); TreeSet<int[]> activeParts = new TreeSet<>(new Comparator<int[]>() { public int compare(int[] ints, int[] t1) { if (ints[1] == t1[1]) { return Integer.compare(ints[2], t1[2]); } return Integer.compare(ints[1], t1[1]); } }); int[] assign = new int[N]; for (int i = 0; i < N + M; i++) { if (parts.get(i)[3] == 0) { activeParts.add(parts.get(i).clone()); } else { int[] a = activeParts.higher(new int[]{0, parts.get(i)[1] - 1, N + M + 1, -1}); if (a == null) { out.println("NO"); return; } else { assign[parts.get(i)[2]] = a[2]; max_parts[a[2]]--; if (max_parts[a[2]] == 0) { activeParts.remove(store_parts[a[2]]); } } } } out.println("YES"); for (int j : assign) { out.println(j + 1); } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["3\n1 3\n2 4\n3 5\n2\n1 4 2\n2 5 1", "3\n1 3\n2 4\n3 5\n2\n1 3 2\n2 5 1"]
2 seconds
["YES\n1 1 2", "NO"]
null
Java 8
standard input
[ "greedy", "two pointers", "implementation", "sortings", "data structures" ]
7fdcfe1a45994e051345cb6462253ef7
The first line contains a single integer n — the number of parts in the play (1 ≤ n ≤ 105). Next n lines contain two space-separated integers each, aj and bj — the range of notes for the j-th part (1 ≤ aj ≤ bj ≤ 109). The next line contains a single integer m — the number of actors (1 ≤ m ≤ 105). Next m lines contain three space-separated integers each, ci, di and ki — the range of the i-th actor and the number of parts that he can perform (1 ≤ ci ≤ di ≤ 109, 1 ≤ ki ≤ 109).
2,100
If there is an assignment that meets all the criteria aboce, print a single word "YES" (without the quotes) in the first line. In the next line print n space-separated integers. The i-th integer should be the number of the actor who should perform the i-th part. If there are multiple correct assignments, print any of them. If there is no correct assignment, print a single word "NO" (without the quotes).
standard output
PASSED
8bf9ec705fac0f4b3548abe9ae4048d6
train_002.jsonl
1418833800
You are an assistant director in a new musical play. The play consists of n musical parts, each part must be performed by exactly one actor. After the casting the director chose m actors who can take part in the play. Your task is to assign the parts to actors. However, there are several limitations.First, each actor has a certain voice range and there are some parts that he cannot sing. Formally, there are two integers for each actor, ci and di (ci ≤ di) — the pitch of the lowest and the highest note that the actor can sing. There also are two integers for each part — aj and bj (aj ≤ bj) — the pitch of the lowest and the highest notes that are present in the part. The i-th actor can perform the j-th part if and only if ci ≤ aj ≤ bj ≤ di, i.e. each note of the part is in the actor's voice range.According to the contract, the i-th actor can perform at most ki parts. Besides, you are allowed not to give any part to some actors (then they take part in crowd scenes).The rehearsal starts in two hours and you need to do the assignment quickly!
256 megabytes
import java.util.Arrays; import java.util.TreeSet; import java.util.ArrayList; import java.io.InputStream; import java.io.InputStreamReader; import java.util.List; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Comparator; import java.util.Collections; import java.io.IOException; import java.util.StringTokenizer; /** * 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); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } } class TaskE { class Singer{ int c; int d; int k; int ind; public Singer(int c, int d, int k, int ind) { this.c = c; this.d = d; this.k = k; this.ind = ind; } } public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); Integer [][]notes = new Integer[n][3]; for (int i = 0; i < n; i++) { notes[i][0] = in.nextInt(); notes[i][1] = in.nextInt(); notes[i][2] = i; } int m = in.nextInt(); ArrayList<Singer> singers = new ArrayList<>(); for (int i = 0; i < m; i++) { int []p = in.primitiveIntArray(0,3); singers.add(new Singer(p[0],p[1],p[2],i)); } Arrays.sort(notes, new Comparator<Integer[]>() { public int compare(Integer[] o1, Integer[] o2) { return o1[0]-o2[0]; } }); Collections.sort(singers, new Comparator<Singer>() { public int compare(Singer o1, Singer o2) { return o1.c - o2.c; } }); TreeSet<Singer> treeSet = new TreeSet<Singer>(new Comparator<Singer>() { public int compare(Singer o1, Singer o2) { if (o1.d == o2.d)return o1.ind - o2.ind; return o1.d - o2.d; } }); int []res = new int[n]; int l = 0; for (int i = 0; i < n; i++) { int a1 = notes[i][0]; int a2 = notes[i][1]; int ind = notes[i][2]; while (l < m && a1 >= singers.get(l).c){ treeSet.add(singers.get(l++)); } Singer check = new Singer(a1,a2,0,-1); Singer k = treeSet.higher(check); if (k == null){ out.print("NO\n");return; } else { res[ind] = k.ind + 1; k.k--; if (k.k == 0){ treeSet.remove(k); } } } out.print("YES\n"); for (int i = 0; i < n; i++) { out.print(res[i]+" "); } } } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public int[] primitiveIntArray(int startIndex,int size){ if (startIndex == 1)size++; int []array = new int[size]; for (int i = startIndex; i < size; i++) { array[i] = Integer.parseInt(next()); } return array; } }
Java
["3\n1 3\n2 4\n3 5\n2\n1 4 2\n2 5 1", "3\n1 3\n2 4\n3 5\n2\n1 3 2\n2 5 1"]
2 seconds
["YES\n1 1 2", "NO"]
null
Java 8
standard input
[ "greedy", "two pointers", "implementation", "sortings", "data structures" ]
7fdcfe1a45994e051345cb6462253ef7
The first line contains a single integer n — the number of parts in the play (1 ≤ n ≤ 105). Next n lines contain two space-separated integers each, aj and bj — the range of notes for the j-th part (1 ≤ aj ≤ bj ≤ 109). The next line contains a single integer m — the number of actors (1 ≤ m ≤ 105). Next m lines contain three space-separated integers each, ci, di and ki — the range of the i-th actor and the number of parts that he can perform (1 ≤ ci ≤ di ≤ 109, 1 ≤ ki ≤ 109).
2,100
If there is an assignment that meets all the criteria aboce, print a single word "YES" (without the quotes) in the first line. In the next line print n space-separated integers. The i-th integer should be the number of the actor who should perform the i-th part. If there are multiple correct assignments, print any of them. If there is no correct assignment, print a single word "NO" (without the quotes).
standard output
PASSED
227424f4a439d79ef01f71a4ac5ab77d
train_002.jsonl
1418833800
You are an assistant director in a new musical play. The play consists of n musical parts, each part must be performed by exactly one actor. After the casting the director chose m actors who can take part in the play. Your task is to assign the parts to actors. However, there are several limitations.First, each actor has a certain voice range and there are some parts that he cannot sing. Formally, there are two integers for each actor, ci and di (ci ≤ di) — the pitch of the lowest and the highest note that the actor can sing. There also are two integers for each part — aj and bj (aj ≤ bj) — the pitch of the lowest and the highest notes that are present in the part. The i-th actor can perform the j-th part if and only if ci ≤ aj ≤ bj ≤ di, i.e. each note of the part is in the actor's voice range.According to the contract, the i-th actor can perform at most ki parts. Besides, you are allowed not to give any part to some actors (then they take part in crowd scenes).The rehearsal starts in two hours and you need to do the assignment quickly!
256 megabytes
import java.io.*; import java.util.*; public class R283qCDistrubtingParts { public static void main(String args[]) { InputReader in = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); boolean yes = true; int n = in.nextInt(); int ans[] = new int[n + 1]; ArrayList<Pair> list = new ArrayList<Pair>(); for(int i=1;i<=n;i++) list.add(new Pair(in.nextInt(),in.nextInt(),i,false)); int m = in.nextInt(); int k[] = new int[m + 1]; for(int i=1;i<=m;i++){ list.add(new Pair(in.nextInt(),in.nextInt(),i,true)); k[i] = in.nextInt(); } Collections.sort(list); TreeSet<Pair> set = new TreeSet<Pair>(new PairComp()); for(Pair p : list){ if(!p.type){ p.b--; Pair first = set.higher(p); if(first == null){ yes = false; break; } k[first.idx]--; if(k[first.idx] == 0) set.remove(first); ans[p.idx] = first.idx; } else set.add(p); } if(yes){ w.println("YES"); for(int i=1;i<=n;i++) w.print(ans[i] + " "); w.println(); } else w.println("NO"); w.close(); } static class Pair implements Comparable<Pair>{ int a,b,idx; boolean type; Pair(int a,int b,int idx,boolean type){ this.a = a; this.b = b; this.idx = idx; this.type = type; } public int compareTo(Pair o){ if(a != o.a) return Integer.compare(a, o.a); return Boolean.compare(o.type, type); } public String toString(){ return type + " " + idx + " " + a + " " + b; } } static class PairComp implements Comparator<Pair>{ public int compare(Pair a,Pair b){ if(a.b != b.b) return Integer.compare(a.b, b.b); if(a.type != b.type){ if(a.type == false) return 1; if(b.type == false) return -1; } return Integer.compare(a.idx, b.idx); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar; private int 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 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 boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["3\n1 3\n2 4\n3 5\n2\n1 4 2\n2 5 1", "3\n1 3\n2 4\n3 5\n2\n1 3 2\n2 5 1"]
2 seconds
["YES\n1 1 2", "NO"]
null
Java 8
standard input
[ "greedy", "two pointers", "implementation", "sortings", "data structures" ]
7fdcfe1a45994e051345cb6462253ef7
The first line contains a single integer n — the number of parts in the play (1 ≤ n ≤ 105). Next n lines contain two space-separated integers each, aj and bj — the range of notes for the j-th part (1 ≤ aj ≤ bj ≤ 109). The next line contains a single integer m — the number of actors (1 ≤ m ≤ 105). Next m lines contain three space-separated integers each, ci, di and ki — the range of the i-th actor and the number of parts that he can perform (1 ≤ ci ≤ di ≤ 109, 1 ≤ ki ≤ 109).
2,100
If there is an assignment that meets all the criteria aboce, print a single word "YES" (without the quotes) in the first line. In the next line print n space-separated integers. The i-th integer should be the number of the actor who should perform the i-th part. If there are multiple correct assignments, print any of them. If there is no correct assignment, print a single word "NO" (without the quotes).
standard output
PASSED
c2db4fafc7314c691a688c9da015df43
train_002.jsonl
1418833800
You are an assistant director in a new musical play. The play consists of n musical parts, each part must be performed by exactly one actor. After the casting the director chose m actors who can take part in the play. Your task is to assign the parts to actors. However, there are several limitations.First, each actor has a certain voice range and there are some parts that he cannot sing. Formally, there are two integers for each actor, ci and di (ci ≤ di) — the pitch of the lowest and the highest note that the actor can sing. There also are two integers for each part — aj and bj (aj ≤ bj) — the pitch of the lowest and the highest notes that are present in the part. The i-th actor can perform the j-th part if and only if ci ≤ aj ≤ bj ≤ di, i.e. each note of the part is in the actor's voice range.According to the contract, the i-th actor can perform at most ki parts. Besides, you are allowed not to give any part to some actors (then they take part in crowd scenes).The rehearsal starts in two hours and you need to do the assignment quickly!
256 megabytes
import com.sun.org.apache.xpath.internal.operations.Bool; import java.io.*; import java.util.*; import static java.lang.Math.*; public class Main extends PrintWriter { BufferedReader in; StringTokenizer stok; final Random rand = new Random(31); final int inf = (int) 1e9; final long linf = (long) 1e18; class Point implements Comparable<Point> { int x, id; boolean open; public Point(int x, int id, boolean open) { this.x = x; this.id = id; this.open = open; } @Override public int compareTo(Point o) { if (x != o.x) { return x - o.x; } if (open != o.open) { return Boolean.compare(o.open, open); } return id - o.id; } } public void solve() throws IOException { int n = nextInt(); int[] px = new int[n]; int[] py = new int[n]; Point[] p = new Point[2 * n]; for (int i = 0; i < n; i++) { px[i] = nextInt(); py[i] = nextInt(); p[2 * i] = new Point(px[i], i, true); p[2 * i + 1] = new Point(py[i], i, false); } int m = nextInt(); int[] ax = new int[m]; int[] ay = new int[m]; int[] ak = new int[m]; Point[] a = new Point[2 * m]; for (int i = 0; i < m; i++) { ax[i] = nextInt(); ay[i] = nextInt(); ak[i] = nextInt(); a[2 * i] = new Point(ax[i], i, true); a[2 * i + 1] = new Point(ay[i], i, false); } Arrays.sort(p); Arrays.sort(a); int ip = 0, ia = 0; TreeSet<Point> as = new TreeSet<>(); int[] ans = new int[n]; while (ip < p.length) { Point ca = ia < a.length ? a[ia] : null; Point cp = p[ip]; if (ca != null && (ca.x < cp.x || (ca.x == cp.x && ca.open))) { if (ca.open) { as.add(new Point(ay[ca.id], ca.id, false)); } ia++; } else { if (cp.open) { Point end = new Point(py[cp.id], -1, false); Point t = as.ceiling(end); if (t == null) { println("NO"); return; } ans[cp.id] = t.id; ak[t.id]--; if (ak[t.id] == 0) { as.remove(t); } } ip++; } } println("YES"); for (int an : ans) { print(an + 1); print(" "); } } public void run() { try { solve(); close(); } catch (Exception e) { e.printStackTrace(); System.exit(abs(-1)); } } Main() throws IOException { super(System.out); in = new BufferedReader(new InputStreamReader(System.in)); } Main(String s) throws IOException { super("".equals(s) ? "output.txt" : (s + ".out")); in = new BufferedReader(new FileReader("".equals(s) ? "input.txt" : (s + ".in"))); } public static void main(String[] args) throws IOException { try { Locale.setDefault(Locale.US); } catch (Exception ignored) { } new Main().run(); } String next() throws IOException { while (stok == null || !stok.hasMoreTokens()) { String s = in.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()); } int[] nextIntArray(int len) throws IOException { int[] a = new int[len]; for (int i = 0; i < len; i++) { a[i] = nextInt(); } return a; } void shuffle(int[] a) { for (int i = 1; i < a.length; i++) { int x = rand.nextInt(i + 1); int t = a[i]; a[i] = a[x]; a[x] = t; } } boolean nextPerm(int[] p) { for (int a = p.length - 2; a >= 0; --a) if (p[a] < p[a + 1]) for (int b = p.length - 1; ; --b) if (p[b] > p[a]) { int t = p[a]; p[a] = p[b]; p[b] = t; for (++a, b = p.length - 1; a < b; ++a, --b) { t = p[a]; p[a] = p[b]; p[b] = t; } return true; } return false; } <T> List<T>[] createAdjacencyList(int countVertex) { List<T>[] res = new List[countVertex]; for (int i = 0; i < countVertex; i++) { res[i] = new ArrayList<T>(); } return res; } }
Java
["3\n1 3\n2 4\n3 5\n2\n1 4 2\n2 5 1", "3\n1 3\n2 4\n3 5\n2\n1 3 2\n2 5 1"]
2 seconds
["YES\n1 1 2", "NO"]
null
Java 8
standard input
[ "greedy", "two pointers", "implementation", "sortings", "data structures" ]
7fdcfe1a45994e051345cb6462253ef7
The first line contains a single integer n — the number of parts in the play (1 ≤ n ≤ 105). Next n lines contain two space-separated integers each, aj and bj — the range of notes for the j-th part (1 ≤ aj ≤ bj ≤ 109). The next line contains a single integer m — the number of actors (1 ≤ m ≤ 105). Next m lines contain three space-separated integers each, ci, di and ki — the range of the i-th actor and the number of parts that he can perform (1 ≤ ci ≤ di ≤ 109, 1 ≤ ki ≤ 109).
2,100
If there is an assignment that meets all the criteria aboce, print a single word "YES" (without the quotes) in the first line. In the next line print n space-separated integers. The i-th integer should be the number of the actor who should perform the i-th part. If there are multiple correct assignments, print any of them. If there is no correct assignment, print a single word "NO" (without the quotes).
standard output
PASSED
89019757131c20e7629f676379a7891f
train_002.jsonl
1418833800
You are an assistant director in a new musical play. The play consists of n musical parts, each part must be performed by exactly one actor. After the casting the director chose m actors who can take part in the play. Your task is to assign the parts to actors. However, there are several limitations.First, each actor has a certain voice range and there are some parts that he cannot sing. Formally, there are two integers for each actor, ci and di (ci ≤ di) — the pitch of the lowest and the highest note that the actor can sing. There also are two integers for each part — aj and bj (aj ≤ bj) — the pitch of the lowest and the highest notes that are present in the part. The i-th actor can perform the j-th part if and only if ci ≤ aj ≤ bj ≤ di, i.e. each note of the part is in the actor's voice range.According to the contract, the i-th actor can perform at most ki parts. Besides, you are allowed not to give any part to some actors (then they take part in crowd scenes).The rehearsal starts in two hours and you need to do the assignment quickly!
256 megabytes
import java.util.NavigableSet; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; import java.math.BigInteger; import java.io.OutputStream; import java.util.Collections; import java.io.PrintWriter; import java.io.Writer; import java.io.IOException; import java.util.TreeSet; import java.io.InputStream; import java.io.OutputStreamWriter; import java.util.Comparator; import java.util.SortedSet; import java.util.Set; /** * Built using CHelper plug-in * Actual solution is at the top * @author Egor Kulikov (egor@egork.net) */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, InputReader in, OutputWriter out) { List<Delta> list = new ArrayList<>(); int roleCount = in.readInt(); for (int i = 0; i < roleCount; i++) { int from = in.readInt(); int to = in.readInt(); list.add(new Delta(from, to, -1, i)); } int artistCount = in.readInt(); for (int i = 0; i < artistCount; i++) { int from = in.readInt(); int to = in.readInt(); int value = in.readInt(); list.add(new Delta(from, to, value, i)); } NavigableSet<Delta> artists = new TreeSet<>(); Collections.sort(list, new Comparator<Delta>() { public int compare(Delta o1, Delta o2) { if (o1.from != o2.from) { return o1.from - o2.from; } return o2.value - o1.value; } }); int[] answer = new int[roleCount]; for (Delta delta : list) { if (delta.value > 0) { artists.add(delta); } else { NavigableSet<Delta> tail = artists.tailSet(delta, false); if (tail.isEmpty()) { out.printLine("NO"); return; } Delta artist = tail.first(); artist.value--; answer[delta.index] = artist.index + 1; if (artist.value == 0) { artists.remove(artist); } } } out.printLine("YES"); out.printLine(answer); } static class Delta implements Comparable<Delta> { int from; int to; int value; int index; public Delta(int from, int to, int value, int index) { this.from = from; this.to = to; this.value = value; this.index = index; } public int compareTo(Delta o) { if (to != o.to) { return to - o.to; } if ((value == -1) != (o.value == -1)) { if (value == -1) { return -1; } else { return 1; } } return index - o.index; } } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void print(int[] array) { for (int i = 0; i < array.length; i++) { if (i != 0) writer.print(' '); writer.print(array[i]); } } public void printLine(int[] array) { print(array); writer.println(); } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } }
Java
["3\n1 3\n2 4\n3 5\n2\n1 4 2\n2 5 1", "3\n1 3\n2 4\n3 5\n2\n1 3 2\n2 5 1"]
2 seconds
["YES\n1 1 2", "NO"]
null
Java 8
standard input
[ "greedy", "two pointers", "implementation", "sortings", "data structures" ]
7fdcfe1a45994e051345cb6462253ef7
The first line contains a single integer n — the number of parts in the play (1 ≤ n ≤ 105). Next n lines contain two space-separated integers each, aj and bj — the range of notes for the j-th part (1 ≤ aj ≤ bj ≤ 109). The next line contains a single integer m — the number of actors (1 ≤ m ≤ 105). Next m lines contain three space-separated integers each, ci, di and ki — the range of the i-th actor and the number of parts that he can perform (1 ≤ ci ≤ di ≤ 109, 1 ≤ ki ≤ 109).
2,100
If there is an assignment that meets all the criteria aboce, print a single word "YES" (without the quotes) in the first line. In the next line print n space-separated integers. The i-th integer should be the number of the actor who should perform the i-th part. If there are multiple correct assignments, print any of them. If there is no correct assignment, print a single word "NO" (without the quotes).
standard output
PASSED
f607fa9896163754aba3284afdea5085
train_002.jsonl
1418833800
You are an assistant director in a new musical play. The play consists of n musical parts, each part must be performed by exactly one actor. After the casting the director chose m actors who can take part in the play. Your task is to assign the parts to actors. However, there are several limitations.First, each actor has a certain voice range and there are some parts that he cannot sing. Formally, there are two integers for each actor, ci and di (ci ≤ di) — the pitch of the lowest and the highest note that the actor can sing. There also are two integers for each part — aj and bj (aj ≤ bj) — the pitch of the lowest and the highest notes that are present in the part. The i-th actor can perform the j-th part if and only if ci ≤ aj ≤ bj ≤ di, i.e. each note of the part is in the actor's voice range.According to the contract, the i-th actor can perform at most ki parts. Besides, you are allowed not to give any part to some actors (then they take part in crowd scenes).The rehearsal starts in two hours and you need to do the assignment quickly!
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; /** * @author Pavel Mavrin */ public class C { private void solve() throws IOException { int n = nextInt(); List<Segment> a = new ArrayList<Segment>(); for (int i = 0; i < n; i++) { a.add(new Segment(nextInt() * 2, nextInt() * 2, false, i)); } int m = nextInt(); for (int i = 0; i < m; i++) { a.add(new Segment(nextInt() * 2 - 1, nextInt() * 2 + 1, nextInt(), true, i)); } List<Position> p = new ArrayList<Position>(); for (Segment segment : a) { p.add(new Position(segment.l, segment, true)); p.add(new Position(segment.r, segment, false)); } Collections.sort(p); int c = 0; for (Position position : p) { if (position.l) { position.segment.l = c++; } else { position.segment.r = c++; } } SegmentTree segmentTree = new SegmentTree(p.size()); Collections.sort(a); int[] res = new int[n]; int cc = 0; Segment[] z = new Segment[p.size()]; for (Segment segment : a) { if (segment.a) { for (int i = 0; i < segment.k; i++) { int x = segmentTree.findAfter(segment.l); if (x > segment.r) { break; } else { int j = z[x].id; res[j] = segment.id; cc++; segmentTree.set(x, false); } } } else { segmentTree.set(segment.l, true); z[segment.l] = segment; } } if (cc == n) { out.println("YES"); for (int i = 0; i < res.length; i++) { out.print(res[i] + 1 + " "); } } else { out.println("NO"); } } class Segment implements Comparable<Segment>{ int l; int r; int k; int id; boolean a; public Segment(int l, int r, boolean a, int id) { this.l = l; this.r = r; this.a = a; this.id = id; } public Segment(int l, int r, int k, boolean a, int id) { this.l = l; this.r = r; this.k = k; this.a = a; this.id = id; } public int compareTo(Segment o) { return Integer.compare(r, o.r); } } class Position implements Comparable<Position>{ int x; boolean l; Segment segment; public Position(int x, Segment segment, boolean l) { this.x = x; this.l = l; this.segment = segment; } public int compareTo(Position o) { return Integer.compare(x, o.x); } } class SegmentTree { private int[] a; private int size; public SegmentTree(int n) { int size = 1; while (size < n) size *= 2; this.size = size; a = new int[2 * size]; Arrays.fill(a, -1); } private void set(int i, boolean v) { set(0, 0, size, i, v); } private void set(int n, int l, int r, int i, boolean v) { if (r == l + 1) { a[n] = v ? l : -1; } else { int m = (l + r) / 2; if (i < m) { set(n * 2 + 1, l, m, i, v); } else { set(n * 2 + 2, m, r, i, v); } a[n] = Math.max(a[n * 2 + 1], a[n * 2 + 2]); } } private int get(int i) { return get(0, 0, size, i); } private int get(int n, int l, int r, int i) { if (r == l + 1) { return a[n]; } else { int m = (l + r) / 2; if (i < m) { return get(n * 2 + 1, l, m, i); } else { return get(n * 2 + 2, m, r, i); } } } public int findAfter(int x) { return findAfter(0, 0, size, x); } private int findAfter(int n, int l, int r, int x) { if (a[n] < 0) return size; if (r == l + 1) return a[n]; if (a[n * 2 + 1] >= x) { return findAfter(2 * n + 1, l, (l + r) / 2, x); } else { return findAfter(2 * n + 2, (l + r) / 2, r, x); } } } BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; PrintWriter out = new PrintWriter(System.out); String next() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } public static void main(String[] args) throws IOException { new C().run(); } private void run() throws IOException { solve(); out.close(); } }
Java
["3\n1 3\n2 4\n3 5\n2\n1 4 2\n2 5 1", "3\n1 3\n2 4\n3 5\n2\n1 3 2\n2 5 1"]
2 seconds
["YES\n1 1 2", "NO"]
null
Java 8
standard input
[ "greedy", "two pointers", "implementation", "sortings", "data structures" ]
7fdcfe1a45994e051345cb6462253ef7
The first line contains a single integer n — the number of parts in the play (1 ≤ n ≤ 105). Next n lines contain two space-separated integers each, aj and bj — the range of notes for the j-th part (1 ≤ aj ≤ bj ≤ 109). The next line contains a single integer m — the number of actors (1 ≤ m ≤ 105). Next m lines contain three space-separated integers each, ci, di and ki — the range of the i-th actor and the number of parts that he can perform (1 ≤ ci ≤ di ≤ 109, 1 ≤ ki ≤ 109).
2,100
If there is an assignment that meets all the criteria aboce, print a single word "YES" (without the quotes) in the first line. In the next line print n space-separated integers. The i-th integer should be the number of the actor who should perform the i-th part. If there are multiple correct assignments, print any of them. If there is no correct assignment, print a single word "NO" (without the quotes).
standard output
PASSED
05aa161e2965d24fe3d45c847b548839
train_002.jsonl
1418833800
You are an assistant director in a new musical play. The play consists of n musical parts, each part must be performed by exactly one actor. After the casting the director chose m actors who can take part in the play. Your task is to assign the parts to actors. However, there are several limitations.First, each actor has a certain voice range and there are some parts that he cannot sing. Formally, there are two integers for each actor, ci and di (ci ≤ di) — the pitch of the lowest and the highest note that the actor can sing. There also are two integers for each part — aj and bj (aj ≤ bj) — the pitch of the lowest and the highest notes that are present in the part. The i-th actor can perform the j-th part if and only if ci ≤ aj ≤ bj ≤ di, i.e. each note of the part is in the actor's voice range.According to the contract, the i-th actor can perform at most ki parts. Besides, you are allowed not to give any part to some actors (then they take part in crowd scenes).The rehearsal starts in two hours and you need to do the assignment quickly!
256 megabytes
import java.util.Arrays; import java.util.TreeSet; import java.io.InputStream; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Comparator; import java.io.IOException; import java.util.StringTokenizer; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { private class part implements Comparable<part> { int l, r, id; public part(int l, int r, int id) { this.l = l; this.r = r; this.id = id; } private int Id(int a, int b) { return (a == b ? 0 : (a < b ? -1 : 1)); } public int compareTo(part o) { return (l != o.l ? Id(l, o.l) : Id(r, o.r)); } } private class actor implements Comparable<actor> { int l, r, cnt, id; public actor(int l, int r, int cnt, int id) { this.l = l; this.r = r; this.cnt = cnt; this.id = id; } private int Id(int a, int b) { return (a == b ? 0 : (a < b ? -1 : 1)); } public int compareTo(actor o) { return (r != o.r ? Id(r, o.r) : (l != o.l ? Id(l, o.l) : Id(id, o.id))); } } private int n, m; private part[] a; private actor[] b; private TreeSet<actor> heap; private int[] res; public void solve(int testNumber, InputReader in, PrintWriter out) { n = in.nextInt(); a = new part[n]; res = new int[n]; for (int i = 0; i < n; ++i) a[i] = new part(in.nextInt(), in.nextInt(), i); m = in.nextInt(); b = new actor[m]; for (int i = 0; i < m; ++i) b[i] = new actor(in.nextInt(), in.nextInt(), in.nextInt(), i); heap = new TreeSet<>(); Arrays.sort(a); Arrays.sort(b, new Comparator<actor>() { public int compare(actor o1, actor o2) { return (o1.l != o2.l ? o1.l - o2.l : (o1.r != o2.r ? o1.r - o2.r : o1.id - o2.id)); } }); for(int i = 0, j = 0; i < n; ++i) { for(; j < m && b[j].l <= a[i].l; ++j) heap.add(b[j]); actor ac = heap.higher(new actor(-1, a[i].r, -1, -1)); if (ac == null) { out.println("NO"); return; } res[a[i].id] = ac.id + 1; --ac.cnt; if (ac.cnt == 0) heap.remove(ac); } out.println("YES"); for(int i = 0; i < n; ++i) out.print(res[i] + " "); } } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() { try { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } catch (Exception e) { throw new UnknownError(e.getMessage()); } } public int nextInt() { return Integer.parseInt(next()); } }
Java
["3\n1 3\n2 4\n3 5\n2\n1 4 2\n2 5 1", "3\n1 3\n2 4\n3 5\n2\n1 3 2\n2 5 1"]
2 seconds
["YES\n1 1 2", "NO"]
null
Java 8
standard input
[ "greedy", "two pointers", "implementation", "sortings", "data structures" ]
7fdcfe1a45994e051345cb6462253ef7
The first line contains a single integer n — the number of parts in the play (1 ≤ n ≤ 105). Next n lines contain two space-separated integers each, aj and bj — the range of notes for the j-th part (1 ≤ aj ≤ bj ≤ 109). The next line contains a single integer m — the number of actors (1 ≤ m ≤ 105). Next m lines contain three space-separated integers each, ci, di and ki — the range of the i-th actor and the number of parts that he can perform (1 ≤ ci ≤ di ≤ 109, 1 ≤ ki ≤ 109).
2,100
If there is an assignment that meets all the criteria aboce, print a single word "YES" (without the quotes) in the first line. In the next line print n space-separated integers. The i-th integer should be the number of the actor who should perform the i-th part. If there are multiple correct assignments, print any of them. If there is no correct assignment, print a single word "NO" (without the quotes).
standard output
PASSED
d086a24b4b80294a8cfcced4e97b508e
train_002.jsonl
1418833800
You are an assistant director in a new musical play. The play consists of n musical parts, each part must be performed by exactly one actor. After the casting the director chose m actors who can take part in the play. Your task is to assign the parts to actors. However, there are several limitations.First, each actor has a certain voice range and there are some parts that he cannot sing. Formally, there are two integers for each actor, ci and di (ci ≤ di) — the pitch of the lowest and the highest note that the actor can sing. There also are two integers for each part — aj and bj (aj ≤ bj) — the pitch of the lowest and the highest notes that are present in the part. The i-th actor can perform the j-th part if and only if ci ≤ aj ≤ bj ≤ di, i.e. each note of the part is in the actor's voice range.According to the contract, the i-th actor can perform at most ki parts. Besides, you are allowed not to give any part to some actors (then they take part in crowd scenes).The rehearsal starts in two hours and you need to do the assignment quickly!
256 megabytes
import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; import java.util.TreeSet; public class C { public static void main(String[] args) throws IOException { init(); int n = nextInt(); ArrayList<Point> points = new ArrayList<>(); for (int i = 0; i < n; i++) points.add(new Point(nextInt(), nextInt(), -1, i + 1)); int m = nextInt(); for (int i = 0; i < m; i++) points.add(new Point(nextInt(), nextInt(), nextInt(), i + 1)); points.sort(Point::reverseCompare); // System.out.println(points); TreeSet<Point> pointTreeSet = new TreeSet<>(); int[] assignments = new int[n]; boolean isPossible = true; for (Point point: points) { if (point.isPart()) { Point assigned = pointTreeSet.ceiling(point); // System.out.println("Curr tree set: " + pointTreeSet + "; " + point + " : " + assigned); if (assigned == null) { isPossible = false; break; } assignments[point.number - 1] = assigned.number; assigned.k -= 1; // System.out.println("Assigned k: " + assigned.k); if (assigned.k == 0) pointTreeSet.remove(assigned); } else { pointTreeSet.add(point); } } if (isPossible) { System.out.println("YES"); System.out.println(Arrays.toString(assignments).replace("[", "").replace("]", "").replace(", ", " ")); } else System.out.println("NO"); } private static class Point implements Comparable<Point> { int x, y, k, number; Point(int x, int y, int k, int number) { this.x = x; this.y = y; this.k = k; this.number = number; } boolean isPart() { return k == -1; } int compareEqual(Point one, Point two) { if (one.isPart() && !two.isPart()) return -1; else if (!one.isPart() && two.isPart()) return 1; else return one.number - two.number; } @Override public int compareTo(Point other) { return this.y == other.y ? other.x == this.x ? compareEqual(this, other) : other.x - this.x : this.y - other.y; } int reverseCompare(Point other) { return this.x == other.x ? other.y == this.y ? other.k - this.k : other.y - this.y : this.x - other.x; } @Override public String toString() { return this.x + " " + this.y + " " + this.k; } } //Input Reader private static BufferedReader reader; private static StringTokenizer tokenizer; private static void init() { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = new StringTokenizer(""); } private static String next() throws IOException { String read; while (!tokenizer.hasMoreTokens()) { read = reader.readLine(); if (read == null || read.equals("")) return "-1"; tokenizer = new StringTokenizer(read); } return tokenizer.nextToken(); } private static int nextInt() throws IOException { return Integer.parseInt(next()); } }
Java
["3\n1 3\n2 4\n3 5\n2\n1 4 2\n2 5 1", "3\n1 3\n2 4\n3 5\n2\n1 3 2\n2 5 1"]
2 seconds
["YES\n1 1 2", "NO"]
null
Java 8
standard input
[ "greedy", "two pointers", "implementation", "sortings", "data structures" ]
7fdcfe1a45994e051345cb6462253ef7
The first line contains a single integer n — the number of parts in the play (1 ≤ n ≤ 105). Next n lines contain two space-separated integers each, aj and bj — the range of notes for the j-th part (1 ≤ aj ≤ bj ≤ 109). The next line contains a single integer m — the number of actors (1 ≤ m ≤ 105). Next m lines contain three space-separated integers each, ci, di and ki — the range of the i-th actor and the number of parts that he can perform (1 ≤ ci ≤ di ≤ 109, 1 ≤ ki ≤ 109).
2,100
If there is an assignment that meets all the criteria aboce, print a single word "YES" (without the quotes) in the first line. In the next line print n space-separated integers. The i-th integer should be the number of the actor who should perform the i-th part. If there are multiple correct assignments, print any of them. If there is no correct assignment, print a single word "NO" (without the quotes).
standard output
PASSED
8e6c7467d611ce404b55936f5b700a64
train_002.jsonl
1418833800
You are an assistant director in a new musical play. The play consists of n musical parts, each part must be performed by exactly one actor. After the casting the director chose m actors who can take part in the play. Your task is to assign the parts to actors. However, there are several limitations.First, each actor has a certain voice range and there are some parts that he cannot sing. Formally, there are two integers for each actor, ci and di (ci ≤ di) — the pitch of the lowest and the highest note that the actor can sing. There also are two integers for each part — aj and bj (aj ≤ bj) — the pitch of the lowest and the highest notes that are present in the part. The i-th actor can perform the j-th part if and only if ci ≤ aj ≤ bj ≤ di, i.e. each note of the part is in the actor's voice range.According to the contract, the i-th actor can perform at most ki parts. Besides, you are allowed not to give any part to some actors (then they take part in crowd scenes).The rehearsal starts in two hours and you need to do the assignment quickly!
256 megabytes
import java.util.*; import java.text.*; import java.io.*; import java.math.*; import java.awt.geom.*; public class Cf496E { public static void main(String[] args) { Distributing_Parts tmp=new Distributing_Parts(); tmp.solve(); } } class Distributing_Parts { static class Singer { int l,r; int cont,id; Singer(){} Singer(int l,int r,int cont,int id) { this.l=l; this.r=r; this.cont=cont; this.id=id; } } static class Music { int l,r; int id; Music(){} Music(int l,int r,int id) { this.l=l; this.r=r; this.id=id; } } int num_s,num_m; Singer[] si; Music[] mu; int[] who; void input() { InputReader in=new InputReader(System.in); num_m=in.nextInt(); mu=new Music[num_m]; for(int i=0;i<num_m;i++) { int l=in.nextInt(); int r=in.nextInt(); mu[i]=new Music(l,r,i); } who=new int[num_m]; num_s=in.nextInt(); si=new Singer[num_s]; for(int i=0;i<num_s;i++) { int l=in.nextInt(); int r=in.nextInt(); int cont=in.nextInt(); si[i]=new Singer(l,r,cont,i+1); } Arrays.sort(mu,new Comparator<Music>() { public int compare(Music x,Music y) { return x.l-y.l; } }); Arrays.sort(si,new Comparator<Singer>() { public int compare(Singer x,Singer y) { return x.l-y.l; } }); } void solve() { input(); PrintWriter out=new PrintWriter(System.out); TreeSet<Singer> set=new TreeSet<Singer>(new Comparator<Singer>(){ public int compare(Singer x,Singer y) { int dis=x.r-y.r; if(dis==0) dis=x.id-y.id; return dis; } }); int index=0; for(Music u:mu) { while(index<num_s&&si[index].l<=u.l) { set.add(si[index++]); } Singer tmp=new Singer(-1,u.r,0,0); Singer s=set.higher(tmp); if(s==null) { out.println("NO"); out.close(); return; }else { //out.println(s.id+" "+s.l+" "+s.r+" "+u.l+" "+u.r); who[u.id]=s.id; s.cont--; if(s.cont<=0) { set.remove(s); } } } out.println("YES"); for(int i=0;i<num_m;i++) { if(i>0) out.print(" "); out.print(who[i]); } out.println(); out.close(); } } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader=new BufferedReader(new InputStreamReader(stream)); tokenizer=null; } public String next() { while(tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); }catch(IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { return Long.parseLong(next()); } public BigInteger nextBigInteger() { return new BigInteger(next()); } }
Java
["3\n1 3\n2 4\n3 5\n2\n1 4 2\n2 5 1", "3\n1 3\n2 4\n3 5\n2\n1 3 2\n2 5 1"]
2 seconds
["YES\n1 1 2", "NO"]
null
Java 8
standard input
[ "greedy", "two pointers", "implementation", "sortings", "data structures" ]
7fdcfe1a45994e051345cb6462253ef7
The first line contains a single integer n — the number of parts in the play (1 ≤ n ≤ 105). Next n lines contain two space-separated integers each, aj and bj — the range of notes for the j-th part (1 ≤ aj ≤ bj ≤ 109). The next line contains a single integer m — the number of actors (1 ≤ m ≤ 105). Next m lines contain three space-separated integers each, ci, di and ki — the range of the i-th actor and the number of parts that he can perform (1 ≤ ci ≤ di ≤ 109, 1 ≤ ki ≤ 109).
2,100
If there is an assignment that meets all the criteria aboce, print a single word "YES" (without the quotes) in the first line. In the next line print n space-separated integers. The i-th integer should be the number of the actor who should perform the i-th part. If there are multiple correct assignments, print any of them. If there is no correct assignment, print a single word "NO" (without the quotes).
standard output
PASSED
ec13f6c5a14264f3ce0cb104546eedec
train_002.jsonl
1418833800
You are an assistant director in a new musical play. The play consists of n musical parts, each part must be performed by exactly one actor. After the casting the director chose m actors who can take part in the play. Your task is to assign the parts to actors. However, there are several limitations.First, each actor has a certain voice range and there are some parts that he cannot sing. Formally, there are two integers for each actor, ci and di (ci ≤ di) — the pitch of the lowest and the highest note that the actor can sing. There also are two integers for each part — aj and bj (aj ≤ bj) — the pitch of the lowest and the highest notes that are present in the part. The i-th actor can perform the j-th part if and only if ci ≤ aj ≤ bj ≤ di, i.e. each note of the part is in the actor's voice range.According to the contract, the i-th actor can perform at most ki parts. Besides, you are allowed not to give any part to some actors (then they take part in crowd scenes).The rehearsal starts in two hours and you need to do the assignment quickly!
256 megabytes
import java.io.*; import java.util.*; public class C { FastScanner in; PrintWriter out; class Segment implements Comparable<Segment> { int l, r, k; int id; public Segment(int l, int r, int k, int id) { super(); this.l = l; this.r = r; this.k = k; this.id = id; } @Override public int compareTo(Segment o) { if (l != o.l) { return Integer.compare(l, o.l); } return -Integer.compare(r, o.r); } } void solve() { int n = in.nextInt(); Segment[] a = new Segment[n]; for (int i = 0; i < n; i++) { a[i] = new Segment(in.nextInt() - 1, in.nextInt() - 1, 0, i); } int m = in.nextInt(); Segment[] b = new Segment[m]; for (int i = 0; i < m; i++) { b[i] = new Segment(in.nextInt() - 1, in.nextInt() - 1, in.nextInt(), i); } int[] match = new int[n]; Arrays.fill(match, -1); Arrays.sort(a); Arrays.sort(b); TreeSet<Segment> tset = new TreeSet<>(new Comparator<Segment>() { @Override public int compare(Segment o1, Segment o2) { if (o1.r != o2.r) { return Integer.compare(o1.r, o2.r); } return Integer.compare(o1.id, o2.id); } }); Segment tmp = new Segment(0, 0, 0, -1); int ptr = 0; for (Segment seg : a) { while (ptr < m && b[ptr].l <= seg.l) { tset.add(b[ptr++]); } tmp.r = seg.r; Segment cur = tset.ceiling(tmp); if (cur == null) { out.println("NO"); return; } tset.remove(cur); cur.k--; match[seg.id] = cur.id; if (cur.k > 0) { tset.add(cur); } } out.println("YES"); for (int i = 0; i < n; i++) { out.print((match[i] + 1) + " "); } } void run() { in = new FastScanner(); out = new PrintWriter(System.out); solve(); out.close(); } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { e.printStackTrace(); } } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } public static void main(String[] args) { new C().run(); } }
Java
["3\n1 3\n2 4\n3 5\n2\n1 4 2\n2 5 1", "3\n1 3\n2 4\n3 5\n2\n1 3 2\n2 5 1"]
2 seconds
["YES\n1 1 2", "NO"]
null
Java 8
standard input
[ "greedy", "two pointers", "implementation", "sortings", "data structures" ]
7fdcfe1a45994e051345cb6462253ef7
The first line contains a single integer n — the number of parts in the play (1 ≤ n ≤ 105). Next n lines contain two space-separated integers each, aj and bj — the range of notes for the j-th part (1 ≤ aj ≤ bj ≤ 109). The next line contains a single integer m — the number of actors (1 ≤ m ≤ 105). Next m lines contain three space-separated integers each, ci, di and ki — the range of the i-th actor and the number of parts that he can perform (1 ≤ ci ≤ di ≤ 109, 1 ≤ ki ≤ 109).
2,100
If there is an assignment that meets all the criteria aboce, print a single word "YES" (without the quotes) in the first line. In the next line print n space-separated integers. The i-th integer should be the number of the actor who should perform the i-th part. If there are multiple correct assignments, print any of them. If there is no correct assignment, print a single word "NO" (without the quotes).
standard output
PASSED
02a0641d4724455fd2e226a53eb0d69d
train_002.jsonl
1418833800
You are an assistant director in a new musical play. The play consists of n musical parts, each part must be performed by exactly one actor. After the casting the director chose m actors who can take part in the play. Your task is to assign the parts to actors. However, there are several limitations.First, each actor has a certain voice range and there are some parts that he cannot sing. Formally, there are two integers for each actor, ci and di (ci ≤ di) — the pitch of the lowest and the highest note that the actor can sing. There also are two integers for each part — aj and bj (aj ≤ bj) — the pitch of the lowest and the highest notes that are present in the part. The i-th actor can perform the j-th part if and only if ci ≤ aj ≤ bj ≤ di, i.e. each note of the part is in the actor's voice range.According to the contract, the i-th actor can perform at most ki parts. Besides, you are allowed not to give any part to some actors (then they take part in crowd scenes).The rehearsal starts in two hours and you need to do the assignment quickly!
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.util.Arrays; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.TreeSet; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Rubanenko */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { class Segment implements Comparable<Segment> { int l, r, num; public Segment(int l, int r, int num) { this.l = l; this.r = r; this.num = num; } public int compareTo(Segment rhs) { return r < rhs.r ? -1 : r == rhs.r && l < rhs.l ? -1 : r == rhs.r && l == rhs.l && num < rhs.num ? -1 : r == rhs.r && l == rhs.l && num == rhs.num ? 0 : 1; } } class Event implements Comparable<Event> { int x, num; boolean isRole, isOpening; public Event(int x, int num, boolean isRole, boolean isOpening) { this.x = x; this.num = num; this.isRole = isRole; this.isOpening = isOpening; } public int compareTo(Event rhs) { if (x < rhs.x) return -1; if (x > rhs.x) return 1; if (isOpening && !rhs.isOpening) return -1; if (!isOpening && rhs.isOpening) return 1; if (!isRole && rhs.isRole) return -1; if (isRole == rhs.isRole) return 0; return 1; // return 1 : x == rhs.x && isOpening == rhs.isOpening && isOpening && (isRole == false && rhs.isRole) ? -1 : 1; } } public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); Segment[] roles = new Segment[n + 1]; for (int i = 1; i <= n; i++) { roles[i] = new Segment(in.nextInt(), in.nextInt(), i); } int m = in.nextInt(); Segment[] actors = new Segment[m + 1]; for (int i = 1; i <= m; i++) { actors[i] = new Segment(in.nextInt(), in.nextInt(), in.nextInt()); } Event[] events = new Event[(n + m) * 2 + 1]; int k = 0; for (int i = 1; i <= n; i++) { k++; events[k] = new Event(roles[i].l, roles[i].num, true, true); k++; events[k] = new Event(roles[i].r, roles[i].num, true, false); } for (int i = 1; i <= m; i++) { k++; events[k] = new Event(actors[i].l, i, false, true); k++; events[k] = new Event(actors[i].r, i, false, false); } Arrays.sort(events, 1, k + 1); TreeSet<Segment> s = new TreeSet<>(); int[] ans = new int[n + 1]; int[] songsLeft = new int[m + 1]; for (int i = 1; i <= m; i++) { songsLeft[i] = actors[i].num; } for (int i = 1; i <= k; i++) { // out.println(i + " " + events[i].x + " " + events[i].isRole + " " + events[i].isOpening + " " + events[i].num); if (events[i].isRole) { if (events[i].isOpening) { if (s.isEmpty()) { out.println("NO"); return; } Segment tmp = s.ceiling(new Segment(-1, roles[events[i].num].r, 0)); // out.println(tmp.l + " " + tmp.r + " " + tmp.num); if (tmp == null) { out.println("NO"); return; } int num = tmp.num; ans[events[i].num] = num; songsLeft[num]--; if (songsLeft[num] == 0) { s.remove(tmp); } } continue; } if (events[i].isOpening) { s.add(new Segment(actors[events[i].num].l, actors[events[i].num].r, events[i].num)); } else { Segment tmp = new Segment(actors[events[i].num].l, actors[events[i].num].r, events[i].num); if (s.contains(tmp)) { s.remove(tmp); } } } out.println("YES"); for (int i = 1; i <= n; i++) { out.print(ans[i]); if (i == n) { out.println(); } else { out.print(' '); } } } } class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream inputStream) { reader = new BufferedReader(new InputStreamReader(inputStream)); } public String nextLine() { String line = null; try { line = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return line; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(nextLine()); return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["3\n1 3\n2 4\n3 5\n2\n1 4 2\n2 5 1", "3\n1 3\n2 4\n3 5\n2\n1 3 2\n2 5 1"]
2 seconds
["YES\n1 1 2", "NO"]
null
Java 8
standard input
[ "greedy", "two pointers", "implementation", "sortings", "data structures" ]
7fdcfe1a45994e051345cb6462253ef7
The first line contains a single integer n — the number of parts in the play (1 ≤ n ≤ 105). Next n lines contain two space-separated integers each, aj and bj — the range of notes for the j-th part (1 ≤ aj ≤ bj ≤ 109). The next line contains a single integer m — the number of actors (1 ≤ m ≤ 105). Next m lines contain three space-separated integers each, ci, di and ki — the range of the i-th actor and the number of parts that he can perform (1 ≤ ci ≤ di ≤ 109, 1 ≤ ki ≤ 109).
2,100
If there is an assignment that meets all the criteria aboce, print a single word "YES" (without the quotes) in the first line. In the next line print n space-separated integers. The i-th integer should be the number of the actor who should perform the i-th part. If there are multiple correct assignments, print any of them. If there is no correct assignment, print a single word "NO" (without the quotes).
standard output
PASSED
68b3c46f894f41863f26bf3da59ac739
train_002.jsonl
1418833800
You are an assistant director in a new musical play. The play consists of n musical parts, each part must be performed by exactly one actor. After the casting the director chose m actors who can take part in the play. Your task is to assign the parts to actors. However, there are several limitations.First, each actor has a certain voice range and there are some parts that he cannot sing. Formally, there are two integers for each actor, ci and di (ci ≤ di) — the pitch of the lowest and the highest note that the actor can sing. There also are two integers for each part — aj and bj (aj ≤ bj) — the pitch of the lowest and the highest notes that are present in the part. The i-th actor can perform the j-th part if and only if ci ≤ aj ≤ bj ≤ di, i.e. each note of the part is in the actor's voice range.According to the contract, the i-th actor can perform at most ki parts. Besides, you are allowed not to give any part to some actors (then they take part in crowd scenes).The rehearsal starts in two hours and you need to do the assignment quickly!
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Arrays; import java.util.Comparator; import java.util.StringTokenizer; import java.util.TreeSet; public class Main { public static void main(String[] args) throws IOException{ InputStream inputStream = System.in; OutputStream outputStream = System.out; //InputStream inputStream = new FileInputStream("input.txt"); //OutputStream outputStream = new FileOutputStream("output.txt"); InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskE solver = new TaskE(); solver.solve(in, out); out.close(); } } class TaskE { public void solve(InputReader in, OutputWriter out) { int n = in.nextInt(); Struct[] a = new Struct[n]; for(int i=0; i<n; i++){ int l = in.nextInt(); int r = in.nextInt(); a[i] = new Struct(2,l,r,0,i); } int m = in.nextInt(); Struct[] b = new Struct[m]; for(int i=0; i<m; i++){ int l = in.nextInt(); int r = in.nextInt(); int k = in.nextInt(); b[i] = new Struct(1,l,r,k,i); } Struct[] c = new Struct[n+m]; for(int i=0; i<n; i++) c[i] = a[i]; for(int i=0; i<m; i++) c[i+n] = b[i]; Arrays.sort(c, new CompByLeft()); TreeSet<Struct> set = new TreeSet<Struct>(new CompByRight()); int[] ans = new int[n]; for(int i=0; i<n+m; i++){ if(c[i].type==1){ set.add(c[i]); }else{ Struct s = set.ceiling(new Struct(1,0,c[i].r,0,0)); if(s==null){ out.writeln("NO"); return; }else{ ans[c[i].ind]=s.ind; set.remove(s); if(s.k>1) set.add(new Struct(s.type,s.l,s.r,s.k-1,s.ind)); } } } out.writeln("YES"); for(int i=0; i<n; i++) out.write((ans[i]+1)+" "); } } class CompByLeft implements Comparator<Struct>{ public int compare(Struct s1, Struct s2){ if(s1.l==s2.l) return s1.type-s2.type; else return s1.l-s2.l; } } class CompByRight implements Comparator<Struct>{ public int compare(Struct s1, Struct s2){ return s1.r==s2.r ? s1.ind-s2.ind : s1.r-s2.r; } } class Struct{ public Struct(int type, int l, int r, int k, int ind){ this.type = type; this.l = l; this.r = r; this.k = k; this.ind = ind; } int l,r,k,type,ind; } class InputReader{ BufferedReader reader; StringTokenizer tokenizer; public InputReader(InputStream stream){ tokenizer = null; reader = new BufferedReader(new InputStreamReader(stream)); } public String next(){ while(tokenizer==null || !tokenizer.hasMoreTokens()){ try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(); } } return tokenizer.nextToken(); } public String nextLine(){ tokenizer = null; try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(); } } public int nextInt(){ return Integer.parseInt(next()); } public long nextLong(){ return Long.parseLong(next()); } public int[] nextIntArray(int n){ int[] res = new int[n]; for(int i=0; i<n; i++) res[i] = nextInt(); return res; } } class OutputWriter{ PrintWriter out; public OutputWriter(OutputStream stream){ out = new PrintWriter(new BufferedWriter( new OutputStreamWriter(stream))); } public void write(Object ...o){ for(Object cur : o) out.print(cur); } public void writeln(Object ...o){ write(o); out.println(); } public void flush(){ out.flush(); } public void close(){ out.close(); } }
Java
["3\n1 3\n2 4\n3 5\n2\n1 4 2\n2 5 1", "3\n1 3\n2 4\n3 5\n2\n1 3 2\n2 5 1"]
2 seconds
["YES\n1 1 2", "NO"]
null
Java 8
standard input
[ "greedy", "two pointers", "implementation", "sortings", "data structures" ]
7fdcfe1a45994e051345cb6462253ef7
The first line contains a single integer n — the number of parts in the play (1 ≤ n ≤ 105). Next n lines contain two space-separated integers each, aj and bj — the range of notes for the j-th part (1 ≤ aj ≤ bj ≤ 109). The next line contains a single integer m — the number of actors (1 ≤ m ≤ 105). Next m lines contain three space-separated integers each, ci, di and ki — the range of the i-th actor and the number of parts that he can perform (1 ≤ ci ≤ di ≤ 109, 1 ≤ ki ≤ 109).
2,100
If there is an assignment that meets all the criteria aboce, print a single word "YES" (without the quotes) in the first line. In the next line print n space-separated integers. The i-th integer should be the number of the actor who should perform the i-th part. If there are multiple correct assignments, print any of them. If there is no correct assignment, print a single word "NO" (without the quotes).
standard output
PASSED
b935311b6b829958b7a2ab003d179dd2
train_002.jsonl
1418833800
You are an assistant director in a new musical play. The play consists of n musical parts, each part must be performed by exactly one actor. After the casting the director chose m actors who can take part in the play. Your task is to assign the parts to actors. However, there are several limitations.First, each actor has a certain voice range and there are some parts that he cannot sing. Formally, there are two integers for each actor, ci and di (ci ≤ di) — the pitch of the lowest and the highest note that the actor can sing. There also are two integers for each part — aj and bj (aj ≤ bj) — the pitch of the lowest and the highest notes that are present in the part. The i-th actor can perform the j-th part if and only if ci ≤ aj ≤ bj ≤ di, i.e. each note of the part is in the actor's voice range.According to the contract, the i-th actor can perform at most ki parts. Besides, you are allowed not to give any part to some actors (then they take part in crowd scenes).The rehearsal starts in two hours and you need to do the assignment quickly!
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; /** * Created by dhamada on 15/05/17. */ public class C { public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); Part[] parts = new Part[n]; for (int i = 0 ; i < n ; i++) { parts[i] = new Part(in.nextInt(), in.nextInt(), i); } int m = in.nextInt(); Actor[] actors = new Actor[m]; for (int i = 0; i < m ; i++) { actors[i] = new Actor(in.nextInt(), in.nextInt(), in.nextInt(), i); } List<Event> events = new ArrayList<>(); for (int i = 0 ; i < n ; i++) { events.add(Event.buildEventPartQuery(parts[i])); } for (int i = 0 ; i < m ; i++) { events.add(Event.buildEventActorEnter(actors[i])); events.add(Event.buildEventActorLeave(actors[i])); } Collections.sort(events); TreeSet<Actor> availableActors = new TreeSet<>(); int[] ans = new int[n]; boolean found = true; for (Event e : events) { long type = e.at & 3; if (type == 0) { availableActors.add(e.actor); } else if (type == 1) { Part part = e.part; Actor bestActor = availableActors.higher(Actor.pseudoActor(part.to)); if (bestActor == null) { found = false; break; } ans[part.idx] = bestActor.idx+1; bestActor.cnt--; if (bestActor.cnt == 0) { availableActors.remove(bestActor); } } else { availableActors.remove(e.actor); } } if (found) { out.println("YES"); StringBuilder b = new StringBuilder(); for (int a : ans) { b.append(' ').append(a); } out.println(b.substring(1)); } else { out.println("NO"); } out.flush(); } static class Event implements Comparable<Event> { long at; Part part; Actor actor; public static Event buildEventActorEnter(Actor actor) { Event e = new Event(); e.actor = actor; e.at = ((1L *actor.fr) << 2) + 0; return e; } public static Event buildEventPartQuery(Part part) { Event e = new Event(); e.part = part; e.at = ((1L * part.fr) << 2) + 1; return e; } public static Event buildEventActorLeave(Actor actor) { Event e = new Event(); e.actor = actor; e.at = ((1L * actor.to) << 2) + 2; return e; } @Override public int compareTo(Event o) { return Long.compare(at, o.at); } } static class Part { int fr; int to; int idx; public Part(int f, int t, int i) { fr = f; to = t; idx = i; } } static class Actor implements Comparable<Actor> { int fr; int to; int cnt; int idx; public static Actor pseudoActor(int to) { return new Actor(0, to, 1, -1); } public Actor(int f, int t, int c, int i) { fr = f; to = t; cnt = c; idx = i; } @Override public int compareTo(Actor o) { if (to == o.to) { return idx - o.idx; } return to - o.to; } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } private int next() { 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 char nextChar() { int c = next(); while (isSpaceChar(c)) c = next(); if ('a' <= c && c <= 'z') { return (char)c; } if ('A' <= c && c <= 'Z') { return (char)c; } throw new InputMismatchException(); } public String nextToken() { int c = next(); while (isSpaceChar(c)) c = next(); StringBuilder res = new StringBuilder(); do { res.append((char)c); c = next(); } while (!isSpaceChar(c)); return res.toString(); } public int nextInt() { int c = next(); while (isSpaceChar(c)) c = next(); int sgn = 1; if (c == '-') { sgn = -1; c = next(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = next(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = next(); while (isSpaceChar(c)) c = next(); long sgn = 1; if (c == '-') { sgn = -1; c = next(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = next(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static void debug(Object... o) { System.err.println(Arrays.deepToString(o)); } }
Java
["3\n1 3\n2 4\n3 5\n2\n1 4 2\n2 5 1", "3\n1 3\n2 4\n3 5\n2\n1 3 2\n2 5 1"]
2 seconds
["YES\n1 1 2", "NO"]
null
Java 8
standard input
[ "greedy", "two pointers", "implementation", "sortings", "data structures" ]
7fdcfe1a45994e051345cb6462253ef7
The first line contains a single integer n — the number of parts in the play (1 ≤ n ≤ 105). Next n lines contain two space-separated integers each, aj and bj — the range of notes for the j-th part (1 ≤ aj ≤ bj ≤ 109). The next line contains a single integer m — the number of actors (1 ≤ m ≤ 105). Next m lines contain three space-separated integers each, ci, di and ki — the range of the i-th actor and the number of parts that he can perform (1 ≤ ci ≤ di ≤ 109, 1 ≤ ki ≤ 109).
2,100
If there is an assignment that meets all the criteria aboce, print a single word "YES" (without the quotes) in the first line. In the next line print n space-separated integers. The i-th integer should be the number of the actor who should perform the i-th part. If there are multiple correct assignments, print any of them. If there is no correct assignment, print a single word "NO" (without the quotes).
standard output
PASSED
63f9375c9eb460ad00f7aa0299b739c6
train_002.jsonl
1418833800
You are an assistant director in a new musical play. The play consists of n musical parts, each part must be performed by exactly one actor. After the casting the director chose m actors who can take part in the play. Your task is to assign the parts to actors. However, there are several limitations.First, each actor has a certain voice range and there are some parts that he cannot sing. Formally, there are two integers for each actor, ci and di (ci ≤ di) — the pitch of the lowest and the highest note that the actor can sing. There also are two integers for each part — aj and bj (aj ≤ bj) — the pitch of the lowest and the highest notes that are present in the part. The i-th actor can perform the j-th part if and only if ci ≤ aj ≤ bj ≤ di, i.e. each note of the part is in the actor's voice range.According to the contract, the i-th actor can perform at most ki parts. Besides, you are allowed not to give any part to some actors (then they take part in crowd scenes).The rehearsal starts in two hours and you need to do the assignment quickly!
256 megabytes
import java.util.List; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.ArrayList; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.util.Collections; 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); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, FastScanner in, PrintWriter out) { int numSongs = in.nextInt(); Song[] songs = new Song[numSongs]; List<Event> events = new ArrayList<Event>(); for (int i = 0; i < numSongs; i++) { int l = in.nextInt(); int r = in.nextInt(); songs[i] = new Song(l, r, i); events.add(new Event(l, i, 1)); } int numSingers = in.nextInt(); Singer[] singers = new Singer[numSingers]; tree = new int[numSingers]; for (int i = 0; i < numSingers; i++) { int l = in.nextInt(); int r = in.nextInt(); int k = in.nextInt(); singers[i] = new Singer(l, r, k, i); events.add(new Event(l, i, 0)); events.add(new Event(r, i, 2)); } Collections.sort(events); Singer[] sortedSingers = singers.clone(); Arrays.sort(sortedSingers); int[] ans = new int[numSongs]; boolean ok = true; for (Event e : events) { if (e.type == 0) { int pos = Arrays.binarySearch(sortedSingers, singers[e.id]); add(pos, +1); } else if (e.type == 1) { int l = -1; int r = numSingers - 1; int need = songs[e.id].r; // the first singer s with s.r >= need while (r - l > 1) { int m = (l + r) / 2; Singer s = sortedSingers[m]; if (s.r >= need) { r = m; } else { l = m; } } if (sortedSingers[r].r < need) { ok = false; break; } int first = r; l = first - 1; r = numSingers - 1; if (sum(first, numSingers - 1) == 0) { ok = false; break; } while (r - l > 1) { int m = (l + r) / 2; if (sum(first, m) > 0) { r = m; } else { l = m; } } Singer best = sortedSingers[r]; --best.k; if (best.k == 0) { add(r, -1); } ans[e.id] = best.id; } else { int pos = Arrays.binarySearch(sortedSingers, singers[e.id]); if (singers[e.id].k > 0) { add(pos, -1); } } } if (!ok) { out.println("NO"); return; } out.println("YES"); for (int i = 0; i < numSongs; i++) { if (i > 0) { out.print(" "); } out.print(ans[i] + 1); } out.println(); } int[] tree; void add(int pos, int val) { while (pos < tree.length) { tree[pos] += val; pos |= pos + 1; } } int sum(int l, int r) { if (l > r) { return 0; } return sum(r) - sum(l - 1); } int sum(int r) { int res = 0; while (r >= 0) { res += tree[r]; r = (r & (r + 1)) - 1; } return res; } class Event implements Comparable<Event> { int x; int id; int type; Event(int x, int id, int type) { this.x = x; this.id = id; this.type = type; } public int compareTo(Event o) { if (x != o.x) { return x < o.x ? -1 : 1; } if (type != o.type) { return type - o.type; } return id - o.id; } } class Singer implements Comparable<Singer> { int l, r; int id; int k; Singer(int l, int r, int k, int id) { this.l = l; this.r = r; this.k = k; this.id = id; } public int compareTo(Singer o) { if (r != o.r) { return r < o.r ? -1 : 1; } return id - o.id; } } class Song implements Comparable<Song> { int l, r; int id; Song(int l, int r, int id) { this.l = l; this.r = r; this.id = id; } public int compareTo(Song o) { if (l != o.l) { return l < o.l ? -1 : 1; } if (r != o.r) { return r > o.r ? -1 : 1; } return id - o.id; } } } class FastScanner { private BufferedReader in; private StringTokenizer st; public FastScanner(InputStream stream) { in = new BufferedReader(new InputStreamReader(stream)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { String rl = in.readLine(); if (rl == null) { return null; } st = new StringTokenizer(rl); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["3\n1 3\n2 4\n3 5\n2\n1 4 2\n2 5 1", "3\n1 3\n2 4\n3 5\n2\n1 3 2\n2 5 1"]
2 seconds
["YES\n1 1 2", "NO"]
null
Java 8
standard input
[ "greedy", "two pointers", "implementation", "sortings", "data structures" ]
7fdcfe1a45994e051345cb6462253ef7
The first line contains a single integer n — the number of parts in the play (1 ≤ n ≤ 105). Next n lines contain two space-separated integers each, aj and bj — the range of notes for the j-th part (1 ≤ aj ≤ bj ≤ 109). The next line contains a single integer m — the number of actors (1 ≤ m ≤ 105). Next m lines contain three space-separated integers each, ci, di and ki — the range of the i-th actor and the number of parts that he can perform (1 ≤ ci ≤ di ≤ 109, 1 ≤ ki ≤ 109).
2,100
If there is an assignment that meets all the criteria aboce, print a single word "YES" (without the quotes) in the first line. In the next line print n space-separated integers. The i-th integer should be the number of the actor who should perform the i-th part. If there are multiple correct assignments, print any of them. If there is no correct assignment, print a single word "NO" (without the quotes).
standard output
PASSED
ac7231cf0fec3c5c2b6abe7b0108279a
train_002.jsonl
1418833800
You are an assistant director in a new musical play. The play consists of n musical parts, each part must be performed by exactly one actor. After the casting the director chose m actors who can take part in the play. Your task is to assign the parts to actors. However, there are several limitations.First, each actor has a certain voice range and there are some parts that he cannot sing. Formally, there are two integers for each actor, ci and di (ci ≤ di) — the pitch of the lowest and the highest note that the actor can sing. There also are two integers for each part — aj and bj (aj ≤ bj) — the pitch of the lowest and the highest notes that are present in the part. The i-th actor can perform the j-th part if and only if ci ≤ aj ≤ bj ≤ di, i.e. each note of the part is in the actor's voice range.According to the contract, the i-th actor can perform at most ki parts. Besides, you are allowed not to give any part to some actors (then they take part in crowd scenes).The rehearsal starts in two hours and you need to do the assignment quickly!
256 megabytes
import java.util.List; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.SortedSet; import java.util.Set; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.TreeSet; import java.util.StringTokenizer; import java.util.Collections; 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); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, FastScanner in, PrintWriter out) { int numSongs = in.nextInt(); Song[] songs = new Song[numSongs]; List<Event> events = new ArrayList<Event>(); for (int i = 0; i < numSongs; i++) { int l = in.nextInt(); int r = in.nextInt(); songs[i] = new Song(l, r, i); events.add(new Event(l, i, 1)); } int numSingers = in.nextInt(); Singer[] singers = new Singer[numSingers]; TreeSet<Singer> set = new TreeSet<Singer>(); for (int i = 0; i < numSingers; i++) { int l = in.nextInt(); int r = in.nextInt(); int k = in.nextInt(); singers[i] = new Singer(l, r, k, i); events.add(new Event(l, i, 0)); events.add(new Event(r, i, 2)); } Collections.sort(events); int[] ans = new int[numSongs]; for (Event e : events) { if (e.type == 0) { set.add(singers[e.id]); } else if (e.type == 1) { int need = songs[e.id].r; // the first singer s with s.r >= need SortedSet<Singer> all = set.tailSet(new Singer(0, need, 0, -1)); if (all.isEmpty()) { out.println("NO"); return; } Singer best = all.first(); --best.k; if (best.k == 0) { set.remove(best); } ans[e.id] = best.id; } else { if (singers[e.id].k > 0) { set.remove(singers[e.id]); } } } out.println("YES"); for (int i = 0; i < numSongs; i++) { if (i > 0) { out.print(" "); } out.print(ans[i] + 1); } out.println(); } class Event implements Comparable<Event> { int x; int id; int type; Event(int x, int id, int type) { this.x = x; this.id = id; this.type = type; } public int compareTo(Event o) { if (x != o.x) { return x < o.x ? -1 : 1; } if (type != o.type) { return type - o.type; } return id - o.id; } } class Singer implements Comparable<Singer> { int l, r; int id; int k; Singer(int l, int r, int k, int id) { this.l = l; this.r = r; this.k = k; this.id = id; } public int compareTo(Singer o) { if (r != o.r) { return r < o.r ? -1 : 1; } return id - o.id; } } class Song implements Comparable<Song> { int l, r; int id; Song(int l, int r, int id) { this.l = l; this.r = r; this.id = id; } public int compareTo(Song o) { if (l != o.l) { return l < o.l ? -1 : 1; } if (r != o.r) { return r > o.r ? -1 : 1; } return id - o.id; } } } class FastScanner { private BufferedReader in; private StringTokenizer st; public FastScanner(InputStream stream) { in = new BufferedReader(new InputStreamReader(stream)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { String rl = in.readLine(); if (rl == null) { return null; } st = new StringTokenizer(rl); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["3\n1 3\n2 4\n3 5\n2\n1 4 2\n2 5 1", "3\n1 3\n2 4\n3 5\n2\n1 3 2\n2 5 1"]
2 seconds
["YES\n1 1 2", "NO"]
null
Java 8
standard input
[ "greedy", "two pointers", "implementation", "sortings", "data structures" ]
7fdcfe1a45994e051345cb6462253ef7
The first line contains a single integer n — the number of parts in the play (1 ≤ n ≤ 105). Next n lines contain two space-separated integers each, aj and bj — the range of notes for the j-th part (1 ≤ aj ≤ bj ≤ 109). The next line contains a single integer m — the number of actors (1 ≤ m ≤ 105). Next m lines contain three space-separated integers each, ci, di and ki — the range of the i-th actor and the number of parts that he can perform (1 ≤ ci ≤ di ≤ 109, 1 ≤ ki ≤ 109).
2,100
If there is an assignment that meets all the criteria aboce, print a single word "YES" (without the quotes) in the first line. In the next line print n space-separated integers. The i-th integer should be the number of the actor who should perform the i-th part. If there are multiple correct assignments, print any of them. If there is no correct assignment, print a single word "NO" (without the quotes).
standard output
PASSED
ba6efb304999cf6328bed82a2657e73c
train_002.jsonl
1418833800
You are an assistant director in a new musical play. The play consists of n musical parts, each part must be performed by exactly one actor. After the casting the director chose m actors who can take part in the play. Your task is to assign the parts to actors. However, there are several limitations.First, each actor has a certain voice range and there are some parts that he cannot sing. Formally, there are two integers for each actor, ci and di (ci ≤ di) — the pitch of the lowest and the highest note that the actor can sing. There also are two integers for each part — aj and bj (aj ≤ bj) — the pitch of the lowest and the highest notes that are present in the part. The i-th actor can perform the j-th part if and only if ci ≤ aj ≤ bj ≤ di, i.e. each note of the part is in the actor's voice range.According to the contract, the i-th actor can perform at most ki parts. Besides, you are allowed not to give any part to some actors (then they take part in crowd scenes).The rehearsal starts in two hours and you need to do the assignment quickly!
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.SortedSet; import java.util.Set; import java.io.IOException; import java.io.InputStreamReader; import java.util.TreeSet; import java.util.StringTokenizer; import java.io.BufferedReader; import java.util.Comparator; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author beginner1010 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); Songs[] songs = new Songs[n]; for (int i = 0; i < n; i++) { songs[i] = new Songs(); songs[i].id = i; songs[i].left = in.nextInt(); songs[i].right = in.nextInt(); } Arrays.sort(songs, new Comparator<Songs>() { public int compare(Songs o1, Songs o2) { return o1.left - o2.left; } }); int m = in.nextInt(); Actors[] actors = new Actors[m]; for (int i = 0; i < m; i++) { actors[i] = new Actors(); actors[i].id = i; actors[i].left = in.nextInt(); actors[i].right = in.nextInt(); actors[i].capacity = in.nextInt(); } Arrays.sort(actors, new Comparator<Actors>() { public int compare(Actors o1, Actors o2) { return o1.left - o2.left; } }); TreeSet<Actors> tree = new TreeSet<Actors>(new Comparator<Actors>() { public int compare(Actors o1, Actors o2) { int cmp = o1.right - o2.right; if (cmp == 0) { cmp = o1.id - o2.id; } return cmp; } }); int[] ans = new int[n]; int idx = 0; for (int i = 0; i < n; i++) { int a = songs[i].left, b = songs[i].right; while (idx < m && actors[idx].left <= a) { tree.add(actors[idx]); idx++; } Actors dump = new Actors(); dump.right = b; dump.id = -1; SortedSet<Actors> tail = tree.tailSet(dump); if (tail.isEmpty()) { out.println("NO"); return; } Actors closest = tail.first(); ans[songs[i].id] = closest.id + 1; closest.capacity--; if (closest.capacity == 0) { tree.remove(closest); } } out.println("YES"); for (int i = 0; i < n; i++) { if (i > 0) out.print(" "); out.print(ans[i]); } out.println(); } class Songs { int left; int right; int id; } class Actors { int left; int right; int capacity; int id; } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["3\n1 3\n2 4\n3 5\n2\n1 4 2\n2 5 1", "3\n1 3\n2 4\n3 5\n2\n1 3 2\n2 5 1"]
2 seconds
["YES\n1 1 2", "NO"]
null
Java 8
standard input
[ "greedy", "two pointers", "implementation", "sortings", "data structures" ]
7fdcfe1a45994e051345cb6462253ef7
The first line contains a single integer n — the number of parts in the play (1 ≤ n ≤ 105). Next n lines contain two space-separated integers each, aj and bj — the range of notes for the j-th part (1 ≤ aj ≤ bj ≤ 109). The next line contains a single integer m — the number of actors (1 ≤ m ≤ 105). Next m lines contain three space-separated integers each, ci, di and ki — the range of the i-th actor and the number of parts that he can perform (1 ≤ ci ≤ di ≤ 109, 1 ≤ ki ≤ 109).
2,100
If there is an assignment that meets all the criteria aboce, print a single word "YES" (without the quotes) in the first line. In the next line print n space-separated integers. The i-th integer should be the number of the actor who should perform the i-th part. If there are multiple correct assignments, print any of them. If there is no correct assignment, print a single word "NO" (without the quotes).
standard output
PASSED
b6d1887dec2b0f0ad6fa907732fe23f6
train_002.jsonl
1418833800
You are an assistant director in a new musical play. The play consists of n musical parts, each part must be performed by exactly one actor. After the casting the director chose m actors who can take part in the play. Your task is to assign the parts to actors. However, there are several limitations.First, each actor has a certain voice range and there are some parts that he cannot sing. Formally, there are two integers for each actor, ci and di (ci ≤ di) — the pitch of the lowest and the highest note that the actor can sing. There also are two integers for each part — aj and bj (aj ≤ bj) — the pitch of the lowest and the highest notes that are present in the part. The i-th actor can perform the j-th part if and only if ci ≤ aj ≤ bj ≤ di, i.e. each note of the part is in the actor's voice range.According to the contract, the i-th actor can perform at most ki parts. Besides, you are allowed not to give any part to some actors (then they take part in crowd scenes).The rehearsal starts in two hours and you need to do the assignment quickly!
256 megabytes
import java.awt.Point; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Currency; import java.util.HashSet; import java.util.List; import java.util.SortedSet; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeSet; /** * @author Jens Staahl */ public class Prac { // some local config // static boolean test = false ; private boolean test = System.getProperty("ONLINE_JUDGE") == null; static String testDataFile = "testdata.txt"; // static String testDataFile = "testdata.txt"; private static String ENDL = "\n"; // Just solves the acutal kattis-problem ZKattio io; class Part implements Comparable<Part> { int left, right, idx; public Part(int left, int right, int idx) { super(); this.left = left; this.right = right; this.idx = idx; } @Override public int compareTo(Part o) { return Integer.compare(left, o.left); } } class Actor implements Comparable<Actor> { int left, right, idx, count; public Actor(int left, int right, int idx, int count) { super(); this.left = left; this.right = right; this.idx = idx; this.count = count; } @Override public int compareTo(Actor o) { return Integer.compare(left, o.left); } } private void solve() throws Throwable { io = new ZKattio(stream); int n = io.getInt(); Part[] parts = new Part[n]; for (int i = 0; i < n; i++) { parts[i] = new Part(io.getInt(), io.getInt(), i+1); } int m = io.getInt(); Actor[] actors = new Actor[m]; for (int i = 0; i < m; i++) { actors[i] = new Actor(io.getInt(), io.getInt(), i+1, io.getInt()); } Arrays.sort(parts); Arrays.sort(actors); int aidx = 0; TreeSet<Actor> set = new TreeSet<Actor>(new Comparator<Actor>() { @Override public int compare(Actor a, Actor b) { if(a.right != b.right){ return Integer.compare(a.right, b.right); } return Integer.compare(a.idx, b.idx); } }); int[] ans = new int[n+1]; for (int i = 0; i < parts.length; i++) { Part part = parts[i]; while(aidx < actors.length && actors[aidx].left <= part.left){ Actor actor = actors[aidx]; set.add(actor); aidx ++; } SortedSet<Actor> tailSet = set.tailSet(new Actor(0, part.right, -1, 0)); if(tailSet.isEmpty()) { System.out.println("NO"); return; } Actor actor = tailSet.first(); actor.count --; ans[part.idx]= actor.idx; if(actor.count == 0) { tailSet.remove(actor); } } out.print("YES\n"); for (int i = 0; i < n; i++) { if(i > 0) { out.print(" " ); } out.print(ans[i+1] + ""); } out.flush(); } public static void main(String[] args) throws Throwable { new Prac().solve(); } public Prac() throws Throwable { if (test) { stream = new FileInputStream(testDataFile); } } InputStream stream = System.in; PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));// outStream public class ZKattio extends PrintWriter { public ZKattio(InputStream i) { super(new BufferedOutputStream(System.out)); r = new BufferedReader(new InputStreamReader(i)); } public ZKattio(InputStream i, OutputStream o) { super(new BufferedOutputStream(o)); r = new BufferedReader(new InputStreamReader(i)); } public boolean hasMoreTokens() { return peekToken() != null; } public int getInt() { return Integer.parseInt(nextToken()); } public double getDouble() { return Double.parseDouble(nextToken()); } public long getLong() { return Long.parseLong(nextToken()); } public String getWord() { return nextToken(); } private BufferedReader r; private String line; private StringTokenizer st; private String token; private String peekToken() { if (token == null) try { while (st == null || !st.hasMoreTokens()) { line = r.readLine(); if (line == null) return null; st = new StringTokenizer(line); } token = st.nextToken(); } catch (IOException e) { } return token; } private String nextToken() { String ans = peekToken(); token = null; return ans; } } // System.out; }
Java
["3\n1 3\n2 4\n3 5\n2\n1 4 2\n2 5 1", "3\n1 3\n2 4\n3 5\n2\n1 3 2\n2 5 1"]
2 seconds
["YES\n1 1 2", "NO"]
null
Java 8
standard input
[ "greedy", "two pointers", "implementation", "sortings", "data structures" ]
7fdcfe1a45994e051345cb6462253ef7
The first line contains a single integer n — the number of parts in the play (1 ≤ n ≤ 105). Next n lines contain two space-separated integers each, aj and bj — the range of notes for the j-th part (1 ≤ aj ≤ bj ≤ 109). The next line contains a single integer m — the number of actors (1 ≤ m ≤ 105). Next m lines contain three space-separated integers each, ci, di and ki — the range of the i-th actor and the number of parts that he can perform (1 ≤ ci ≤ di ≤ 109, 1 ≤ ki ≤ 109).
2,100
If there is an assignment that meets all the criteria aboce, print a single word "YES" (without the quotes) in the first line. In the next line print n space-separated integers. The i-th integer should be the number of the actor who should perform the i-th part. If there are multiple correct assignments, print any of them. If there is no correct assignment, print a single word "NO" (without the quotes).
standard output
PASSED
ead30c62e4ac813cf992259c4ad87ad7
train_002.jsonl
1418833800
You are an assistant director in a new musical play. The play consists of n musical parts, each part must be performed by exactly one actor. After the casting the director chose m actors who can take part in the play. Your task is to assign the parts to actors. However, there are several limitations.First, each actor has a certain voice range and there are some parts that he cannot sing. Formally, there are two integers for each actor, ci and di (ci ≤ di) — the pitch of the lowest and the highest note that the actor can sing. There also are two integers for each part — aj and bj (aj ≤ bj) — the pitch of the lowest and the highest notes that are present in the part. The i-th actor can perform the j-th part if and only if ci ≤ aj ≤ bj ≤ di, i.e. each note of the part is in the actor's voice range.According to the contract, the i-th actor can perform at most ki parts. Besides, you are allowed not to give any part to some actors (then they take part in crowd scenes).The rehearsal starts in two hours and you need to do the assignment quickly!
256 megabytes
import java.awt.Point; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.SortedSet; import java.util.StringTokenizer; import java.util.TreeSet; /** * @author Jens Staahl */ public class Prac { // some local config // static boolean test = false ; private boolean test = System.getProperty("ONLINE_JUDGE") == null; static String testDataFile = "testdata.txt"; // static String testDataFile = "testdata.txt"; private static String ENDL = "\n"; // Just solves the acutal kattis-problem ZKattio io; class Part implements Comparable<Part>{ int left, right, idx; public Part(int left, int right, int idx) { this.left = left; this.right = right; this.idx = idx; } @Override public int compareTo(Part o) { return Integer.compare(this.left, o.left); } } class Actor implements Comparable<Actor>{ int left, right, idx, capacity; public Actor(int left, int right, int idx, int capacity) { super(); this.left = left; this.right = right; this.idx = idx; this.capacity = capacity; } @Override public int compareTo(Actor o) { return Integer.compare(this.left, o.left); } } private void solve() throws Throwable { io = new ZKattio(stream); int n = io.getInt(); Part[] parts = new Part[n]; for (int i = 0; i < n; i++) { parts[i] = new Part(io.getInt(), io.getInt(), i); } int m = io.getInt(); Actor[] actors = new Actor[m]; for (int i = 0; i < m; i++) { actors[i] = new Actor(io.getInt(), io.getInt(), i, io.getInt()); } Arrays.sort(parts); Arrays.sort(actors); int aidx = 0; TreeSet<Actor> set = new TreeSet<>(new Comparator<Actor>() { @Override public int compare(Actor o1, Actor o2) { int c = o1.right - o2.right; if(c != 0) { return c; } return o1.idx - o2.idx; } }); int[] res = new int[n]; // long t0 = -System.currentTimeMillis(); // long t1 = 0;//-System.currentTimeMillis(); for (int i = 0; i < parts.length; i++) { Part p = parts[i]; // if( i % 100 == 0) { // System.out.println((System.currentTimeMillis() + t0 ) + ", "+ t1); // } while (aidx < actors.length && actors[aidx].left <= p.left) { set.add(actors[aidx]); aidx++; } SortedSet<Actor> tailSet = set.tailSet(new Actor(0, p.right, -1, 0)); // t1 -= System.currentTimeMillis(); if (tailSet.isEmpty()) { System.out.println("NO"); return; } // t1 += System.currentTimeMillis(); Actor first = tailSet.first(); first.capacity--; res[p.idx] = first.idx + 1; if (first.capacity <= 0) { set.remove(first); } } out.print("YES\n"); for (int i = 0; i < res.length; i++) { if(i > 0) { out.print(" "); } out.print(res[i] +""); } out.print("\n"); out.flush(); } public static void main(String[] args) throws Throwable { new Prac().solve(); } public Prac() throws Throwable { if (test) { stream = new FileInputStream(testDataFile); } } InputStream stream = System.in; PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));// outStream public class ZKattio extends PrintWriter { public ZKattio(InputStream i) { super(new BufferedOutputStream(System.out)); r = new BufferedReader(new InputStreamReader(i)); } public ZKattio(InputStream i, OutputStream o) { super(new BufferedOutputStream(o)); r = new BufferedReader(new InputStreamReader(i)); } public boolean hasMoreTokens() { return peekToken() != null; } public int getInt() { return Integer.parseInt(nextToken()); } public double getDouble() { return Double.parseDouble(nextToken()); } public long getLong() { return Long.parseLong(nextToken()); } public String getWord() { return nextToken(); } private BufferedReader r; private String line; private StringTokenizer st; private String token; private String peekToken() { if (token == null) try { while (st == null || !st.hasMoreTokens()) { line = r.readLine(); if (line == null) return null; st = new StringTokenizer(line); } token = st.nextToken(); } catch (IOException e) { } return token; } private String nextToken() { String ans = peekToken(); token = null; return ans; } } // System.out; }
Java
["3\n1 3\n2 4\n3 5\n2\n1 4 2\n2 5 1", "3\n1 3\n2 4\n3 5\n2\n1 3 2\n2 5 1"]
2 seconds
["YES\n1 1 2", "NO"]
null
Java 8
standard input
[ "greedy", "two pointers", "implementation", "sortings", "data structures" ]
7fdcfe1a45994e051345cb6462253ef7
The first line contains a single integer n — the number of parts in the play (1 ≤ n ≤ 105). Next n lines contain two space-separated integers each, aj and bj — the range of notes for the j-th part (1 ≤ aj ≤ bj ≤ 109). The next line contains a single integer m — the number of actors (1 ≤ m ≤ 105). Next m lines contain three space-separated integers each, ci, di and ki — the range of the i-th actor and the number of parts that he can perform (1 ≤ ci ≤ di ≤ 109, 1 ≤ ki ≤ 109).
2,100
If there is an assignment that meets all the criteria aboce, print a single word "YES" (without the quotes) in the first line. In the next line print n space-separated integers. The i-th integer should be the number of the actor who should perform the i-th part. If there are multiple correct assignments, print any of them. If there is no correct assignment, print a single word "NO" (without the quotes).
standard output
PASSED
623cd90380a44e9344dcc40943a7d1f0
train_002.jsonl
1418833800
You are an assistant director in a new musical play. The play consists of n musical parts, each part must be performed by exactly one actor. After the casting the director chose m actors who can take part in the play. Your task is to assign the parts to actors. However, there are several limitations.First, each actor has a certain voice range and there are some parts that he cannot sing. Formally, there are two integers for each actor, ci and di (ci ≤ di) — the pitch of the lowest and the highest note that the actor can sing. There also are two integers for each part — aj and bj (aj ≤ bj) — the pitch of the lowest and the highest notes that are present in the part. The i-th actor can perform the j-th part if and only if ci ≤ aj ≤ bj ≤ di, i.e. each note of the part is in the actor's voice range.According to the contract, the i-th actor can perform at most ki parts. Besides, you are allowed not to give any part to some actors (then they take part in crowd scenes).The rehearsal starts in two hours and you need to do the assignment quickly!
256 megabytes
import java.awt.Point; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.SortedSet; import java.util.StringTokenizer; import java.util.TreeSet; /** * @author Jens Staahl */ public class Prac { // some local config // static boolean test = false ; private boolean test = System.getProperty("ONLINE_JUDGE") == null; static String testDataFile = "testdata.txt"; // static String testDataFile = "testdata.txt"; private static String ENDL = "\n"; // Just solves the acutal kattis-problem ZKattio io; class Actor implements Comparable<Actor>{ int left, right, idx, capacity; public Actor(int left, int right, int idx, int capacity) { super(); this.left = left; this.right = right; this.idx = idx; this.capacity = capacity; } @Override public int compareTo(Actor o) { return Integer.compare(left, o.left); } } class Part implements Comparable<Part> { int left, right, idx; public Part(int left, int right, int idx) { super(); this.left = left; this.right = right; this.idx = idx; } @Override public int compareTo(Part o) { return Integer.compare(left, o.left); } } private void solve() throws Throwable { io = new ZKattio(stream); List<Actor> actors = new ArrayList<>(); List<Part> parts = new ArrayList<>(); int n = io.getInt(); for (int i = 0; i < n; i++) { parts.add(new Part(io.getInt(), io.getInt(), i+1)); } int m = io.getInt(); for (int i = 0; i < m; i++) { actors.add(new Actor(io.getInt(), io.getInt(), i+1, io.getInt())); } Collections.sort(actors); Collections.sort(parts); TreeSet<Actor> set = new TreeSet<>(new Comparator<Actor>(){ @Override public int compare(Actor o1, Actor o2) { int ret = Integer.compare(o1.right, o2.right); if(ret == 0) { ret = Integer.compare(o1.idx, o2.idx); } return ret; }}); int actorIdx = 0; int[] ans = new int[n+1]; for (Part part : parts) { while(actorIdx < actors.size() && actors.get(actorIdx).left <= part.left) { set.add(actors.get(actorIdx)); actorIdx ++; } SortedSet<Actor> tailSet = set.tailSet(new Actor(0, part.right, -1, 0)); if(tailSet.isEmpty()) { System.out.println("NO"); return; } Actor first = tailSet.first(); first.capacity --; ans[part.idx] = first.idx; if(first.capacity <= 0) { set.remove(first); } } out.print("YES\n"); for (int i = 0; i < n; i++) { if(i > 0) { out.print(" "); } out.print(ans[i+1]); } out.flush(); } public static void main(String[] args) throws Throwable { new Prac().solve(); } public Prac() throws Throwable { if (test) { stream = new FileInputStream(testDataFile); } } InputStream stream = System.in; PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));// outStream public class ZKattio extends PrintWriter { public ZKattio(InputStream i) { super(new BufferedOutputStream(System.out)); r = new BufferedReader(new InputStreamReader(i)); } public ZKattio(InputStream i, OutputStream o) { super(new BufferedOutputStream(o)); r = new BufferedReader(new InputStreamReader(i)); } public boolean hasMoreTokens() { return peekToken() != null; } public int getInt() { return Integer.parseInt(nextToken()); } public double getDouble() { return Double.parseDouble(nextToken()); } public long getLong() { return Long.parseLong(nextToken()); } public String getWord() { return nextToken(); } private BufferedReader r; private String line; private StringTokenizer st; private String token; private String peekToken() { if (token == null) try { while (st == null || !st.hasMoreTokens()) { line = r.readLine(); if (line == null) return null; st = new StringTokenizer(line); } token = st.nextToken(); } catch (IOException e) { } return token; } private String nextToken() { String ans = peekToken(); token = null; return ans; } } // System.out; }
Java
["3\n1 3\n2 4\n3 5\n2\n1 4 2\n2 5 1", "3\n1 3\n2 4\n3 5\n2\n1 3 2\n2 5 1"]
2 seconds
["YES\n1 1 2", "NO"]
null
Java 8
standard input
[ "greedy", "two pointers", "implementation", "sortings", "data structures" ]
7fdcfe1a45994e051345cb6462253ef7
The first line contains a single integer n — the number of parts in the play (1 ≤ n ≤ 105). Next n lines contain two space-separated integers each, aj and bj — the range of notes for the j-th part (1 ≤ aj ≤ bj ≤ 109). The next line contains a single integer m — the number of actors (1 ≤ m ≤ 105). Next m lines contain three space-separated integers each, ci, di and ki — the range of the i-th actor and the number of parts that he can perform (1 ≤ ci ≤ di ≤ 109, 1 ≤ ki ≤ 109).
2,100
If there is an assignment that meets all the criteria aboce, print a single word "YES" (without the quotes) in the first line. In the next line print n space-separated integers. The i-th integer should be the number of the actor who should perform the i-th part. If there are multiple correct assignments, print any of them. If there is no correct assignment, print a single word "NO" (without the quotes).
standard output
PASSED
6408d51063844bfb92775c0a5689e1ba
train_002.jsonl
1418833800
You are an assistant director in a new musical play. The play consists of n musical parts, each part must be performed by exactly one actor. After the casting the director chose m actors who can take part in the play. Your task is to assign the parts to actors. However, there are several limitations.First, each actor has a certain voice range and there are some parts that he cannot sing. Formally, there are two integers for each actor, ci and di (ci ≤ di) — the pitch of the lowest and the highest note that the actor can sing. There also are two integers for each part — aj and bj (aj ≤ bj) — the pitch of the lowest and the highest notes that are present in the part. The i-th actor can perform the j-th part if and only if ci ≤ aj ≤ bj ≤ di, i.e. each note of the part is in the actor's voice range.According to the contract, the i-th actor can perform at most ki parts. Besides, you are allowed not to give any part to some actors (then they take part in crowd scenes).The rehearsal starts in two hours and you need to do the assignment quickly!
256 megabytes
import java.io.*; import java.util.*; public class C { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; static class Task implements Comparable<Task> { int l, r, id; public Task(int l, int r, int id) { this.l = l; this.r = r; this.id = id; } @Override public int compareTo(Task o) { if (l != o.l) { return l < o.l ? -1 : 1; } return Integer.compare(r, o.r); } } static class Worker implements Comparable<Worker> { int l, r, cap, id; public Worker(int l, int r, int cap, int id) { this.l = l; this.r = r; this.cap = cap; this.id = id; } @Override public int compareTo(Worker o) { if (r != o.r) { return r < o.r ? -1 : 1; } if (l != o.l) { return l < o.l ? -1 : 1; } return Integer.compare(id, o.id); } } void solve() throws IOException { int n = nextInt(); Task[] a = new Task[n]; for (int i = 0; i < n; i++) { int l = nextInt(); int r = nextInt(); a[i] = new Task(l, r, i); } int m = nextInt(); Worker[] b = new Worker[m]; for (int i = 0; i < m; i++) { int l = nextInt(); int r = nextInt(); int cap = nextInt(); b[i] = new Worker(l, r, cap, i); } Arrays.sort(a); Arrays.sort(b, new Comparator<Worker>() { @Override public int compare(Worker o1, Worker o2) { if (o1.l != o2.l) { return o1.l < o2.l ? -1 : 1; } return Integer.compare(o1.r, o2.r); } }); TreeSet<Worker> set = new TreeSet<>(); Worker seeker = new Worker(-1, -1, -1, -1); int[] ans = new int[n]; for (int i = 0, j = 0; i < n; i++) { while (j < m && b[j].l <= a[i].l) { set.add(b[j++]); } seeker.l = -1; seeker.r = a[i].r; Worker use = set.higher(seeker); if (use == null) { out.println("NO"); return; } ans[a[i].id] = use.id; use.cap--; if (use.cap == 0) { set.remove(use); } } out.println("YES"); for (int i = 0; i < n; i++) { out.print(ans[i] + 1 + " " ); } out.println(); } C() 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 C(); } 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\n1 3\n2 4\n3 5\n2\n1 4 2\n2 5 1", "3\n1 3\n2 4\n3 5\n2\n1 3 2\n2 5 1"]
2 seconds
["YES\n1 1 2", "NO"]
null
Java 8
standard input
[ "greedy", "two pointers", "implementation", "sortings", "data structures" ]
7fdcfe1a45994e051345cb6462253ef7
The first line contains a single integer n — the number of parts in the play (1 ≤ n ≤ 105). Next n lines contain two space-separated integers each, aj and bj — the range of notes for the j-th part (1 ≤ aj ≤ bj ≤ 109). The next line contains a single integer m — the number of actors (1 ≤ m ≤ 105). Next m lines contain three space-separated integers each, ci, di and ki — the range of the i-th actor and the number of parts that he can perform (1 ≤ ci ≤ di ≤ 109, 1 ≤ ki ≤ 109).
2,100
If there is an assignment that meets all the criteria aboce, print a single word "YES" (without the quotes) in the first line. In the next line print n space-separated integers. The i-th integer should be the number of the actor who should perform the i-th part. If there are multiple correct assignments, print any of them. If there is no correct assignment, print a single word "NO" (without the quotes).
standard output
PASSED
206ce48f129e7e77fb03da942a9e3651
train_002.jsonl
1418833800
You are an assistant director in a new musical play. The play consists of n musical parts, each part must be performed by exactly one actor. After the casting the director chose m actors who can take part in the play. Your task is to assign the parts to actors. However, there are several limitations.First, each actor has a certain voice range and there are some parts that he cannot sing. Formally, there are two integers for each actor, ci and di (ci ≤ di) — the pitch of the lowest and the highest note that the actor can sing. There also are two integers for each part — aj and bj (aj ≤ bj) — the pitch of the lowest and the highest notes that are present in the part. The i-th actor can perform the j-th part if and only if ci ≤ aj ≤ bj ≤ di, i.e. each note of the part is in the actor's voice range.According to the contract, the i-th actor can perform at most ki parts. Besides, you are allowed not to give any part to some actors (then they take part in crowd scenes).The rehearsal starts in two hours and you need to do the assignment quickly!
256 megabytes
import java.util.*; import java.io.*; import java.awt.Point; import java.math.BigDecimal; import java.math.BigInteger; import static java.lang.Math.*; // Solution is at the bottom of code public class C implements Runnable{ final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; BufferedReader in; OutputWriter out; StringTokenizer tok = new StringTokenizer(""); public static void main(String[] args){ new Thread(null, new C(), "", 128 * (1L << 20)).start(); } ///////////////////////////////////////////////////////////////////// void init() throws FileNotFoundException{ Locale.setDefault(Locale.US); if (ONLINE_JUDGE){ in = new BufferedReader(new InputStreamReader(System.in)); out = new OutputWriter(System.out); }else{ in = new BufferedReader(new FileReader("input.txt")); out = new OutputWriter("output.txt"); } } //////////////////////////////////////////////////////////////// long timeBegin, timeEnd; void time(){ timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } void debug(Object... objects){ if (ONLINE_JUDGE){ for (Object o: objects){ System.err.println(o.toString()); } } } ///////////////////////////////////////////////////////////////////// public void run(){ try{ timeBegin = System.currentTimeMillis(); Locale.setDefault(Locale.US); init(); solve(); out.close(); time(); }catch (Exception e){ e.printStackTrace(System.err); System.exit(-1); } } ///////////////////////////////////////////////////////////////////// String delim = " "; String readString() throws IOException{ while(!tok.hasMoreTokens()){ try{ tok = new StringTokenizer(in.readLine()); }catch (Exception e){ return null; } } return tok.nextToken(delim); } String readLine() throws IOException{ return in.readLine(); } ///////////////////////////////////////////////////////////////// final char NOT_A_SYMBOL = '\0'; char readChar() throws IOException{ int intValue = in.read(); if (intValue == -1){ return NOT_A_SYMBOL; } return (char) intValue; } char[] readCharArray() throws IOException{ return readLine().toCharArray(); } ///////////////////////////////////////////////////////////////// int readInt() throws IOException { return Integer.parseInt(readString()); } int[] readIntArray(int size) throws IOException { int[] array = new int[size]; for (int index = 0; index < size; ++index){ array[index] = readInt(); } return array; } int[] readSortedIntArray(int size) throws IOException { Integer[] array = new Integer[size]; for (int index = 0; index < size; ++index) { array[index] = readInt(); } Arrays.sort(array); int[] sortedArray = new int[size]; for (int index = 0; index < size; ++index) { sortedArray[index] = array[index]; } return sortedArray; } int[] readIntArrayWithDecrease(int size) throws IOException { int[] array = readIntArray(size); for (int i = 0; i < size; ++i) { array[i]--; } return array; } /////////////////////////////////////////////////////////////////// int[][] readIntMatrix(int rowsCount, int columnsCount) throws IOException { int[][] matrix = new int[rowsCount][]; for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) { matrix[rowIndex] = readIntArray(columnsCount); } return matrix; } int[][] readIntMatrixWithDecrease(int rowsCount, int columnsCount) throws IOException { int[][] matrix = new int[rowsCount][]; for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) { matrix[rowIndex] = readIntArrayWithDecrease(columnsCount); } return matrix; } /////////////////////////////////////////////////////////////////// long readLong() throws IOException{ return Long.parseLong(readString()); } long[] readLongArray(int size) throws IOException{ long[] array = new long[size]; for (int index = 0; index < size; ++index){ array[index] = readLong(); } return array; } //////////////////////////////////////////////////////////////////// double readDouble() throws IOException{ return Double.parseDouble(readString()); } double[] readDoubleArray(int size) throws IOException{ double[] array = new double[size]; for (int index = 0; index < size; ++index){ array[index] = readDouble(); } return array; } //////////////////////////////////////////////////////////////////// BigInteger readBigInteger() throws IOException { return new BigInteger(readString()); } BigDecimal readBigDecimal() throws IOException { return new BigDecimal(readString()); } ///////////////////////////////////////////////////////////////////// Point readPoint() throws IOException{ int x = readInt(); int y = readInt(); return new Point(x, y); } Point[] readPointArray(int size) throws IOException{ Point[] array = new Point[size]; for (int index = 0; index < size; ++index){ array[index] = readPoint(); } return array; } ///////////////////////////////////////////////////////////////////// List<Integer>[] readGraph(int vertexNumber, int edgeNumber) throws IOException{ @SuppressWarnings("unchecked") List<Integer>[] graph = new List[vertexNumber]; for (int index = 0; index < vertexNumber; ++index){ graph[index] = new ArrayList<Integer>(); } while (edgeNumber-- > 0){ int from = readInt() - 1; int to = readInt() - 1; graph[from].add(to); graph[to].add(from); } return graph; } ///////////////////////////////////////////////////////////////////// static class IntIndexPair { static Comparator<IntIndexPair> increaseComparator = new Comparator<C.IntIndexPair>() { @Override public int compare(IntIndexPair indexPair1, IntIndexPair indexPair2) { int value1 = indexPair1.value; int value2 = indexPair2.value; if (value1 != value2) return value1 - value2; int index1 = indexPair1.index; int index2 = indexPair2.index; return index1 - index2; } }; static Comparator<IntIndexPair> decreaseComparator = new Comparator<C.IntIndexPair>() { @Override public int compare(IntIndexPair indexPair1, IntIndexPair indexPair2) { int value1 = indexPair1.value; int value2 = indexPair2.value; if (value1 != value2) return -(value1 - value2); int index1 = indexPair1.index; int index2 = indexPair2.index; return index1 - index2; } }; int value, index; public IntIndexPair(int value, int index) { super(); this.value = value; this.index = index; } public int getRealIndex() { return index + 1; } } IntIndexPair[] readIntIndexArray(int size) throws IOException { IntIndexPair[] array = new IntIndexPair[size]; for (int index = 0; index < size; ++index) { array[index] = new IntIndexPair(readInt(), index); } return array; } ///////////////////////////////////////////////////////////////////// static class OutputWriter extends PrintWriter { final int DEFAULT_PRECISION = 12; protected int precision; protected String format, formatWithSpace; { precision = DEFAULT_PRECISION; format = createFormat(precision); formatWithSpace = format + " "; } public OutputWriter(OutputStream out) { super(out); } public OutputWriter(String fileName) throws FileNotFoundException { super(fileName); } public int getPrecision() { return precision; } public void setPrecision(int precision) { precision = max(0, precision); this.precision = precision; format = createFormat(precision); formatWithSpace = format + " "; } private String createFormat(int precision){ return "%." + precision + "f"; } @Override public void print(double d){ printf(format, d); } public void printWithSpace(double d){ printf(formatWithSpace, d); } public void printAll(double...d){ for (int i = 0; i < d.length - 1; ++i){ printWithSpace(d[i]); } print(d[d.length - 1]); } @Override public void println(double d){ printlnAll(d); } public void printlnAll(double... d){ printAll(d); println(); } } ///////////////////////////////////////////////////////////////////// static final int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; static final int[][] steps8 = { {-1, 0}, {1, 0}, {0, -1}, {0, 1}, {-1, -1}, {1, 1}, {1, -1}, {-1, 1} }; static final boolean check(int index, int lim){ return (0 <= index && index < lim); } ///////////////////////////////////////////////////////////////////// static final boolean checkBit(int mask, int bit){ return (mask & (1 << bit)) != 0; } ///////////////////////////////////////////////////////////////////// static final long getSum(int[] array) { long sum = 0; for (int value: array) { sum += value; } return sum; } static final Point getMinMax(int[] array) { int min = array[0]; int max = array[0]; for (int index = 0, size = array.length; index < size; ++index, ++index) { int value = array[index]; if (index == size - 1) { min = min(min, value); max = max(max, value); } else { int otherValue = array[index + 1]; if (value <= otherValue) { min = min(min, value); max = max(max, otherValue); } else { min = min(min, otherValue); max = max(max, value); } } } return new Point(min, max); } ///////////////////////////////////////////////////////////////////// class Music implements Comparable<Music> { int from, to; int type; int index; public Music(int from, int to, int type, int index) { super(); this.from = from; this.to = to; this.type = type; this.index = index; } @Override public int compareTo(Music other) { if (this.from != other.from) return this.from - other.from; if (this.type != other.type) return this.type - other.type; return this.to - other.to; } } final int ACTOR = 0, SONG = 1; void solve() throws IOException { int songCount = readInt(); Point[] songs = readPointArray(songCount); int actorCount = readInt(); Point[] actors = new Point[actorCount]; final int[] counts = new int[actorCount]; for (int i = 0; i < actorCount; ++i) { actors[i] = readPoint(); counts[i] = readInt(); } int musicCount = songCount + actorCount; Music[] musics = new Music[musicCount]; for (int i = 0; i < songCount; ++i) { musics[i] = new Music(songs[i].x, songs[i].y, SONG, i); } for (int i = songCount; i < musicCount; ++i) { musics[i] = new Music(actors[i - songCount].x, actors[i - songCount].y, ACTOR, i); } Arrays.sort(musics); int[] indexes = new int[songCount]; Arrays.fill(indexes, -1); boolean can = true; TreeSet<Music> canActors = new TreeSet<C.Music>(new Comparator<Music>() { @Override public int compare(Music m1, Music m2) { if (m1.to != m2.to) { return m1.to - m2.to; } if (m2.from != m1.from) { return m2.from - m1.from; }; return m1.index - m2.index; } }); for (Music music : musics) { if (music.type == SONG) { int a = music.from; int b = music.to; // while (canActors.first().to < a) { // canActors.pollFirst(); // } // if (canActors.size() == 0) { can = false; } Music greedyMusic = canActors.ceiling(music); while (greedyMusic != null && counts[greedyMusic.index - songCount] == 0) { canActors.remove(greedyMusic); greedyMusic = canActors.ceiling(music); } if (greedyMusic == null || greedyMusic.from > a || greedyMusic.to < b || counts[greedyMusic.index - songCount] == 0) { can = false; } else { int actorIndex = greedyMusic.index - songCount; indexes[music.index] = actorIndex + 1; counts[actorIndex]--; if (counts[actorIndex] == 0) { canActors.remove(greedyMusic); } } } else { canActors.add(music); } if (!can) break; } out.println(can ? "YES" : "NO"); if (can) { for (int index : indexes) { out.print(index + " "); } out.println(); } } }
Java
["3\n1 3\n2 4\n3 5\n2\n1 4 2\n2 5 1", "3\n1 3\n2 4\n3 5\n2\n1 3 2\n2 5 1"]
2 seconds
["YES\n1 1 2", "NO"]
null
Java 8
standard input
[ "greedy", "two pointers", "implementation", "sortings", "data structures" ]
7fdcfe1a45994e051345cb6462253ef7
The first line contains a single integer n — the number of parts in the play (1 ≤ n ≤ 105). Next n lines contain two space-separated integers each, aj and bj — the range of notes for the j-th part (1 ≤ aj ≤ bj ≤ 109). The next line contains a single integer m — the number of actors (1 ≤ m ≤ 105). Next m lines contain three space-separated integers each, ci, di and ki — the range of the i-th actor and the number of parts that he can perform (1 ≤ ci ≤ di ≤ 109, 1 ≤ ki ≤ 109).
2,100
If there is an assignment that meets all the criteria aboce, print a single word "YES" (without the quotes) in the first line. In the next line print n space-separated integers. The i-th integer should be the number of the actor who should perform the i-th part. If there are multiple correct assignments, print any of them. If there is no correct assignment, print a single word "NO" (without the quotes).
standard output
PASSED
60a5c138887c0b208ee6e8dbfa21d5e2
train_002.jsonl
1418833800
You are an assistant director in a new musical play. The play consists of n musical parts, each part must be performed by exactly one actor. After the casting the director chose m actors who can take part in the play. Your task is to assign the parts to actors. However, there are several limitations.First, each actor has a certain voice range and there are some parts that he cannot sing. Formally, there are two integers for each actor, ci and di (ci ≤ di) — the pitch of the lowest and the highest note that the actor can sing. There also are two integers for each part — aj and bj (aj ≤ bj) — the pitch of the lowest and the highest notes that are present in the part. The i-th actor can perform the j-th part if and only if ci ≤ aj ≤ bj ≤ di, i.e. each note of the part is in the actor's voice range.According to the contract, the i-th actor can perform at most ki parts. Besides, you are allowed not to give any part to some actors (then they take part in crowd scenes).The rehearsal starts in two hours and you need to do the assignment quickly!
256 megabytes
import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.SortedSet; import java.util.Set; import java.util.Comparator; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.TreeSet; 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); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); Aria[] arias = new Aria[n]; for (int i = 0; i < n; i++) { arias[i] = new Aria(); arias[i].left = in.nextInt(); arias[i].right = in.nextInt(); arias[i].id = i; } int m = in.nextInt(); Singer[] singers = new Singer[m]; for (int i = 0; i < m; i++) { singers[i] = new Singer(); singers[i].left = in.nextInt(); singers[i].right = in.nextInt(); singers[i].capacity = in.nextInt(); singers[i].id = i; } Arrays.sort(singers, new Comparator<Singer>() { @Override public int compare(Singer o1, Singer o2) { return o1.left - o2.left; } }); Arrays.sort(arias, new Comparator<Aria>() { @Override public int compare(Aria o1, Aria o2) { return o1.left - o2.left; } }); int singerPtr = 0; TreeSet<Singer> availableSinger = new TreeSet<>(new Comparator<Singer>() { @Override public int compare(Singer o1, Singer o2) { int r = o1.right - o2.right; if (r == 0) { r = o1.id - o2.id; } return r; } }); int[] performer = new int[n]; for (Aria aria : arias) { while (singerPtr < m && singers[singerPtr].left <= aria.left) { availableSinger.add(singers[singerPtr]); singerPtr++; } Singer tmp = new Singer(); tmp.right = aria.right; tmp.id = -1; SortedSet<Singer> tail = availableSinger.tailSet(tmp); if (tail.isEmpty()) { out.println("NO"); return; } else { Singer candidate = tail.first(); performer[aria.id] = candidate.id; candidate.capacity--; if (candidate.capacity == 0) { availableSinger.remove(candidate); } } } out.println("YES"); for (int i = 0; i < n; i++) { out.print((performer[i] + 1) + " "); } } private static class Singer { int capacity; int left; int right; int id; } private static class Aria { int left; int right; int id; } } 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\n1 3\n2 4\n3 5\n2\n1 4 2\n2 5 1", "3\n1 3\n2 4\n3 5\n2\n1 3 2\n2 5 1"]
2 seconds
["YES\n1 1 2", "NO"]
null
Java 8
standard input
[ "greedy", "two pointers", "implementation", "sortings", "data structures" ]
7fdcfe1a45994e051345cb6462253ef7
The first line contains a single integer n — the number of parts in the play (1 ≤ n ≤ 105). Next n lines contain two space-separated integers each, aj and bj — the range of notes for the j-th part (1 ≤ aj ≤ bj ≤ 109). The next line contains a single integer m — the number of actors (1 ≤ m ≤ 105). Next m lines contain three space-separated integers each, ci, di and ki — the range of the i-th actor and the number of parts that he can perform (1 ≤ ci ≤ di ≤ 109, 1 ≤ ki ≤ 109).
2,100
If there is an assignment that meets all the criteria aboce, print a single word "YES" (without the quotes) in the first line. In the next line print n space-separated integers. The i-th integer should be the number of the actor who should perform the i-th part. If there are multiple correct assignments, print any of them. If there is no correct assignment, print a single word "NO" (without the quotes).
standard output
PASSED
110c7b278827f2a0b65870f64e0dd324
train_002.jsonl
1418833800
You are an assistant director in a new musical play. The play consists of n musical parts, each part must be performed by exactly one actor. After the casting the director chose m actors who can take part in the play. Your task is to assign the parts to actors. However, there are several limitations.First, each actor has a certain voice range and there are some parts that he cannot sing. Formally, there are two integers for each actor, ci and di (ci ≤ di) — the pitch of the lowest and the highest note that the actor can sing. There also are two integers for each part — aj and bj (aj ≤ bj) — the pitch of the lowest and the highest notes that are present in the part. The i-th actor can perform the j-th part if and only if ci ≤ aj ≤ bj ≤ di, i.e. each note of the part is in the actor's voice range.According to the contract, the i-th actor can perform at most ki parts. Besides, you are allowed not to give any part to some actors (then they take part in crowd scenes).The rehearsal starts in two hours and you need to do the assignment quickly!
256 megabytes
import java.util.Arrays; import java.util.TreeSet; import java.util.ArrayList; import java.io.InputStream; import java.io.InputStreamReader; import java.util.List; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Collections; import java.io.IOException; import java.util.StringTokenizer; /** * Built using CHelper plug-in * Actual solution is at the top * @author Igor Kraskevich */ 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); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { class Pair implements Comparable<Pair> { int first; int second; Pair(int first, int second) { this.first = first; this.second = second; } public int compareTo(Pair p) { if (first != p.first) return Integer.compare(first, p.first); return Integer.compare(second, p.second); } public boolean equals(Object o) { if (!(o instanceof Pair)) return false; Pair p = (Pair) o; return this.compareTo(p) == 0; } } class Event implements Comparable<Event> { int x; int type; int id; Event(int x, int type, int id) { this.x = x; this.type = type; this.id = id; } public int compareTo(Event e) { if (x != e.x) return Integer.compare(x, e.x); return Integer.compare(type, e.type); } } public void solve(int testNumber, FastScanner in, PrintWriter out) { int n = in.nextInt(); int[] a = new int[n]; int[] b = new int[n]; int[] res = new int[n]; Arrays.fill(res, -1); ArrayList<Event> e = new ArrayList<>(); for (int i = 0; i < n; i++) { a[i] = in.nextInt(); b[i] = in.nextInt(); e.add(new Event(a[i], 2, i)); } int m = in.nextInt(); int[] c = new int[m]; int[] d = new int[m]; int[] cnt = new int[m]; for (int i = 0; i < m; i++) { c[i] = in.nextInt(); d[i] = in.nextInt(); cnt[i] = in.nextInt(); e.add(new Event(c[i], 1, i)); e.add(new Event(d[i], 3, i)); } Collections.sort(e); TreeSet<Pair> have = new TreeSet<>(); for (Event event : e) { if (event.type == 1) { int i = event.id; have.add(new Pair(d[i], i)); } else if (event.type == 3) { int i = event.id; have.remove(new Pair(d[i], i)); } else { int i = event.id; int right = b[i]; Pair p = have.ceiling(new Pair(right, 0)); if (p == null) { out.println("NO"); return; } res[i] = p.second; cnt[p.second]--; if (cnt[p.second] == 0) have.remove(p); } } out.println("YES"); for (int i = 0; i < n; i++) out.print((res[i] + 1) + " "); out.println(); } } class FastScanner { private StringTokenizer tokenizer; private BufferedReader reader; public FastScanner(InputStream inputStream) { reader = new BufferedReader(new InputStreamReader(inputStream)); } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { String line = null; try { line = reader.readLine(); } catch (IOException e) { // ignore } if (line == null) return null; tokenizer = new StringTokenizer(line); } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["3\n1 3\n2 4\n3 5\n2\n1 4 2\n2 5 1", "3\n1 3\n2 4\n3 5\n2\n1 3 2\n2 5 1"]
2 seconds
["YES\n1 1 2", "NO"]
null
Java 8
standard input
[ "greedy", "two pointers", "implementation", "sortings", "data structures" ]
7fdcfe1a45994e051345cb6462253ef7
The first line contains a single integer n — the number of parts in the play (1 ≤ n ≤ 105). Next n lines contain two space-separated integers each, aj and bj — the range of notes for the j-th part (1 ≤ aj ≤ bj ≤ 109). The next line contains a single integer m — the number of actors (1 ≤ m ≤ 105). Next m lines contain three space-separated integers each, ci, di and ki — the range of the i-th actor and the number of parts that he can perform (1 ≤ ci ≤ di ≤ 109, 1 ≤ ki ≤ 109).
2,100
If there is an assignment that meets all the criteria aboce, print a single word "YES" (without the quotes) in the first line. In the next line print n space-separated integers. The i-th integer should be the number of the actor who should perform the i-th part. If there are multiple correct assignments, print any of them. If there is no correct assignment, print a single word "NO" (without the quotes).
standard output
PASSED
29b5ffed25580cce7d2cba76516b0bb0
train_002.jsonl
1418833800
You are an assistant director in a new musical play. The play consists of n musical parts, each part must be performed by exactly one actor. After the casting the director chose m actors who can take part in the play. Your task is to assign the parts to actors. However, there are several limitations.First, each actor has a certain voice range and there are some parts that he cannot sing. Formally, there are two integers for each actor, ci and di (ci ≤ di) — the pitch of the lowest and the highest note that the actor can sing. There also are two integers for each part — aj and bj (aj ≤ bj) — the pitch of the lowest and the highest notes that are present in the part. The i-th actor can perform the j-th part if and only if ci ≤ aj ≤ bj ≤ di, i.e. each note of the part is in the actor's voice range.According to the contract, the i-th actor can perform at most ki parts. Besides, you are allowed not to give any part to some actors (then they take part in crowd scenes).The rehearsal starts in two hours and you need to do the assignment quickly!
256 megabytes
import java.util.Arrays; import java.util.TreeSet; import java.io.InputStream; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Comparator; import java.io.IOException; import java.util.SortedSet; import java.util.Set; import java.util.StringTokenizer; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { static class Aria { int left; int right; int index; } static class Singer { int left; int right; int capacity; int id; } public void solve(int testNumber, InputReader in, PrintWriter out) { int numArias = in.nextInt(); Aria[] arias = new Aria[numArias]; for (int i = 0; i < numArias; ++i) { arias[i] = new Aria(); arias[i].left = in.nextInt(); arias[i].right = in.nextInt(); arias[i].index = i; } int numSingers = in.nextInt(); Singer[] singers = new Singer[numSingers]; for (int i = 0; i < numSingers; ++i) { singers[i] = new Singer(); singers[i].left = in.nextInt(); singers[i].right = in.nextInt(); singers[i].capacity = in.nextInt(); if (singers[i].capacity <= 0) throw new RuntimeException(); singers[i].id = i + 1; } Arrays.sort(arias, new Comparator<Aria>() { public int compare(Aria o1, Aria o2) { return o1.left - o2.left; } }); Arrays.sort(singers, new Comparator<Singer>() { public int compare(Singer o1, Singer o2) { return o1.left - o2.left; } }); int singerPtr = 0; TreeSet<Singer> available = new TreeSet<>(new Comparator<Singer>() { public int compare(Singer o1, Singer o2) { int z = o1.right - o2.right; if (z == 0) z = o1.id - o2.id; return z; } }); int[] performer = new int[numArias]; for (Aria aria : arias) { while (singerPtr < singers.length && singers[singerPtr].left <= aria.left) { available.add(singers[singerPtr++]); } Singer tmp = new Singer(); tmp.right = aria.right; tmp.id = -1; SortedSet<Singer> tail = available.tailSet(tmp); if (tail.isEmpty()) { out.println("NO"); return; } else { Singer who = tail.first(); performer[aria.index] = who.id; --who.capacity; if (who.capacity == 0) { available.remove(who); } } } out.println("YES"); for (int i = 0; i < numArias; ++i) { if (i > 0) out.print(" "); out.print(performer[i]); } out.println(); } } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["3\n1 3\n2 4\n3 5\n2\n1 4 2\n2 5 1", "3\n1 3\n2 4\n3 5\n2\n1 3 2\n2 5 1"]
2 seconds
["YES\n1 1 2", "NO"]
null
Java 8
standard input
[ "greedy", "two pointers", "implementation", "sortings", "data structures" ]
7fdcfe1a45994e051345cb6462253ef7
The first line contains a single integer n — the number of parts in the play (1 ≤ n ≤ 105). Next n lines contain two space-separated integers each, aj and bj — the range of notes for the j-th part (1 ≤ aj ≤ bj ≤ 109). The next line contains a single integer m — the number of actors (1 ≤ m ≤ 105). Next m lines contain three space-separated integers each, ci, di and ki — the range of the i-th actor and the number of parts that he can perform (1 ≤ ci ≤ di ≤ 109, 1 ≤ ki ≤ 109).
2,100
If there is an assignment that meets all the criteria aboce, print a single word "YES" (without the quotes) in the first line. In the next line print n space-separated integers. The i-th integer should be the number of the actor who should perform the i-th part. If there are multiple correct assignments, print any of them. If there is no correct assignment, print a single word "NO" (without the quotes).
standard output
PASSED
46a69e5c1aeae8fad2c2611eba745e9f
train_002.jsonl
1418833800
You are an assistant director in a new musical play. The play consists of n musical parts, each part must be performed by exactly one actor. After the casting the director chose m actors who can take part in the play. Your task is to assign the parts to actors. However, there are several limitations.First, each actor has a certain voice range and there are some parts that he cannot sing. Formally, there are two integers for each actor, ci and di (ci ≤ di) — the pitch of the lowest and the highest note that the actor can sing. There also are two integers for each part — aj and bj (aj ≤ bj) — the pitch of the lowest and the highest notes that are present in the part. The i-th actor can perform the j-th part if and only if ci ≤ aj ≤ bj ≤ di, i.e. each note of the part is in the actor's voice range.According to the contract, the i-th actor can perform at most ki parts. Besides, you are allowed not to give any part to some actors (then they take part in crowd scenes).The rehearsal starts in two hours and you need to do the assignment quickly!
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.Collections; import java.util.List; import java.util.Map; import java.util.TreeMap; public class Main { // public static void main(String[] args) throws IOException { // BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // String line = br.readLine(); // int[] A = new int[line.length()]; // if (line.charAt(0) != '(') { // System.out.println(-1); // return; // } // A[0] = 1; // for (int i = 1; i < line.length(); i++) { // int k = (line.charAt(i) == '(') ? 1 : -1; // A[i] = A[i-1] + k; // if (A[i] < 0) { // System.out.println(-1); // return; // } // } // int last = line.length()-1; // while (line.charAt(last) != '#') { // last--; // } // // if (A[line.length()-1] > A[last]) { // System.out.print(-1); // return; // } // int lastVal = 1 + A[line.length()-1]; // for (int i = last+1; i < line.length(); i++) { // if (A[i] - lastVal + 1 < 0) { // System.out.println(-1); // return; // } // } // for (int i = 0; i < last; i++) { // if (line.charAt(i) == '#') { // System.out.println(1); // } // } // System.out.println(lastVal); // } // public static void main(String[] args) throws IOException { // BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // String line = br.readLine(); // String[] values = line.split(" "); // int a = Integer.parseInt(values[0]); // int b = Integer.parseInt(values[1]); // int c = a - b; // if (c == 0) { // System.out.println("infinity"); // return; // } // int counter = 0; // for (int i = 1; i <= Math.sqrt(c); i++) { // if (c % i == 0) { // if (i > b) { // counter++; // } // if (c / i > b && c / i != i) { // counter++; // } // } // } // System.out.println(counter); // } // public static int binsearch(int a, int[] B) // { // int start = 0; // int end = B.length-1; // while (start < end) { // // int m = (start + end) / 2; // if (B[m] < a) { // start = m+1; // } else { // end = m; // } // } // if (B[start] < a) { // return B.length; // } else { // return start; // } // } // // public static void main(String[] args) throws IOException { // BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // String line = br.readLine(); // int n = Integer.parseInt(line); // line = br.readLine(); // String[] values = line.split(" "); // int[] A = new int[n]; // for (int i = 0; i < n; i++) { // A[i] = Integer.parseInt(values[i]); // } // line = br.readLine(); // int m = Integer.parseInt(line); // line = br.readLine(); // values = line.split(" "); // int[] B = new int[m]; // for (int i = 0; i < m; i++) { // B[i] = Integer.parseInt(values[i]); // } // final int POINT_1 = 2; // final int POINT_2 = 3; // Arrays.sort(A); // Arrays.sort(B); // int a = POINT_1*n; // int b = POINT_1*m; // int maxDiff = a-b; // for (int i = 0; i < n; i++) { // if ((i > 0 && A[i] != A[i-1]) || (i == 0)) { // int index = binsearch(A[i], B); // int tmpA = (n-i)*POINT_2 + i*POINT_1; // int tmpB = (m-index)*POINT_2 + index*POINT_1; // int tmpDiff = tmpA - tmpB; // if ((tmpDiff > maxDiff) || (tmpDiff == maxDiff && tmpA > a)) { // maxDiff = tmpDiff; // a = (n-i)*POINT_2 + i*POINT_1; // b = (m-index)*POINT_2 + index*POINT_1; // } // } // } // System.out.print(a + ":" + b); // } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); ArrayList<Integer> xs = new ArrayList<Integer>(); ArrayList<Integer> ys = new ArrayList<Integer>(); ArrayList<Integer> ks = new ArrayList<Integer>(); int n = 0; int m = 0; for (int k = 0; k < 2;k++) { String line = br.readLine(); m = Integer.parseInt(line); for (int i = 0; i < m; i++) { line = br.readLine(); String[] values = line.split(" "); xs.add(Integer.parseInt(values[0])); ys.add(Integer.parseInt(values[1])); if (k == 1) { ks.add(Integer.parseInt(values[2])); } } if (k == 0) { n = m; } } TreeMap<Integer, ArrayList<Integer>> xMap = new TreeMap<Integer, ArrayList<Integer>>(); TreeMap<Integer, ArrayList<Integer>> yMap = new TreeMap<Integer, ArrayList<Integer>>(); for (int i = 0; i < xs.size(); i++) { ArrayList<Integer> list = new ArrayList<Integer>(); if (xMap.containsKey(xs.get(i))) { list = xMap.get(xs.get(i)); } list.add(i); xMap.put(xs.get(i), list); } boolean success = true; int[] distribution = new int[n]; for (Map.Entry<Integer, ArrayList<Integer>> me : xMap.entrySet()) { // System.out.println("mapX " + me.getKey() + " " + me.getValue()); ArrayList<Integer> tmpParts = new ArrayList<Integer>(); ArrayList<Integer> list = me.getValue(); for (Integer i : list) { if (i >= n) { ArrayList<Integer> tmp = new ArrayList<Integer>(); if (yMap.containsKey(ys.get(i))) { tmp = yMap.get(ys.get(i)); } tmp.add(i); yMap.put(ys.get(i), tmp); } else { tmpParts.add(i); } } for (Integer i : tmpParts) { Object keyGe = yMap.ceilingKey(ys.get(i)); if (keyGe == null) { success = false; break; } else { // for (Map.Entry<Integer, ArrayList<Integer>> me1 : yMap.entrySet()) { // System.out.println("map " + me1.getKey() + " " + me1.getValue()); // } // System.out.println(keyGe); ArrayList<Integer> result = yMap.get(keyGe); // System.out.println(Arrays.toString(result.toArray())); distribution[i] = result.get(0)+1-n; ks.set(result.get(0)-n, ks.get(result.get(0)-n) - 1); if (ks.get(result.get(0)-n) == 0) { result.remove(0); if (result.size() == 0) { // System.out.println("here"); yMap.remove(keyGe); } } } } } if (success) { System.out.println("YES"); for (int i = 0; i < n; i++) { System.out.print(distribution[i] + " "); } } else { System.out.println("NO"); } } }
Java
["3\n1 3\n2 4\n3 5\n2\n1 4 2\n2 5 1", "3\n1 3\n2 4\n3 5\n2\n1 3 2\n2 5 1"]
2 seconds
["YES\n1 1 2", "NO"]
null
Java 6
standard input
[ "greedy", "two pointers", "implementation", "sortings", "data structures" ]
7fdcfe1a45994e051345cb6462253ef7
The first line contains a single integer n — the number of parts in the play (1 ≤ n ≤ 105). Next n lines contain two space-separated integers each, aj and bj — the range of notes for the j-th part (1 ≤ aj ≤ bj ≤ 109). The next line contains a single integer m — the number of actors (1 ≤ m ≤ 105). Next m lines contain three space-separated integers each, ci, di and ki — the range of the i-th actor and the number of parts that he can perform (1 ≤ ci ≤ di ≤ 109, 1 ≤ ki ≤ 109).
2,100
If there is an assignment that meets all the criteria aboce, print a single word "YES" (without the quotes) in the first line. In the next line print n space-separated integers. The i-th integer should be the number of the actor who should perform the i-th part. If there are multiple correct assignments, print any of them. If there is no correct assignment, print a single word "NO" (without the quotes).
standard output
PASSED
5dccfbf151e0d932d7e30c42587ad9bc
train_002.jsonl
1418833800
You are an assistant director in a new musical play. The play consists of n musical parts, each part must be performed by exactly one actor. After the casting the director chose m actors who can take part in the play. Your task is to assign the parts to actors. However, there are several limitations.First, each actor has a certain voice range and there are some parts that he cannot sing. Formally, there are two integers for each actor, ci and di (ci ≤ di) — the pitch of the lowest and the highest note that the actor can sing. There also are two integers for each part — aj and bj (aj ≤ bj) — the pitch of the lowest and the highest notes that are present in the part. The i-th actor can perform the j-th part if and only if ci ≤ aj ≤ bj ≤ di, i.e. each note of the part is in the actor's voice range.According to the contract, the i-th actor can perform at most ki parts. Besides, you are allowed not to give any part to some actors (then they take part in crowd scenes).The rehearsal starts in two hours and you need to do the assignment quickly!
256 megabytes
import java.util.List; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.TreeMap; import java.util.ArrayList; import java.io.PrintStream; import java.io.BufferedReader; import java.util.Comparator; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.util.Collections; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author bdepwgjqet */ 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); C solver = new C(); solver.solve(1, in, out); out.close(); } } class C { int n, m; public class TimeSegment { int l; int r; int id; TimeSegment(int l, int r, int id) { this.l = l; this.r = r; this.id = id; } } public class Performer { TimeSegment timeSegment; int count; Performer(TimeSegment timeSegment, int count) { this.timeSegment = timeSegment; this.count = count; } } List<TimeSegment> performTimeSegment; List<Performer> performers; TreeMap<Performer, Integer> performersQueue; int[] result; int[] useCount; List<TimeSegment> tests; List<Performer> testp; public void solve(int testNumber, InputReader in, PrintWriter out) { n = in.nextInt(); tests = new ArrayList<TimeSegment>(); testp = new ArrayList<Performer>(); performTimeSegment = new ArrayList<TimeSegment>(); result = new int[n]; for (int i = 0; i < n; i++) { int x = in.nextInt(); int y = in.nextInt(); performTimeSegment.add(new TimeSegment(x, y, i + 1)); tests.add(new TimeSegment(x, y, i + 1)); } m = in.nextInt(); performers = new ArrayList<Performer>(); for (int i = 0; i < m; i++) { int x = in.nextInt(); int y = in.nextInt(); int k = in.nextInt(); performers.add(new Performer(new TimeSegment(x, y, -i - 1), k)); testp.add(new Performer(new TimeSegment(x, y, i + 1), k)); } Collections.sort(performTimeSegment, new Comparator<TimeSegment>() { @Override public int compare(TimeSegment o1, TimeSegment o2) { if (o1.l == o2.l) { return o2.r - o1.r; } return o1.l - o2.l; } }); Collections.sort(performers, new Comparator<Performer>() { @Override public int compare(Performer o1, Performer o2) { if (o1.timeSegment.l == o2.timeSegment.l) { return o2.timeSegment.r - o1.timeSegment.r; } return o1.timeSegment.l - o2.timeSegment.l; } }); performersQueue = new TreeMap<Performer, Integer>(new Comparator<Performer>() { @Override public int compare(Performer o1, Performer o2) { if (o1.timeSegment.r == o2.timeSegment.r) { if(o1.count == o2.count) { if(o1.timeSegment.l == o2.timeSegment.l) { return o2.timeSegment.id - o1.timeSegment.id; } return o2.timeSegment.l - o1.timeSegment.l; } return o1.count - o2.count; } return o1.timeSegment.r - o2.timeSegment.r; } }); int performerIndex = 0; boolean findSolution = true; for (int i = 0; i < performTimeSegment.size(); i++) { TimeSegment timeSegment = performTimeSegment.get(i); for (; performerIndex < performers.size(); performerIndex++) { Performer performer = performers.get(performerIndex); if (performer.timeSegment.l <= timeSegment.l) { if (performersQueue.containsKey(performer)) { performersQueue.put(performer, performersQueue.get(performer) + 1); } else { performersQueue.put(performer, 1); } } else { break; } } int id = -1; Performer key = performersQueue.ceilingKey(new Performer(timeSegment, 1)); if (key != null) { Integer value = performersQueue.get(key); if (value.intValue() <= 0) { findSolution = false; break; } performersQueue.remove(key); if (key.count > 1) { key.count--; performersQueue.put(key, 1); } id = -key.timeSegment.id; } if (id == -1) { findSolution = false; break; } result[timeSegment.id - 1] = id; } if (findSolution) { useCount = new int[m]; Arrays.fill(useCount,0); for (int i = 0; i < n; i++) { int l = tests.get(i).l; int r = tests.get(i).r; int ll = testp.get(result[i] - 1).timeSegment.l; int rr = testp.get(result[i] - 1).timeSegment.r; useCount[result[i]-1]++; if (ll > l || rr < r) { System.out.println(i + " " + l + " " + r + " " + ll + " " + rr); findSolution = false; } } for(int i=0; i<m; i++) { if(useCount[i] > testp.get(i).count) { System.out.println(i + " " + useCount[i] + " " + testp.get(i).count); findSolution = false; } } } if (findSolution) { System.out.println("YES"); for (int i = 0; i < n; i++) { System.out.print(result[i]); if (i == n - 1) { System.out.println(""); } else { System.out.print(" "); } } } else { System.out.println("NO"); } } } class InputReader { private final BufferedReader bufferedReader; private StringTokenizer stringTokenizer; public InputReader(InputStream in) { bufferedReader = new BufferedReader(new InputStreamReader(in)); stringTokenizer = null; } public String nextLine() { try { return bufferedReader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } public String nextBlock() { while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) { stringTokenizer = new StringTokenizer(nextLine()); } return stringTokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(nextBlock()); } public double nextDouble() { return Double.parseDouble(nextBlock()); } public long nextLong() { return Long.parseLong(nextBlock()); } }
Java
["3\n1 3\n2 4\n3 5\n2\n1 4 2\n2 5 1", "3\n1 3\n2 4\n3 5\n2\n1 3 2\n2 5 1"]
2 seconds
["YES\n1 1 2", "NO"]
null
Java 6
standard input
[ "greedy", "two pointers", "implementation", "sortings", "data structures" ]
7fdcfe1a45994e051345cb6462253ef7
The first line contains a single integer n — the number of parts in the play (1 ≤ n ≤ 105). Next n lines contain two space-separated integers each, aj and bj — the range of notes for the j-th part (1 ≤ aj ≤ bj ≤ 109). The next line contains a single integer m — the number of actors (1 ≤ m ≤ 105). Next m lines contain three space-separated integers each, ci, di and ki — the range of the i-th actor and the number of parts that he can perform (1 ≤ ci ≤ di ≤ 109, 1 ≤ ki ≤ 109).
2,100
If there is an assignment that meets all the criteria aboce, print a single word "YES" (without the quotes) in the first line. In the next line print n space-separated integers. The i-th integer should be the number of the actor who should perform the i-th part. If there are multiple correct assignments, print any of them. If there is no correct assignment, print a single word "NO" (without the quotes).
standard output
PASSED
f7e8188de3b1eebfdd0370d386804fa4
train_002.jsonl
1418833800
You are an assistant director in a new musical play. The play consists of n musical parts, each part must be performed by exactly one actor. After the casting the director chose m actors who can take part in the play. Your task is to assign the parts to actors. However, there are several limitations.First, each actor has a certain voice range and there are some parts that he cannot sing. Formally, there are two integers for each actor, ci and di (ci ≤ di) — the pitch of the lowest and the highest note that the actor can sing. There also are two integers for each part — aj and bj (aj ≤ bj) — the pitch of the lowest and the highest notes that are present in the part. The i-th actor can perform the j-th part if and only if ci ≤ aj ≤ bj ≤ di, i.e. each note of the part is in the actor's voice range.According to the contract, the i-th actor can perform at most ki parts. Besides, you are allowed not to give any part to some actors (then they take part in crowd scenes).The rehearsal starts in two hours and you need to do the assignment quickly!
256 megabytes
import java.util.List; import java.io.IOException; import java.io.InputStreamReader; import java.util.TreeMap; import java.util.ArrayList; import java.io.PrintStream; import java.io.BufferedReader; import java.util.Comparator; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.util.Collections; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author bdepwgjqet */ 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); C solver = new C(); solver.solve(1, in, out); out.close(); } } class C { int n, m; public class TimeSegment { int l; int r; int id; TimeSegment(int l, int r, int id) { this.l = l; this.r = r; this.id = id; } } public class Performer { TimeSegment timeSegment; int count; Performer(TimeSegment timeSegment, int count) { this.timeSegment = timeSegment; this.count = count; } } List<TimeSegment> performTimeSegment; List<Performer> performers; TreeMap<Performer, Integer> performersQueue; int[] result; public void solve(int testNumber, InputReader in, PrintWriter out) { n = in.nextInt(); performTimeSegment = new ArrayList<TimeSegment>(); result = new int[n]; for (int i = 0; i < n; i++) { int x = in.nextInt(); int y = in.nextInt(); performTimeSegment.add(new TimeSegment(x, y, i + 1)); } m = in.nextInt(); performers = new ArrayList<Performer>(); for (int i = 0; i < m; i++) { int x = in.nextInt(); int y = in.nextInt(); int k = in.nextInt(); performers.add(new Performer(new TimeSegment(x, y, -i - 1), k)); } Collections.sort(performTimeSegment, new Comparator<TimeSegment>() { @Override public int compare(TimeSegment o1, TimeSegment o2) { if (o1.l == o2.l) { return o2.r - o1.r; } return o1.l - o2.l; } }); Collections.sort(performers, new Comparator<Performer>() { @Override public int compare(Performer o1, Performer o2) { if (o1.timeSegment.l == o2.timeSegment.l) { return o2.timeSegment.r - o1.timeSegment.r; } return o1.timeSegment.l - o2.timeSegment.l; } }); performersQueue = new TreeMap<Performer, Integer>(new Comparator<Performer>() { @Override public int compare(Performer o1, Performer o2) { if (o1.timeSegment.r == o2.timeSegment.r) { if (o1.count == o2.count) { if (o1.timeSegment.l == o2.timeSegment.l) { return o2.timeSegment.id - o1.timeSegment.id; } return o2.timeSegment.l - o1.timeSegment.l; } return o1.count - o2.count; } return o1.timeSegment.r - o2.timeSegment.r; } }); int performerIndex = 0; boolean findSolution = true; for (int i = 0; i < performTimeSegment.size(); i++) { TimeSegment timeSegment = performTimeSegment.get(i); for (; performerIndex < performers.size(); performerIndex++) { Performer performer = performers.get(performerIndex); if (performer.timeSegment.l <= timeSegment.l) { if (performersQueue.containsKey(performer)) { performersQueue.put(performer, performersQueue.get(performer) + 1); } else { performersQueue.put(performer, 1); } } else { break; } } int id = -1; Performer key = performersQueue.ceilingKey(new Performer(timeSegment, 1)); if (key != null) { Integer value = performersQueue.get(key); if (value.intValue() <= 0) { findSolution = false; break; } performersQueue.remove(key); if (key.count > 1) { key.count--; performersQueue.put(key, 1); } id = -key.timeSegment.id; } if (id == -1) { findSolution = false; break; } result[timeSegment.id - 1] = id; } if (findSolution) { System.out.println("YES"); for (int i = 0; i < n; i++) { System.out.print(result[i]); if (i == n - 1) { System.out.println(""); } else { System.out.print(" "); } } } else { System.out.println("NO"); } } } class InputReader { private final BufferedReader bufferedReader; private StringTokenizer stringTokenizer; public InputReader(InputStream in) { bufferedReader = new BufferedReader(new InputStreamReader(in)); stringTokenizer = null; } public String nextLine() { try { return bufferedReader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } public String nextBlock() { while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) { stringTokenizer = new StringTokenizer(nextLine()); } return stringTokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(nextBlock()); } public double nextDouble() { return Double.parseDouble(nextBlock()); } public long nextLong() { return Long.parseLong(nextBlock()); } }
Java
["3\n1 3\n2 4\n3 5\n2\n1 4 2\n2 5 1", "3\n1 3\n2 4\n3 5\n2\n1 3 2\n2 5 1"]
2 seconds
["YES\n1 1 2", "NO"]
null
Java 6
standard input
[ "greedy", "two pointers", "implementation", "sortings", "data structures" ]
7fdcfe1a45994e051345cb6462253ef7
The first line contains a single integer n — the number of parts in the play (1 ≤ n ≤ 105). Next n lines contain two space-separated integers each, aj and bj — the range of notes for the j-th part (1 ≤ aj ≤ bj ≤ 109). The next line contains a single integer m — the number of actors (1 ≤ m ≤ 105). Next m lines contain three space-separated integers each, ci, di and ki — the range of the i-th actor and the number of parts that he can perform (1 ≤ ci ≤ di ≤ 109, 1 ≤ ki ≤ 109).
2,100
If there is an assignment that meets all the criteria aboce, print a single word "YES" (without the quotes) in the first line. In the next line print n space-separated integers. The i-th integer should be the number of the actor who should perform the i-th part. If there are multiple correct assignments, print any of them. If there is no correct assignment, print a single word "NO" (without the quotes).
standard output
PASSED
651f4d51c1c38723d5ad7f7e6f9a4b30
train_002.jsonl
1418833800
You are an assistant director in a new musical play. The play consists of n musical parts, each part must be performed by exactly one actor. After the casting the director chose m actors who can take part in the play. Your task is to assign the parts to actors. However, there are several limitations.First, each actor has a certain voice range and there are some parts that he cannot sing. Formally, there are two integers for each actor, ci and di (ci ≤ di) — the pitch of the lowest and the highest note that the actor can sing. There also are two integers for each part — aj and bj (aj ≤ bj) — the pitch of the lowest and the highest notes that are present in the part. The i-th actor can perform the j-th part if and only if ci ≤ aj ≤ bj ≤ di, i.e. each note of the part is in the actor's voice range.According to the contract, the i-th actor can perform at most ki parts. Besides, you are allowed not to give any part to some actors (then they take part in crowd scenes).The rehearsal starts in two hours and you need to do the assignment quickly!
256 megabytes
/* * * @author Mukesh Singh * */ /* Finding_the_Minimum_Window_in_S_which_Contains_All_Elements_from_T */ import java.io.*; import java.util.*; import java.text.DecimalFormat; @SuppressWarnings("unchecked") public class AB { //solve test cases void solve() throws Exception { LinkedList<PP> ls = new LinkedList<PP>(); int n = in.nextInt() ; for(int i= 0 ; i < n ; i++) { int a = in.nextInt(); int b = in.nextInt(); ls.add(new PP(i+1,a,b,0,-1)); } n = in.nextInt() ; for(int i= 0 ; i < n ; i++) { int a = in.nextInt(); int b = in.nextInt(); int k = in.nextInt(); ls.add(new PP(i+1,a,b,1,k)); } Collections.sort(ls,new Comparator<PP>(){ public int compare(PP p1 , PP p2) { if(p1.a < p2.a) return -1 ; else if(p1.a==p2.a) return p2.actor - p1.actor ; return 1 ; } }); TreeSet<PP> ts = new TreeSet<PP>(new Comparator<PP>(){ public int compare(PP p1 , PP p2) { if(p1.actor == p2.actor && p1.b != p2.b ) return p1.b - p2.b ; if(p1.actor == p2.actor && p1.b == p2.b && p1.a != p2.a) return p2.a - p1.a ; if(p1.actor == p2.actor && p1.b == p2.b && p1.a == p2.a) return p1.id - p2.id ; if(p1.actor != p2.actor && p1.b != p2.b ) return p1.b - p2.b ; if(p1.actor != p2.actor && p1.b == p2.b ) return p2.a - p1.a ; return 0; } }); LinkedList<Node> ans = new LinkedList<Node>(); for( PP pp: ls) { if(pp.actor==1) { ts.add(pp); } else { PP p1 = ts.ceiling(pp); //System.out.println("part "+pp.a+" "+pp.b); //System.out.println("act "+p1.a+" "+p1.b); if(p1==null) { System.out.println("NO"); return ; } p1.k = p1.k -1 ; ans.addLast(new Node(pp.id,p1.id)); if(p1.k==0) ts.remove(p1); } } System.out.println("YES"); Collections.sort(ans,new Comparator<Node>(){ public int compare(Node p1 , Node p2) { return p1.part-p2.part ; } }); for(Node aaa:ans) System.out.print(aaa.actor+" "); System.out.println(); } //@ main function public static void main(String[] args) throws Exception { new AB(); } InputReader in; PrintStream out ; DecimalFormat df ; AB() { try { File defaultInput = new File("file.in"); if (defaultInput.exists()) in = new InputReader("file.in"); else in = new InputReader(); defaultInput = new File("file.out"); if (defaultInput.exists()) out = new PrintStream(new FileOutputStream("file.out")); else out = new PrintStream(System.out); df = new DecimalFormat("######0.00"); solve(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(261); } } class InputReader { BufferedReader reader; StringTokenizer tokenizer; InputReader() { reader = new BufferedReader(new InputStreamReader(System.in)); } InputReader(String fileName) throws FileNotFoundException { reader = new BufferedReader(new FileReader(new File(fileName))); } String readLine() throws IOException { return reader.readLine(); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(readLine()); return tokenizer.nextToken(); } boolean hasMoreTokens() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { String s = readLine(); if (s == null) return false; tokenizer = new StringTokenizer(s); } return true; } int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextToken()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(nextToken()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextToken()); } } } class PP { int id ; int a ; int b ; int actor ; int k ; PP(int ii ,int i , int j , int kk ,int l) { id = ii ; a = i ; b = j ; actor= kk ; k = l ; } } class Node { int part ; int actor ; Node(int a , int b) { part = a ; actor = b ; } }
Java
["3\n1 3\n2 4\n3 5\n2\n1 4 2\n2 5 1", "3\n1 3\n2 4\n3 5\n2\n1 3 2\n2 5 1"]
2 seconds
["YES\n1 1 2", "NO"]
null
Java 6
standard input
[ "greedy", "two pointers", "implementation", "sortings", "data structures" ]
7fdcfe1a45994e051345cb6462253ef7
The first line contains a single integer n — the number of parts in the play (1 ≤ n ≤ 105). Next n lines contain two space-separated integers each, aj and bj — the range of notes for the j-th part (1 ≤ aj ≤ bj ≤ 109). The next line contains a single integer m — the number of actors (1 ≤ m ≤ 105). Next m lines contain three space-separated integers each, ci, di and ki — the range of the i-th actor and the number of parts that he can perform (1 ≤ ci ≤ di ≤ 109, 1 ≤ ki ≤ 109).
2,100
If there is an assignment that meets all the criteria aboce, print a single word "YES" (without the quotes) in the first line. In the next line print n space-separated integers. The i-th integer should be the number of the actor who should perform the i-th part. If there are multiple correct assignments, print any of them. If there is no correct assignment, print a single word "NO" (without the quotes).
standard output
PASSED
6b888cf682469a9e78d0c2a6f330649e
train_002.jsonl
1418833800
You are an assistant director in a new musical play. The play consists of n musical parts, each part must be performed by exactly one actor. After the casting the director chose m actors who can take part in the play. Your task is to assign the parts to actors. However, there are several limitations.First, each actor has a certain voice range and there are some parts that he cannot sing. Formally, there are two integers for each actor, ci and di (ci ≤ di) — the pitch of the lowest and the highest note that the actor can sing. There also are two integers for each part — aj and bj (aj ≤ bj) — the pitch of the lowest and the highest notes that are present in the part. The i-th actor can perform the j-th part if and only if ci ≤ aj ≤ bj ≤ di, i.e. each note of the part is in the actor's voice range.According to the contract, the i-th actor can perform at most ki parts. Besides, you are allowed not to give any part to some actors (then they take part in crowd scenes).The rehearsal starts in two hours and you need to do the assignment quickly!
256 megabytes
import java.util.Arrays; import java.util.TreeSet; import java.io.InputStream; import java.io.InputStreamReader; import java.io.BufferedReader; import java.util.List; import java.math.BigInteger; import java.io.PrintStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Comparator; import java.io.IOException; import java.util.StringTokenizer; /** * Built using CHelper plug-in * Actual solution is at the top * @author shu_mj @ http://shu-mj.com */ 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); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { Scanner in; PrintWriter out; public void solve(int testNumber, Scanner in, PrintWriter out) { this.in = in; this.out = out; run(); } void run() { int n = in.nextInt(); P[] ps = new P[n]; for (int i = 0; i < n; i++) { ps[i] = new P(in.nextInt(), in.nextInt(), 0, i); } int m = in.nextInt(); P[] pe = new P[m]; for (int i = 0; i < m; i++) { pe[i] = new P(in.nextInt(), in.nextInt(), in.nextInt(), i); } Algo.sort(ps, new Comparator<P>() { public int compare(P o1, P o2) { if (o1.x != o2.x) return o1.x - o2.x; return o1.y - o2.y; } }); TreeSet<P> set = new TreeSet<P>(new Comparator<P>() { public int compare(P o1, P o2) { if (o1.y != o2.y) return o1.y - o2.y; return o1.id - o2.id; } }); Algo.sort(pe, new Comparator<P>() { public int compare(P o1, P o2) { return o1.x - o2.x; } }); int e = 0; for (P p : ps) { while (e < m && pe[e].x <= p.x) { set.add(pe[e]); e++; } P pp = new P(p.x, p.y, -1, 0); P s = set.ceiling(pp); if (s == null) { out.println("NO"); return ; } p.c = s.id; s.c--; if (s.c == 0) set.remove(s); } Algo.sort(ps, new Comparator<P>() { public int compare(P o1, P o2) { return o1.id - o2.id; } }); out.println("YES"); for (P p : ps) out.print((p.c + 1) + " "); out.println(); } class P { int x; int y; int c; int id; public P(int x, int y, int c, int id) { this.x = x; this.y = y; this.c = c; this.id = id; } } } class Scanner { BufferedReader br; StringTokenizer st; public Scanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); eat(""); } private void eat(String s) { st = new StringTokenizer(s); } public String nextLine() { try { return br.readLine(); } catch (IOException e) { return null; } } public boolean hasNext() { while (!st.hasMoreTokens()) { String s = nextLine(); if (s == null) return false; eat(s); } return true; } public String next() { hasNext(); return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } class Algo { public static <T> void sort(T[] ts, Comparator<? super T> cmp) { sort(ts, 0, ts.length, cmp); } public static <T> void sort(T[] ts, int b, int e, Comparator<? super T> cmp) { sort(ts, ts.clone(), b, e, cmp); } private static <T> void sort(T[] ts, T[] cs, int b, int e, Comparator<? super T> cmp) { if (e - b > 1) { int m = (b + e) / 2; sort(ts, cs, b, m, cmp); sort(ts, cs, m, e, cmp); for (int i = b, j = m, k = b; k < e; ) { if (j >= e || i < m && cmp.compare(ts[i], ts[j]) < 0) cs[k++] = ts[i++]; else cs[k++] = ts[j++]; } System.arraycopy(cs, b, ts, b, e - b); } } }
Java
["3\n1 3\n2 4\n3 5\n2\n1 4 2\n2 5 1", "3\n1 3\n2 4\n3 5\n2\n1 3 2\n2 5 1"]
2 seconds
["YES\n1 1 2", "NO"]
null
Java 6
standard input
[ "greedy", "two pointers", "implementation", "sortings", "data structures" ]
7fdcfe1a45994e051345cb6462253ef7
The first line contains a single integer n — the number of parts in the play (1 ≤ n ≤ 105). Next n lines contain two space-separated integers each, aj and bj — the range of notes for the j-th part (1 ≤ aj ≤ bj ≤ 109). The next line contains a single integer m — the number of actors (1 ≤ m ≤ 105). Next m lines contain three space-separated integers each, ci, di and ki — the range of the i-th actor and the number of parts that he can perform (1 ≤ ci ≤ di ≤ 109, 1 ≤ ki ≤ 109).
2,100
If there is an assignment that meets all the criteria aboce, print a single word "YES" (without the quotes) in the first line. In the next line print n space-separated integers. The i-th integer should be the number of the actor who should perform the i-th part. If there are multiple correct assignments, print any of them. If there is no correct assignment, print a single word "NO" (without the quotes).
standard output
PASSED
271c56be7b348288d1c0f744a61dfd5c
train_002.jsonl
1267963200
This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest.
64 megabytes
import java.util.*; import java.io.*; public class d3 { public static int[] str; public static int n; public static IntervalTree it1, it2; public static void main(String[] Args) { Scanner sc = new Scanner(System.in); String s = sc.next(); n = s.length(); str = new int[n]; it1 = new IntervalTree(n); it2 = new IntervalTree(n); ArrayList<Option> poss = new ArrayList<Option>(); for (int i = 0; i < n; i++) { if (s.charAt(i) == '(') { str[i] = 1; it1.add(1, 0, i); it2.add(1, i, n - 1); } else if (s.charAt(i) == ')') { str[i] = -1; it1.add(-1, 0, i); it2.add(-1, i, n - 1); } else { it1.add(-1, 0, i); it2.add(1, i, n - 1); poss.add(new Option(i,sc.nextInt(), sc.nextInt())); } } if ((n & 1) == 1 || !canValid()) { System.out.println(-1); return; } Collections.sort(poss); long ans = 0; for (Option o : poss) { set(o.ind, 1); str[o.ind] = 1; ans += o.a; if (!canValid()) { set(o.ind, -1); str[o.ind] = -1; ans += (o.b - o.a); } } PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); out.println(ans); for (int i = 0; i < n; i++) out.print((str[i] == 1 ? "(" : ")")); out.println(); out.close(); } public static void set(int ind, int value) { // Check if value needs to be unset if (str[ind] != 0) { // it1 stores the front values it1.add(-str[ind], 0, ind); it2.add(-str[ind], ind, n - 1); } else { it1.add(1, 0, ind); it2.add(-1, ind, n - 1); } it1.add(value, 0, ind); it2.add(value, ind, n - 1); } public static int oo = 987654321; public static class IntervalTree { int min, max, carry, st, en; IntervalTree child1, child2; IntervalTree(int n) { st = 0; en = n - 1; min = 0; max = 0; carry = 0; if (en == st) return; int mid = (n - 1) / 2; child1 = new IntervalTree(st, mid); child2 = new IntervalTree(mid + 1, en); } IntervalTree(int s, int e) { st = s; en = e; min = 0; max = 0; carry = 0; if (en == st) return; int mid = (s + e) / 2; //System.out.println(s +" " +e +" " +mid); child1 = new IntervalTree(st, mid); child2 = new IntervalTree(mid + 1, en); } int getMin(int lo, int hi) { if (lo > en || hi < st) return oo; if (lo <= st && hi >= en) return min + carry; prop(); int p1 = child1.getMin(lo, hi); int p2 = child2.getMin(lo, hi); if (p1 < p2) return p1; return p2; } int getMax(int lo, int hi) { if (lo > en || hi < st) return -oo; if (lo <= st && hi >= en) return max + carry; prop(); int p1 = child1.getMax(lo, hi); int p2 = child2.getMax(lo, hi); if (p1 > p2) return p1; return p2; } void prop() { child1.push(carry); child2.push(carry); min += carry; max += carry; carry = 0; } void add(int val, int lo, int hi) { if (lo > en || hi < st) return; if (lo <= st && hi >= en){ carry += val; return; } prop(); child1.add(val, lo, hi); child2.add(val, lo, hi); min = child1.min + child1.carry; if (child2.min + child2.carry < min) min = child2.min + child2.carry; max = child1.max + child1.carry; if (child2.max + child2.carry > max) max = child2.max + child2.carry; } void push(int val) { carry += val; } } public static boolean canValid() { return (it1.getMax(0, n - 1) <= 0 && it2.getMin(0, n - 1) >= 0); } public static class Option implements Comparable<Option> { int a; int b; int ind; Option(int ii, int aa, int bb) { ind = ii; a = aa; b = bb; } public int compareTo(Option o) { return (a - b) - (o.a - o.b); } } }
Java
["(??)\n1 2\n2 8"]
1 second
["4\n()()"]
null
Java 8
standard input
[ "greedy" ]
970cd8ce0cf7214b7f2be337990557c9
The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai,  bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one.
2,600
Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them.
standard output
PASSED
53b988172f3d1fda51e8e0ff1d658951
train_002.jsonl
1267963200
This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest.
64 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.PriorityQueue; public class LeastCostBracketSequence { // A class to keep track of the closing brackets placed, // in case they need to be switched. It will be used in // a priority queue based on the difference between open and close. // so when a bracket needs to be switched the one with the best price // gain is selected. public static class Price implements Comparable<Price> { public Integer index; public Integer open; public Integer close; public Integer diff; public Price(int i, int o, int c) { index = i; open = o; close = c; diff = c - o; } @Override public int compareTo(Price arg0) { return arg0.diff.compareTo(this.diff); } } public static void main(String args[]) throws IOException { BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); char[] sequence = console.readLine().toCharArray(); if(sequence[0] == ')' || sequence[sequence.length-1] == '(' || sequence.length%2 == 1) { System.out.println("-1"); } else { int balance = 0; long totalCost = 0; PriorityQueue<Price> closers = new PriorityQueue<Price>(); // main loop, checks existing brackets and adjusts balance // accordingly for(int n=0; n<sequence.length; n++) { if(sequence[n] == '(') balance++; else if(sequence[n] == ')') balance--; else { // it's a '?' so we can get the corresponding // bracket prices String[] tempPrices = console.readLine().split(" "); // always add a closing bracket, we'll check the balance after sequence[n] = ')'; balance--; totalCost += Integer.parseInt(tempPrices[1]); // now a Price object needs to be added to the priority queue so // we can switch this cell if we need to later. closers.add(new Price(n, Integer.parseInt(tempPrices[0]), Integer.parseInt(tempPrices[1]))); } // Now check the balance, if it's off, switch the cell that will lower the totalCost the most if(balance < 0) { if(balance == -1 && closers.size() > 0) { Price bestSwitch = closers.poll(); sequence[bestSwitch.index] = '('; if((n+1)%2 == 0) balance++; else balance += 2; totalCost -= bestSwitch.diff; } else { System.out.println("-1"); return; } } } if(balance == 0) { System.out.println(totalCost); System.out.println(sequence); } else System.out.println("-1"); } } }
Java
["(??)\n1 2\n2 8"]
1 second
["4\n()()"]
null
Java 8
standard input
[ "greedy" ]
970cd8ce0cf7214b7f2be337990557c9
The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai,  bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one.
2,600
Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them.
standard output
PASSED
613838cae8c194c22aadf5a26bd319cc
train_002.jsonl
1267963200
This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest.
64 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Collection; import java.util.PriorityQueue; import java.util.StringTokenizer; import java.util.stream.Stream; public class Main implements Runnable { static final double time = 1e9; static final int MOD = (int) 1e9 + 7; static final long mh = Long.MAX_VALUE; static final Reader in = new Reader(); static final PrintWriter out = new PrintWriter(System.out); StringBuilder answer = new StringBuilder(); long start = System.nanoTime(); public static void main(String[] args) { new Thread(null, new Main(), "persefone", 1 << 28).start(); } @Override public void run() { solve(); printf(); long elapsed = System.nanoTime() - start; // out.println("stamp : " + elapsed / time); // out.println("stamp : " + TimeUnit.SECONDS.convert(elapsed, TimeUnit.NANOSECONDS)); close(); // out.flush(); } void solve() { char[] s = in.next().toCharArray(); int balanced = 0; long cost = 0; PriorityQueue<int[]> queue = new PriorityQueue<>((a, b) -> a[0] - b[0]); for (int i = 0; i < s.length; i++) { if (s[i] == '(') { ++balanced; } else if (s[i] == ')') { --balanced; } else { int x = in.nextInt(); int y = in.nextInt(); cost += y; queue.add(new int[] { x - y, i }); s[i] = ')'; --balanced; } if (balanced < 0) { if (queue.isEmpty()) { printf(-1); return; } int[] c = queue.poll(); cost += c[0]; s[c[1]] = '('; balanced += 2; } } if (balanced != 0) { add(-1); return; } printf(cost, s); } void printf() { out.print(answer); } void close() { out.close(); } 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); } @SuppressWarnings("unchecked") <T extends Comparable<? super T>> T min(T... t) { if (t.length == 0) return null; T m = t[0]; for (int i = 1; i < t.length; i++) if (t[i].compareTo(m) < 0) m = t[i]; return m; } @SuppressWarnings("unchecked") <T extends Comparable<? super T>> T max(T... t) { if (t.length == 0) return null; T m = t[0]; for (int i = 1; i < t.length; i++) if (t[i].compareTo(m) > 0) m = t[i]; return m; } int gcd(int a, int b) { return (b == 0) ? a : gcd(b, a % b); } long gcd(long a, long b) { return (b == 0) ? a : gcd(b, a % b); } // c = gcd(a, b) -> extends gcd method: ax + by = c <----> (b % a)p + q = c; int[] ext_gcd(int a, int b) { if (b == 0) return new int[] {a, 1, 0 }; int[] vals = ext_gcd(b, a % b); int d = vals[0]; // gcd int p = vals[2]; // int q = vals[1] - (a / b) * vals[2]; return new int[] { d, p, q }; } // find any solution of the equation: ax + by = c using extends gcd boolean find_any_solution(int a, int b, int c, int[] root) { int[] vals = ext_gcd(Math.abs(a), Math.abs(b)); if (c % vals[0] != 0) return false; printf(vals); root[0] = c * vals[1] / vals[0]; root[1] = c * vals[2] / vals[0]; if (a < 0) root[0] *= -1; if (b < 0) root[1] *= -1; return true; } int mod(int x) { return x % MOD; } int mod(int x, int y) { return mod(mod(x) + mod(y)); } long mod(long x) { return x % MOD; } long mod (long x, long y) { return mod(mod(x) + mod(y)); } int lw(long[] f, int l, int r, long k) { int R = r, m = 0; while (l <= r) { m = l + r >> 1; if (m == R) return m; if (f[m] >= k) r = m - 1; else l = m + 1; } return l; } int up(long[] f, int l, int r, long k) { int R = r, m = 0; while (l <= r) { m = l + r >> 1; if (m == R) return m; if (f[m] > k) r = m - 1; else l = m + 1; } return l; } int lw(int[] f, int l, int r, int k) { int R = r, m = 0; while (l <= r) { m = l + r >> 1; if (m == R) return m; if (f[m] >= k) r = m - 1; else l = m + 1; } return l; } int up(int[] f, int l, int r, int k) { int R = r, m = 0; while (l <= r) { m = l + r >> 1; if (m == R) return m; if (f[m] > k) r = m - 1; else l = m + 1; } return l; } long calc(int base, int exponent) { if (exponent == 0) return 1; if (exponent == 1) return base % MOD; long m = calc(base, exponent >> 1); if (exponent % 2 == 0) return m * m % MOD; return base * m * m % MOD; } long calc(int base, long exponent) { if (exponent == 0) return 1; if (exponent == 1) return base % MOD; long m = calc(base, exponent >> 1); if (exponent % 2 == 0) return m * m % MOD; return base * m * m % MOD; } long calc(long base, long exponent) { if (exponent == 0) return 1; if (exponent == 1) return base % MOD; long m = calc(base, exponent >> 1); if (exponent % 2 == 0) return m * m % MOD; return base * m * m % MOD; } long power(int base, int exponent) { if (exponent == 0) return 1; long m = power(base, exponent >> 1); if (exponent % 2 == 0) return m * m; return base * m * m; } void swap(int[] a, int i, int j) { a[i] ^= a[j]; a[j] ^= a[i]; a[i] ^= a[j]; } void swap(long[] a, int i, int j) { long tmp = a[i]; a[i] = a[j]; a[j] = tmp; } static class Pair<K extends Comparable<? super K>, V extends Comparable<? super V>> implements Comparable<Pair<K, V>> { private K k; private V v; Pair() {} Pair(K k, V v) { this.k = k; this.v = v; } K getK() { return k; } V getV() { return v; } void setK(K k) { this.k = k; } void setV(V v) { this.v = v; } void setKV(K k, V v) { this.k = k; this.v = v; } @SuppressWarnings("unchecked") @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || !(o instanceof Pair)) return false; Pair<K, V> p = (Pair<K, V>) o; return k.compareTo(p.k) == 0 && v.compareTo(p.v) == 0; } @Override public int hashCode() { int hash = 31; hash = hash * 89 + k.hashCode(); hash = hash * 89 + v.hashCode(); return hash; } @Override public int compareTo(Pair<K, V> pair) { return k.compareTo(pair.k) == 0 ? v.compareTo(pair.v) : k.compareTo(pair.k); } @Override public Pair<K, V> clone() { return new Pair<K, V>(this.k, this.v); } @Override public String toString() { return String.valueOf(k).concat(" ").concat(String.valueOf(v)).concat("\n"); } } static class Reader { private BufferedReader br; private StringTokenizer st; Reader() { br = new BufferedReader(new InputStreamReader(System.in)); } 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
["(??)\n1 2\n2 8"]
1 second
["4\n()()"]
null
Java 8
standard input
[ "greedy" ]
970cd8ce0cf7214b7f2be337990557c9
The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai,  bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one.
2,600
Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them.
standard output
PASSED
3484b3010c7d334e459fbf0368acafd6
train_002.jsonl
1267963200
This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest.
64 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.PriorityQueue; public class Main { public static class Paren implements Comparable<Paren> { int cost; int index; public Paren(int c, int i) { cost = c; index = i; } @Override public int compareTo(Paren p) { return cost > p.cost ? 1 : -1; } } public static void main(String[] args) { try{ BufferedReader b = new BufferedReader(new InputStreamReader(System.in)); char[] bs = b.readLine().toCharArray(); int n=0; long sum=0; PriorityQueue<Paren> queue = new PriorityQueue<Paren>(); for(int i=0; i<bs.length; i++){ if(bs[i] == '('){ n++; } if(bs[i] == ')'){ n--; } if(bs[i]=='?'){ bs[i] = ')'; n--; String[] inputs = b.readLine().split(" "); int x = Integer.parseInt(inputs[0]); int y = Integer.parseInt(inputs[1]); sum += y; queue.add(new Paren((x - y), i)); } if (n < 0) { if(queue.isEmpty()){ System.out.println("-1"); return; } n += 2; Paren paren = queue.poll(); sum += paren.cost; bs[paren.index] = '('; } } if (n != 0) { System.out.println("-1"); } else { System.out.println(sum); System.out.println(bs); } } catch(IOException io){ // io.printStackTrace(); } } }
Java
["(??)\n1 2\n2 8"]
1 second
["4\n()()"]
null
Java 8
standard input
[ "greedy" ]
970cd8ce0cf7214b7f2be337990557c9
The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai,  bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one.
2,600
Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them.
standard output
PASSED
ba0eb23313638c0153fdbd03e9da861f
train_002.jsonl
1267963200
This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest.
64 megabytes
import java.util.*; import java.io.*; public class leastCost { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); StringBuilder pattern = new StringBuilder(in.readLine()); long cost = 0; int state = 0; PriorityQueue<Bracket> pq = new PriorityQueue<>(); for (int i = 0; i < pattern.length(); i++) { char c = pattern.charAt(i); if (c == '(') state++; else if (c == ')') state--; else { String line = in.readLine(); String[] part = line.split(" "); int open = Integer.parseInt(part[0]); int close = Integer.parseInt(part[1]); pq.add(new Bracket(i, close - open)); pattern.setCharAt(i, ')'); state--; cost += close; } if (state < 0) { if (pq.isEmpty()) break; Bracket b = pq.poll(); pattern.setCharAt(b.index, '('); state += 2; cost -= b.diff; } } if (state != 0) { cost = -1; pattern = new StringBuilder(); } out.println(cost); out.println(pattern.toString()); out.close(); in.close(); } } class Bracket implements Comparable<Bracket> { int index; int diff; public Bracket(int index, int diff) { this.index = index; this.diff = diff; } @Override public int compareTo(Bracket o) { return o.diff - this.diff; } }
Java
["(??)\n1 2\n2 8"]
1 second
["4\n()()"]
null
Java 8
standard input
[ "greedy" ]
970cd8ce0cf7214b7f2be337990557c9
The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai,  bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one.
2,600
Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them.
standard output
PASSED
b46323ed3afd824ad451671d3583efcc
train_002.jsonl
1267963200
This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest.
64 megabytes
//package main; import java.io.*; import java.util.*; public class Main{ public static void main(String[] args) throws IOException { Reader.init(System.in); StringBuffer outBuffer = new StringBuffer(); //TODO: implement brute force? (O(n^2), n = 5*10^4) //BaseCost arrayList //CostDifferential arrayList SortedSet<Cost> cost = new TreeSet<Cost>(); //Base character array char[] sequence = Reader.next().toCharArray(); long totalCost = 0; int options = 0; int openBrackets = 0; //TODO: Pre-find last mandatory close bracket (including forced ?) //If the last ? is about to be added, it had //Check that length is even for runtime if(sequence.length % 2 == 0) { //iteration process for(int n = 0; n < sequence.length; n++) { //If it is ?, add to options if(sequence[n] == '?') { //Get the weights from input int open = Reader.nextInt(); int close = Reader.nextInt(); cost.add(new Cost(open, close, n)); options++; } else { //Else openBrackets count if(sequence[n] == '(') { openBrackets++; } else { openBrackets--; //If openBrackets < 0, impossible. Break. if(openBrackets < 0) { break; } } } //If options > openBrackets, if(options > openBrackets) { //Get the cheapest Cost cheapest = cost.first(); //Apply weight totalCost+=cheapest.open; //Mark the open bracket in sequence sequence[cheapest.id] = '('; openBrackets++; cost.remove(cheapest); options--; } } //Fill remaining spaces with close brackets. while(cost.size() > 0) { Cost next = cost.first(); //Apply weight. totalCost+=next.close; //Mark in sequence sequence[next.id] = ')'; openBrackets--; cost.remove(next); } //Check to make sure sequence is balanced if(openBrackets == 0) { outBuffer.append(totalCost); outBuffer.append("\n"); outBuffer.append(sequence); } else { outBuffer.append(-1); } } else { outBuffer.append(-1); } System.out.println(outBuffer); } } class Cost implements Comparable<Cost> { public int open; public int close; public int id; public int diff() { return open - close; } Cost(int openIn, int closeIn, int idIn) { open = openIn; close = closeIn; id = idIn; } @Override public int compareTo(Cost aThat) { final int BEFORE = -1; final int EQUAL = 0; final int AFTER = 1; if(this == aThat) return EQUAL; if(this.diff() < aThat.diff()) return BEFORE; if(this.diff() > aThat.diff()) return AFTER; if(this.id < aThat.id) return BEFORE; if(this.id > aThat.id) return AFTER; return EQUAL; } } // Class for buffered reading int and double values //Mad props go out to: http://www.cpe.ku.ac.th/~jim/java-io.html class Reader { static BufferedReader reader; static StringTokenizer tokenizer; //call this method to initialize reader for InputStream static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input) ); tokenizer = new StringTokenizer(""); } //get next word static String next() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt( next() ); } static double nextDouble() throws IOException { return Double.parseDouble( next() ); } }
Java
["(??)\n1 2\n2 8"]
1 second
["4\n()()"]
null
Java 8
standard input
[ "greedy" ]
970cd8ce0cf7214b7f2be337990557c9
The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai,  bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one.
2,600
Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them.
standard output
PASSED
cc89432212d7a7787fe60aac6bd23098
train_002.jsonl
1267963200
This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest.
64 megabytes
import java.util.*; import java.io.*; public class Main { // We'll need some sort of structure to hold the cost for each parenthesis static class Paren implements Comparable<Paren> { int index, cost; Paren(int c, int i) { this.index = i; this.cost = c; } @Override public int compareTo(Paren paren) { return this.cost - paren.cost; } } public static void main(String args[]) { Scanner in = new Scanner(System.in); char[] expression = in.nextLine().toCharArray(); PriorityQueue<Paren> parens = new PriorityQueue<Paren>(); // Count ?'s int n= 0 ; for(int i = 0; i < expression.length; i++) { if(expression[i] == '?') n++; } // array to keep track of the two costs for each ? int cost[][] = new int[n][2]; for(int i = 0; i < n; i++) { cost[i][0] = in.nextInt(); cost[i][1] = in.nextInt(); } // Now we'll proceed to count the expression from left to right, // assuming every ( is 1 and every ) is -1. We will evaluate the score // of each ? and assume each one to be what the smallest score would be // // We do all of this so we can find the point where our middle is. This is given by // the point we receive our lowest score on. int count = 0, countMin = 0, costCount = 0, indexMin = 0; for(int i = 0; i < expression.length; i++) { if(expression[i] == '(') count++; else if (expression[i] == ')') { count--; if(count < countMin) { countMin = count; indexMin = i + 1; } } else if (expression[i] == '?') { if(cost[costCount][0] < cost[costCount][1]) count++; else { count--; if(count < countMin) { countMin = count; indexMin = i + 1; } } costCount++; } } // Now that we know the optimal middle of the expression, we can iterate through each side and // add our costs to our priority queue // Our queue will store all of our ) choices when going through the left. Once we get to a point where we have too many ), we will switch // the one with the least amount of difference in cost to ( costCount = 0; count = 0; long totalCost = 0; for(int i = 0; i < indexMin; i++) { if(expression[i] == '(') count++; else if (expression[i] == ')') count--; else { if (cost[costCount][0] < cost[costCount][1]) { totalCost += cost[costCount][0]; expression[i] = '('; count++; } else { totalCost += cost[costCount][1]; expression[i] = ')'; parens.add(new Paren(cost[costCount][0] - cost[costCount][1], i)); count--; } costCount++; } if(count < 0) { Paren smallestParen = parens.poll(); // If we can't find a right paren, then our expression is illegal if(smallestParen == null) { System.out.println(-1); return; } expression[smallestParen.index] = '('; count += 2; // We just swapped a right to a left totalCost += smallestParen.cost; // Add that difference in cost we just took on by swapping the paren } } // This next part is basically the last one but we're going from the right and swapping ) with ( count = 0; parens.clear(); costCount = cost.length - 1; for(int i = expression.length - 1; i >= indexMin; i--) { if(expression[i] == '(') count--; else if(expression[i] == ')') count++; else { if(cost[costCount][0] >= cost[costCount][1]) { totalCost += cost[costCount][1]; expression[i] = ')'; count++; } else { totalCost += cost[costCount][0]; expression[i] = '('; parens.add(new Paren(cost[costCount][1] - cost[costCount][0], i)); count--; } costCount--; } if ( count < 0) { Paren smallestParen = parens.poll(); if(smallestParen == null) { System.out.println(-1); return; } expression[smallestParen.index] = ')'; count += 2; totalCost += smallestParen.cost; } } System.out.println(totalCost); for(int i = 0; i < expression.length; i++) System.out.print(expression[i]); in.close(); } // This was just a function to test if I understood what made an expression regular /*static boolean isRegular(char[] expression) { int numLeft = 0; for (int i = 0; i < expression.length; i++) { if(expression[i] == '(') numLeft++; else numLeft--; if(numLeft < 0) return false; } if(numLeft != 0) return false; return true; }*/ }
Java
["(??)\n1 2\n2 8"]
1 second
["4\n()()"]
null
Java 8
standard input
[ "greedy" ]
970cd8ce0cf7214b7f2be337990557c9
The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai,  bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one.
2,600
Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them.
standard output
PASSED
098f2d211e5357562cbafcd5ec3ca6bc
train_002.jsonl
1267963200
This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest.
64 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.PriorityQueue; import java.util.StringTokenizer; public class E { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); char[] s = sc.next().toCharArray(); PriorityQueue<Rep> pq = new PriorityQueue<Rep>(); long ans = 0; int sum = 0; for(int i = 0; i < s.length; ++i) { if(s[i] == '?') { int open = sc.nextInt(), close = sc.nextInt(); pq.add(new Rep(i, open - close)); s[i] = ')'; ans += close; --sum; } else if(s[i] == '(') ++sum; else --sum; if(sum < 0) if(pq.isEmpty()) { ans = -1; break; } else { Rep r = pq.remove(); s[r.idx] = '('; ans += r.cost; sum += 2; } } if(sum != 0) ans = -1; out.println(ans); if(ans != -1) out.println(s); out.flush(); out.close(); } static class Rep implements Comparable<Rep> { int idx, cost; Rep(int a, int b) { idx = a; cost = b; } public int compareTo(Rep r) { return cost - r.cost; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public Scanner(FileReader r){ br = new BufferedReader(r);} 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
["(??)\n1 2\n2 8"]
1 second
["4\n()()"]
null
Java 8
standard input
[ "greedy" ]
970cd8ce0cf7214b7f2be337990557c9
The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai,  bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one.
2,600
Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them.
standard output
PASSED
0769e8b112418961fbb27fb5e93120fa
train_002.jsonl
1267963200
This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest.
64 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.PriorityQueue; import java.util.StringTokenizer; public class Problem3D { private static class CostDiff implements Comparable<CostDiff> { int diff; int pos; CostDiff(int diff, int pos) { this.diff = diff; this.pos = pos; } @Override public int compareTo(CostDiff obj) { if (this.diff > obj.diff) { return 1; } else if (this.diff < obj.diff) { return -1; } return 0; } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); char[] str = br.readLine().toCharArray(); int len = str.length; int status = 0; long cost = 0; PriorityQueue<CostDiff> diffs = new PriorityQueue<CostDiff>(); for (int i = 0; i < len; i++) { char c = str[i]; if (c == '(') { status++; } else if (c == ')') { status--; } else { StringTokenizer st = new StringTokenizer(br.readLine()); int openCost = Integer.parseInt(st.nextToken()); int closeCost = Integer.parseInt(st.nextToken()); diffs.add(new CostDiff(openCost - closeCost, i)); str[i] = ')'; status--; cost += closeCost; } if(status < 0) { if(diffs.isEmpty()) { System.out.println(-1); System.exit(0); } else { CostDiff maxDiff = diffs.remove(); str[maxDiff.pos] = '('; cost += maxDiff.diff; status += 2; } } } if(status > 0) { System.out.println(-1); System.exit(0); } System.out.println(cost); System.out.println(new String(str)); } }
Java
["(??)\n1 2\n2 8"]
1 second
["4\n()()"]
null
Java 8
standard input
[ "greedy" ]
970cd8ce0cf7214b7f2be337990557c9
The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai,  bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one.
2,600
Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them.
standard output
PASSED
b1ad27959f09989b07546e618f126e40
train_002.jsonl
1267963200
This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest.
64 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; /** * Created by James on 1/29/2015. */ public class Driver { public static void main(String [] args) throws IOException { BufferedReader scanner = new BufferedReader(new InputStreamReader(System.in)); String sequence = scanner.readLine(); if (sequence.length() % 2 == 1) { System.out.println(-1); return; } long balanced = 0, score = 0; Queue<Cost> costs = new PriorityQueue<Cost>(); char [] seqChars = sequence.toCharArray(); for (int i = 0; i < sequence.length(); ++i) { if (seqChars[i] == '(') { balanced++; } else if (seqChars[i] == ')') { balanced--; } else if (seqChars[i] == '?') { String [] pieces = scanner.readLine().split("\\s+"); seqChars[i] = ')'; costs.add(new Cost(Integer.parseInt(pieces[0]) - Integer.parseInt(pieces[1]), i)); score += Integer.parseInt(pieces[1]); balanced--; } if (!costs.isEmpty() && balanced == -1) { Cost cost = costs.poll(); seqChars[cost.spot] = '('; score += cost.cost; balanced += 2; } else if (balanced < -1) { break; } } if (0 == balanced) { System.out.println(score); System.out.println(new String(seqChars)); } else { System.out.println(-1); } } private static class Cost implements Comparable<Cost> { int cost, spot; public Cost(int cost, int spot) { this.cost = cost; this.spot = spot; } @Override public int compareTo(Cost o) { return this.cost > o.cost ? 1 : -1; } } }
Java
["(??)\n1 2\n2 8"]
1 second
["4\n()()"]
null
Java 8
standard input
[ "greedy" ]
970cd8ce0cf7214b7f2be337990557c9
The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai,  bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one.
2,600
Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them.
standard output
PASSED
c4f80fcd0d3aba8382ac183bcb3bb2d6
train_002.jsonl
1267963200
This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest.
64 megabytes
import java.io.*; import java.util.*; public class D0003_LeastCostBacketSequence { static class Bracket implements Comparable<Bracket> { int index; int open; int close; public Bracket(int i, int o, int c) { index = i; open = o; close = c; } public int compareTo(Bracket b) { return Integer.compare(open - close, b.open - b.close); } } public static void main(String[] args) { InputReader in = new InputReader(); char[] arr = in.next().toCharArray(); int n = arr.length; PriorityQueue<Bracket> pq = new PriorityQueue<>(); long balance = 0, totalCost = 0; for (int i=0; i<n; i++) { if (arr[i] == '(') ++balance; else if (arr[i] == ')') --balance; else { Bracket b = new Bracket(i, in.nextInt(), in.nextInt()); pq.add(b); totalCost += b.close; arr[i] = ')'; --balance; } if (balance < 0) { if (pq.isEmpty()) break; Bracket b = pq.poll(); arr[b.index] = '('; totalCost -= b.close; totalCost += b.open; balance += 2; } } if (balance != 0) System.out.println(-1); else { StringBuffer sb = new StringBuffer(); sb.append(totalCost + "\n"); for (char c: arr) sb.append(c); System.out.println(sb); } } static class InputReader { public BufferedReader br; public StringTokenizer st; public InputReader() { br = new BufferedReader(new InputStreamReader(System.in)); st = null; } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["(??)\n1 2\n2 8"]
1 second
["4\n()()"]
null
Java 8
standard input
[ "greedy" ]
970cd8ce0cf7214b7f2be337990557c9
The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai,  bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one.
2,600
Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them.
standard output
PASSED
c62a9e937fa8139b9da6eeeb7b950ef0
train_002.jsonl
1267963200
This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest.
64 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.PriorityQueue; public class Main { public static class Paren implements Comparable<Paren> { int cost; int index; public Paren(int c, int i) { cost = c; index = i; } @Override public int compareTo(Paren p) { return cost > p.cost ? 1 : -1; } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); char[] bracketSequence = br.readLine().toCharArray(); int numberOfQuestions = bracketSequence.length; int brackets = 0; long totalCost = 0; PriorityQueue<Paren> queue = new PriorityQueue<Paren>(); String[] inputs; for (int i = 0; i < numberOfQuestions; i++) { // Opening bracket if (bracketSequence[i] == '(') { brackets++; // Closing bracket } else if (bracketSequence[i] == ')') { brackets--; // Question mark } else { brackets--; inputs = br.readLine().split(" "); int a = Integer.parseInt(inputs[0]); int b = Integer.parseInt(inputs[1]); totalCost += b; bracketSequence[i] = ')'; queue.add(new Paren((a - b), i)); } if (brackets < 0) { if (queue.isEmpty()) { System.out.println("-1"); System.exit(0); } brackets += 2; Paren paren = queue.poll(); totalCost += paren.cost; bracketSequence[paren.index] = '('; } } if (brackets != 0) { System.out.println("-1"); } else { System.out.println(totalCost); System.out.println(bracketSequence); } } }
Java
["(??)\n1 2\n2 8"]
1 second
["4\n()()"]
null
Java 8
standard input
[ "greedy" ]
970cd8ce0cf7214b7f2be337990557c9
The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai,  bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one.
2,600
Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them.
standard output
PASSED
151d97948d09c281fe7275203c0a34b7
train_002.jsonl
1267963200
This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest.
64 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.PriorityQueue; import java.util.Queue; public class A3D { public static BufferedReader buffstdin = new BufferedReader(new InputStreamReader(System.in)); static OutputStream out = new BufferedOutputStream ( System.out ); //static ArrayList<String> stack = new ArrayList<String>(); static int openB = 0; static int closeB = 0; static final String open = "("; static final String close = ")"; static final String q = "?"; static long opens = 0; static long closes = 0; static long price = 0; static ArrayList<Integer> Qs = new ArrayList<Integer>(); static Queue<qPoint> qPoints = new PriorityQueue<qPoint>(); public static void print(String s) throws IOException { s = s + "\n"; out.write(s.getBytes()); } public static void print(int s) throws IOException { print("" + s); } public static int openAt(String[] sequence, int limit) { openB = 0; int curOpen = 0; closeB = 0; for(int i=0; i<limit; i++) { if(sequence[i].equals(open)) { openB++; curOpen++; } else if(sequence[i].equals(close)) { closeB++; curOpen--; if(curOpen < 0) return -1; } else return -1; } return curOpen; } public static boolean isValid(String[] sequence) throws IOException { openB = 0; int curOpen = 0; closeB = 0; for(int i=0; i<sequence.length; i++) { if(sequence[i].equals(open)) { openB++; curOpen++; } else if(sequence[i].equals(close)) { closeB++; curOpen--; if(curOpen < 0) return false; } else return false; } if(openB != closeB) { return false; } return true; } public static int getQs (String[] sequence) throws IOException { int count = 0; for(int i=0; i<sequence.length; i++) { if(sequence[i].equals(q)) { Qs.add(i); count++; sequence[i] = ")"; closes++; String[] line = buffstdin.readLine().split(" "); int endPrice = Integer.valueOf(line[1]); int startPrice = Integer.valueOf(line[0]); price += endPrice; qPoints.add(new qPoint(i, startPrice-endPrice)); } else if(sequence[i].equals(open)) { //print("Found the open"); opens++; } else if(sequence[i].equals(close)) { closes++; } if(!qPoints.isEmpty() && closes > opens) { qPoint p = qPoints.poll(); sequence[p.x] = "("; //print(p.x); price += p.priceChange; opens++; closes--; //print("Closes: " +closes + " Opens: " + opens); //printSequence(sequence); } } return count; } public static class qPoint implements Comparable<qPoint> { public int x; public long priceChange; public qPoint(int X, int P) { x=X; priceChange=P; } @Override public int compareTo(qPoint arg0) { return Long.signum(priceChange - arg0.priceChange); } } public static void printSequence(String[] sequence) throws IOException { for(int i=0; i<sequence.length; i++) { out.write(sequence[i].getBytes()); } out.write("\n".getBytes()); } public static void main(String[] args) throws IOException { String[] line = buffstdin.readLine().trim().split(""); String[] sequence = Arrays.copyOfRange(line, 0, line.length); //printSequence(sequence); int totalQs = getQs(sequence); //printSequence(sequence); //int remaining = closes-opens; //print("Closes: " +closes + " Opens: " + opens); //print(remaining); //printSequence(sequence); //print(sequence[1]); if(closes - opens != 0 || !isValid(sequence)) { print(-1); //printSequence(sequence); } else { print("" + price); printSequence(sequence); } out.flush(); } }
Java
["(??)\n1 2\n2 8"]
1 second
["4\n()()"]
null
Java 8
standard input
[ "greedy" ]
970cd8ce0cf7214b7f2be337990557c9
The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai,  bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one.
2,600
Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them.
standard output
PASSED
1bf04ca81317c39fc0f0b4fbb69ad006
train_002.jsonl
1267963200
This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest.
64 megabytes
import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.PriorityQueue; import java.util.Comparator; import java.io.IOException; public class Main { static class Pair { private int first; private int second; public Pair(int f, int s) { this.first = f; this.second = s; } public int getFirst() { return first; } public int getSecond() { return second; } } static class QueueComparator implements Comparator<Pair> { public int compare(Pair p1, Pair p2) { return p1.first-p2.first; } } public static void main(String[] args) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try { String str = br.readLine(); ArrayList<Pair> costArrayList = new ArrayList<Pair>(); StringTokenizer sk = null; StringBuilder newString = new StringBuilder(""); boolean[] isQuestion = new boolean[str.length()]; long costTillNow = 0; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == '?') { newString.append(')'); String inp = br.readLine(); sk = new StringTokenizer(inp, " "); int a = Integer.parseInt(sk.nextToken()); int b = Integer.parseInt(sk.nextToken()); costArrayList.add(new Pair(a, b)); costTillNow += b; isQuestion[i] = true; } else { newString.append(str.charAt(i)); } } int parenCount = 0; int c = 0; Comparator<Pair> comp = new QueueComparator(); PriorityQueue<Pair> pq = new PriorityQueue<Pair>(newString.length(), comp); for (int i = 0; i < newString.length(); i++) { if (newString.charAt(i) == '(') { parenCount++; } else { parenCount--; if (isQuestion[i]) { pq.add(new Pair(costArrayList.get(c).first-costArrayList.get(c).second, i)); c++; } } if (parenCount < 0) { if (pq.size() > 0) { Pair p = pq.peek(); pq.remove(); costTillNow += p.getFirst(); newString.replace(p.getSecond(), p.getSecond()+1, "("); parenCount += 2; } else { break; } } } if (parenCount != 0) { System.out.println("-1"); } else { System.out.println(costTillNow); System.out.println(newString.toString()); } } catch (IOException ioe) { System.out.println("IOException : " + ioe); } catch (Exception e) { System.out.println("Exception : " + e); e.printStackTrace(); } } }
Java
["(??)\n1 2\n2 8"]
1 second
["4\n()()"]
null
Java 8
standard input
[ "greedy" ]
970cd8ce0cf7214b7f2be337990557c9
The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai,  bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one.
2,600
Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them.
standard output
PASSED
9ebae58394477e3a46699160619e67d9
train_002.jsonl
1267963200
This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest.
64 megabytes
//package CF; 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.PriorityQueue; import java.util.StringTokenizer; public class D { public static void main(String[] args) throws Exception { Scanner bf = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); char [] c = bf.next().toCharArray(); PriorityQueue<Br> pq = new PriorityQueue<Br>(); long sum = 0; long ans = 0; for (int i = 0; i < c.length; i++) { if(c[i] == '?'){ int o = bf.nextInt(), cl = bf.nextInt(); pq.add(new Br(o-cl, i)); c[i] = ')'; ans += cl; sum--; } else if(c[i] == '('){ sum++; } else{ sum--; } if(sum < 0){ if(pq.isEmpty()){ ans = -1; break; } else{ Br tmp = pq.poll(); c[tmp.ind] = '('; sum += 2; ans += tmp.val; } } } if(sum != 0){ out.println(-1); } else{ out.println(ans); out.println(c); } out.flush(); out.close(); } static class Br implements Comparable<Br>{ int val; int ind; public Br(int v, int i){ val = v; ind = i; } @Override public int compareTo(Br o) { return val - o.val; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader fileReader) { br = new BufferedReader(fileReader); } 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
["(??)\n1 2\n2 8"]
1 second
["4\n()()"]
null
Java 8
standard input
[ "greedy" ]
970cd8ce0cf7214b7f2be337990557c9
The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai,  bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one.
2,600
Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them.
standard output
PASSED
bb529d082fde11cac92369f774a6908d
train_002.jsonl
1267963200
This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest.
64 megabytes
import java.io.*; import java.util.*; public class Xyz { public static void main(String [] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s = br.readLine(); if (s.length() % 2 == 1) { System.out.println(-1); return; } long balanced = 0, score = 0; Queue<Cost> costs = new PriorityQueue<Cost>(); char [] Sequence = s.toCharArray(); for (int i = 0; i < s.length(); ++i) { if (Sequence[i] == '(') { balanced++; } else if (Sequence[i] == ')') { balanced--; } else if (Sequence[i] == '?') { String [] pieces = br.readLine().split("\\s+"); Sequence[i] = ')'; costs.add(new Cost(Integer.parseInt(pieces[0]) - Integer.parseInt(pieces[1]), i)); score = score + Integer.parseInt(pieces[1]); balanced--; } if (!costs.isEmpty() && balanced == -1) { Cost cost = costs.poll(); Sequence[cost.spot] = '('; score += cost.cost; balanced += 2; } else if (balanced < -1) { break; } } if (0 == balanced) { System.out.println(score); System.out.println(new String(Sequence)); } else { System.out.println(-1); } } private static class Cost implements Comparable<Cost> { int cost, spot; public Cost(int cost, int spot) { this.cost = cost; this.spot = spot; } @Override public int compareTo(Cost o) { return this.cost > o.cost ? 1 : -1; } } }
Java
["(??)\n1 2\n2 8"]
1 second
["4\n()()"]
null
Java 8
standard input
[ "greedy" ]
970cd8ce0cf7214b7f2be337990557c9
The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai,  bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one.
2,600
Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them.
standard output
PASSED
995569c0c316d66370f1156c0eb2746f
train_002.jsonl
1267963200
This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest.
64 megabytes
import java.util.*; import java.io.*; public class Solution { public static PrintWriter w = new PrintWriter(System.out); public static long tc = 0; public static long INF = 1000000000000L; public static void main(String args[] ) throws Exception { Reader in = new Reader(); char[] arr = in.next().toCharArray(); long[] cc = new long[arr.length]; for (int i=0; i<arr.length; i++) { if(arr[i] == '?') { long a = in.nextLong(); long b = in.nextLong(); if(a < b) { arr[i] = '('; tc += a; cc[i] = (b-a); } else { arr[i] = ')'; tc += b; cc[i] = a - b; } } else cc[i] = INF; } int balance = 0; int n = arr.length; TreeSet<pair> set = new TreeSet<>(); for (int i=0; i<n; i++) { if(arr[i] == ')') { set.add(new pair(cc[i],i)); --balance; } else ++balance; if(balance < 0) { pair use = set.first(); set.remove(use); tc += use.cost; arr[use.index] = '('; balance += 2; } } set.clear(); balance = 0; for (int i=n-1; i>=0; --i) { if(arr[i] == '(') { set.add(new pair(cc[i],i)); --balance; } else ++balance; if(balance < 0) { pair use = set.first(); set.remove(use); tc += use.cost; balance += 2; arr[use.index] = ')'; } } if(balance != 0) throw new RuntimeException(); if(tc >= INF) w.println("-1"); else { w.println(tc); w.println(arr); } w.flush(); return; } } class pair implements Comparable<pair>{ public long cost; public int index; public pair(long cost, int index) { this.cost = cost; this.index = index; } public int compareTo(pair p) { if(this.cost < p.cost) return -1; else if(this.cost > p.cost) return 1; else if(this.index < p.index) return -1; else if(this.index > p.index) return 1; else return 0; } } class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String nextLine() throws IOException { int c = read(); while(isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while(!isEndOfLine(c)); return res.toString(); } public String next() throws IOException { 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 int nextInt() throws IOException { int ret = 0; byte c = read(); while(c <= ' ') c = read(); boolean neg = (c == '-'); if(neg) c = read(); do { ret = ret * 10 + c - '0'; } while((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public int[] nextIntArray(int n) throws IOException { int a[] = new int[n]; for(int i = 0; i < n; i++) a[i] = nextInt(); return a; } public int[][] next2dIntArray(int n, int m) throws IOException { int a[][] = new int[n][m]; for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) a[i][j] = nextInt(); return a; } public char nextChar() throws IOException { return next().charAt(0); } public long nextLong() throws IOException { long ret = 0; byte c = read(); while(c <= ' ') c = read(); boolean neg = (c == '-'); if(neg) c = read(); do { ret = ret * 10 + c - '0'; } while((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while(c <= ' ') c = read(); boolean neg = (c == '-'); if(neg) c = read(); do { ret = ret * 10 + c - '0'; } while((c = read()) >= '0' && c <= '9'); if (c == '.') { while((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if(neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if(bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if(bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if(din == null) return; din.close(); } public 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
["(??)\n1 2\n2 8"]
1 second
["4\n()()"]
null
Java 8
standard input
[ "greedy" ]
970cd8ce0cf7214b7f2be337990557c9
The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai,  bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one.
2,600
Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them.
standard output
PASSED
0d29f1a072608559ec678ef1e0b4104b
train_002.jsonl
1267963200
This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest.
64 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.PriorityQueue; import java.util.Queue; /** * Created by harish.sharma on 10/9/16. */ public class A1 { public static void main(String[] arg) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); char[] exp = br.readLine().toCharArray(); Queue<Pair> pq = new PriorityQueue<>(); int temp = 0; long sum = 0; for (int i = 0; i < exp.length; i++) { if (exp[i] == '(') { temp++; } else if (exp[i] == ')') { temp--; } else { String[] s = br.readLine().split(" "); int addC = Integer.parseInt(s[0]); int delC = Integer.parseInt(s[1]); exp[i] = ')'; sum += delC; pq.add(new Pair(i, delC - addC)); temp--; } if (temp < 0) { if (pq.isEmpty()) { break; } Pair top = pq.remove(); exp[top.index] = '('; sum -= top.value; temp += 2; } } if (temp != 0) { System.out.println(-1); return; } System.out.println(sum); System.out.println(String.valueOf(exp)); br.close(); } public static class Pair implements Comparable<Pair> { Integer index; Integer value; public Pair(Integer index, Integer value) { this.index = index; this.value = value; } @Override public int compareTo(Pair o) { return -value.compareTo(o.value); } } }
Java
["(??)\n1 2\n2 8"]
1 second
["4\n()()"]
null
Java 8
standard input
[ "greedy" ]
970cd8ce0cf7214b7f2be337990557c9
The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai,  bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one.
2,600
Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them.
standard output
PASSED
4237c21480016d5c055cd898e727aa2b
train_002.jsonl
1267963200
This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest.
64 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; public class LeastCostBracket { public static class Cost implements Comparable<Cost>{ int cost; int index; Cost(int c, int i){ this.cost = c; this.index = i; } public int compareTo(Cost c) { if(this.cost > c.cost){ return 1; } else{ return -1; } } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); String input = br.readLine(); if(input.length() % 2 != 0){ pw.println("-1"); return; } char[] sequence = input.toCharArray(); int balanced = 0; long cost = 0; Queue<Cost> costs = new PriorityQueue<Cost>(); for(int i = 0; i < sequence.length; i++){ if(sequence[i] == '('){ balanced++; } else if(sequence[i] == ')'){ balanced--; } else if(sequence[i] == '?'){ String[] s = br.readLine().split(" "); int L = Integer.parseInt(s[0]); int R = Integer.parseInt(s[1]); costs.add(new Cost(L-R, i)); sequence[i] = ')'; cost += R; balanced--; } if(!costs.isEmpty() && balanced == -1){ Cost c = costs.poll(); sequence[c.index] = '('; cost += c.cost; balanced += 2; } else if(balanced < -1){ break; } } if (balanced == 0) { pw.println(cost); if(cost != -1){ for(int i = 0; i < sequence.length; i++){ pw.print(sequence[i]); } pw.println(); } } else { pw.println("-1"); } pw.close(); } }
Java
["(??)\n1 2\n2 8"]
1 second
["4\n()()"]
null
Java 8
standard input
[ "greedy" ]
970cd8ce0cf7214b7f2be337990557c9
The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai,  bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one.
2,600
Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them.
standard output
PASSED
27760e5275501181e4deabc470fea8d6
train_002.jsonl
1267963200
This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest.
64 megabytes
import java.io.*; import java.util.*; public class Driver { public static class Cost implements Comparable<Cost> { int cost; int pos; Cost (int c, int p) { this.cost = c; this.pos = p; } public int compareTo(Cost c) { if (this.cost > c.cost) { return 1; } else { return -1; } } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String expression = br.readLine(); // if odd number of (), we know it is invalid if (expression.length() % 2 == 1) { System.out.println("-1"); System.exit(0); } char[] seq = expression.toCharArray(); Queue<Cost> costs = new PriorityQueue<Cost>(); //if pcount != 0 in the end the )( are out of balance int pCount = 0; long cost = 0; for (int i = 0; i < seq.length; i++) { switch (seq[i]){ case '(': pCount++; break; case ')': pCount--; break; case '?': // get corrisponding cost line String [] line = br.readLine().split(" "); int first = Integer.parseInt(line[0]); int second = Integer.parseInt(line[1]); costs.add(new Cost(first - second, i)); seq[i] = ')'; cost += second; pCount--; } if (costs.size() > 0 && pCount == -1) { //out of balance so lets fix that Cost c = costs.poll(); seq[c.pos] = '('; cost += c.cost; pCount += 2; } else if (pCount == -1) { break; } } if (0 == pCount) { System.out.println(cost); System.out.println(new String(seq)); } else { System.out.println("-1"); } System.exit(0); } }
Java
["(??)\n1 2\n2 8"]
1 second
["4\n()()"]
null
Java 8
standard input
[ "greedy" ]
970cd8ce0cf7214b7f2be337990557c9
The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai,  bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one.
2,600
Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them.
standard output
PASSED
70ec79efea1c0c862fae7c00dd11b9b7
train_002.jsonl
1267963200
This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest.
64 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.PriorityQueue; import java.util.StringTokenizer; public class Main { static class mark implements Comparable<mark> { long a; long b; int idx; long cost; mark(int idx, long a, long b) { this.a = a; this.b = b; this.idx = idx; cost = a - b; } @Override public int compareTo(mark arg0) { // TODO Auto-generated method stub return (int)(this.cost - arg0.cost); } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); char[] exp = br.readLine().toCharArray(); int n = exp.length; long status = 0; long cost = 0; PriorityQueue<mark> marks = new PriorityQueue<>(); StringBuilder ans = new StringBuilder(); for (int i = 0; i < n; i++) { char current = exp[i]; if (current == '(') status++; else if (current == ')') status--; else { StringTokenizer st = new StringTokenizer(br.readLine()); mark temp = new mark(i, Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken())); marks.add(temp); cost += temp.b; exp[i] = ')'; status--; } if (status<0){ if (marks.isEmpty()) break; mark temp = marks.poll(); status +=2; exp[temp.idx] = '('; cost -= temp.b; cost+= temp.a; } } if (status ==0 ){ out.println(cost); for (int i = 0 ; i<n ; i++){ out.print(exp[i]); } } else out.println(-1); out.flush(); out.close(); } }
Java
["(??)\n1 2\n2 8"]
1 second
["4\n()()"]
null
Java 8
standard input
[ "greedy" ]
970cd8ce0cf7214b7f2be337990557c9
The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai,  bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one.
2,600
Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them.
standard output
PASSED
be16a4d74546689758f6821de266719a
train_002.jsonl
1267963200
This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest.
64 megabytes
// Don't place your source in a package import java.util.*; import java.lang.*; import java.io.*; import java.math.*; // Please name your class Main public class Main { static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); static int read() throws IOException { in.nextToken(); return (int) in.nval; } static String readString() throws IOException { in.nextToken(); return in.sval; } public static void main (String[] args) throws java.lang.Exception { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); //InputReader in = new InputReader(System.in); int T=1; for(int t=0;t<T;t++){ String s=in.next(); int n=0; for(int i=0;i<s.length();i++){ if(s.charAt(i)=='?')n++; } int A[][]=new int[n][3]; for(int i=0;i<n;i++){ A[i][0]=in.nextInt(); A[i][1]=in.nextInt(); A[i][2]=i; } Solution sol=new Solution(); sol.solution(s,A); } out.flush(); } } class Solution{ //constant variable final int MAX=Integer.MAX_VALUE; final int MIN=Integer.MIN_VALUE; //Set<Integer>adjecent[]; ////////////////////////////// public void solution(String s,int A[][]){ if(s.length()%2==1){ msg("-1"); return; } //(())?? //(()??) PriorityQueue<int[]>pq=new PriorityQueue<>((a,b)->{ return (b[1]-b[0])-(a[1]-a[0]); }); StringBuilder str=new StringBuilder(); char res[]=s.toCharArray(); int k=0;long sum=0; int index=0; for(int i=0;i<s.length();i++){ if(res[i]=='(')k++; else if(res[i]==')'){ k--; if(k<0){ if(pq.size()==0){ msg("-1"); return; } int top[]=pq.poll(); if(top[2]==s.length()-1){ if(pq.size()==0){ msg("-1"); return; } top=pq.poll(); } sum-=top[1]; sum+=top[0]; res[top[2]]='('; k+=2; } } else{ k--; res[i]=')'; int pair[]=new int[]{A[index][0],A[index][1],i}; sum+=pair[1]; pq.add(pair); if(k<0){ if(pq.size()==0){ msg("-1"); return; } int top[]=pq.poll(); if(top[2]==s.length()-1){ if(pq.size()==0){ msg("-1"); return; } top=pq.poll(); } sum-=top[1]; sum+=top[0]; res[top[2]]='('; k+=2; } index++; } //msg(i+" "+k); } if(k!=0){ msg("-1"); return; } msg(sum+""); msg(new String(res)); } public void swap(int A[],int l,int r){ int t=A[l]; A[l]=A[r]; A[r]=t; } public long C(long fact[],int i,int j){ // C(20,3)=20!/(17!*3!) // take a/b where a=20! b=17!*3! if(j>i)return 0; if(j==0)return 1; long mod=998244353; long a=fact[i]; long b=((fact[i-j]%mod)*(fact[j]%mod))%mod; BigInteger B= BigInteger.valueOf(b); long binverse=B.modInverse(BigInteger.valueOf(mod)).longValue(); return ((a)*(binverse%mod))%mod; } //map operation public void put(Map<Integer,Integer>map,int i){ if(!map.containsKey(i))map.put(i,0); map.put(i,map.get(i)+1); } public void delete(Map<Integer,Integer>map,int i){ map.put(i,map.get(i)-1); if(map.get(i)==0)map.remove(i); } /*public void tarjan(int p,int r){ if(cut)return; List<Integer>childs=adjecent[r]; dis[r]=low[r]=time; time++; //core for tarjan int son=0; for(int c:childs){ if(ban==c||c==p)continue; if(dis[c]==-1){ son++; tarjan(r,c); low[r]=Math.min(low[r],low[c]); if((r==root&&son>1)||(low[c]>=dis[r]&&r!=root)){ cut=true; return; } }else{ if(c!=p){ low[r]=Math.min(low[r],dis[c]); } } } }*/ //helper function I would use public void remove(Map<Integer,Integer>map,int i){ map.put(i,map.get(i)-1); if(map.get(i)==0)map.remove(i); } public void ascii(String s){ for(char c:s.toCharArray()){ System.out.print((c-'a')+" "); } msg(""); } public int flip(int i){ if(i==0)return 1; else return 0; } public boolean[] primes(int n){ boolean A[]=new boolean[n+1]; for(int i=2;i<=n;i++){ if(A[i]==false){ for(int j=i+i;j<=n;j+=i){ A[j]=true; } } } return A; } public void msg(String s){ System.out.println(s); } public void msg1(String s){ System.out.print(s); } public int[] kmpPre(String p){ int pre[]=new int[p.length()]; int l=0,r=1; while(r<p.length()){ if(p.charAt(l)==p.charAt(r)){ pre[r]=l+1; l++;r++; }else{ if(l==0)r++; else l=pre[l-1]; } } return pre; } public boolean isP(String s){ int l=0,r=s.length()-1; while(l<r){ if(s.charAt(l)!=s.charAt(r))return false; l++;r--; } return true; } public int find(int nums[],int x){//union find => find method if(nums[x]==x)return x; int root=find(nums,nums[x]); nums[x]=root; return root; } public int get(int A[],int i){ if(i<0||i>=A.length)return 0; return A[i]; } public int[] copy1(int A[]){ int a[]=new int[A.length]; for(int i=0;i<a.length;i++)a[i]=A[i]; return a; } public void print1(int A[]){ for(long i:A)System.out.print(i+" "); System.out.println(); } public void print2(long A[][]){ for(int i=0;i<A.length;i++){ for(int j=0;j<A[0].length;j++){ System.out.print(A[i][j]+" "); }System.out.println(); } } public int min(int a,int b){ return Math.min(a,b); } public int[][] matrixdp(int[][] grid) { if(grid.length==0)return new int[][]{}; int res[][]=new int[grid.length][grid[0].length]; for(int i=0;i<grid.length;i++){ for(int j=0;j<grid[0].length;j++){ res[i][j]=grid[i][j]+get(res,i-1,j)+get(res,i,j-1)-get(res,i-1,j-1); } } return res; } public int get(int grid[][],int i,int j){ if(i<0||j<0||i>=grid.length||j>=grid[0].length)return 0; return grid[i][j]; } public int[] suffixArray(String s){ int n=s.length(); Suffix A[]=new Suffix[n]; for(int i=0;i<n;i++){ A[i]=new Suffix(i,s.charAt(i)-'a',0); } for(int i=0;i<n;i++){ if(i==n-1){ A[i].next=-1; }else{ A[i].next=A[i+1].rank; } } Arrays.sort(A); for(int len=4;len<A.length*2;len<<=1){ int in[]=new int[A.length]; int rank=0; int pre=A[0].rank; A[0].rank=rank; in[A[0].index]=0; for(int i=1;i<A.length;i++){//rank for the first two letter if(A[i].rank==pre&&A[i].next==A[i-1].next){ pre=A[i].rank; A[i].rank=rank; }else{ pre=A[i].rank; A[i].rank=++rank; } in[A[i].index]=i; } for(int i=0;i<A.length;i++){ int next=A[i].index+len/2; if(next>=A.length){ A[i].next=-1; }else{ A[i].next=A[in[next]].rank; } } Arrays.sort(A); } int su[]=new int[A.length]; for(int i=0;i<su.length;i++){ su[i]=A[i].index; } return su; } } //suffix array Struct class Suffix implements Comparable<Suffix>{ int index; int rank; int next; public Suffix(int i,int rank,int next){ this.index=i; this.rank=rank; this.next=next; } @Override public int compareTo(Suffix other) { if(this.rank==other.rank){ return this.next-other.next; } return this.rank-other.rank; } public String toString(){ return this.index+" "+this.rank+" "+this.next+" "; } } class Wrapper implements Comparable<Wrapper>{ int spf;int cnt; public Wrapper(int spf,int cnt){ this.spf=spf; this.cnt=cnt; } @Override public int compareTo(Wrapper other) { return this.spf-other.spf; } } class Node{//what the range would be for that particular node boolean state=false; int l=0,r=0; int ll=0,rr=0; public Node(boolean state){ this.state=state; } } class Seg1{ int A[]; public Seg1(int A[]){ this.A=A; } public void update(int left,int right,int val,int s,int e,int id){ if(left<0||right<0||left>right)return; if(left==s&&right==e){ A[id]+=val; return; } int mid=s+(e-s)/2; //[s,mid] [mid+1,e] if(left>=mid+1){ update(left,right,val,mid+1,e,id*2+2); }else if(right<=mid){ update(left,right,val,s,mid,id*2+1); }else{ update(left,mid,val,s,mid,id*2+1); update(mid+1,right,val,mid+1,e,id*2+2); } } public int query(int i,int add,int s,int e,int id){ if(s==e&&i==s){ return A[id]+add; } int mid=s+(e-s)/2; //[s,mid] [mid+1,e] if(i>=mid+1){ return query(i,A[id]+add,mid+1,e,id*2+2); }else{ return query(i,A[id]+add,s,mid,id*2+1); } } } class MaxFlow{ public static List<Edge>[] createGraph(int nodes) { List<Edge>[] graph = new List[nodes]; for (int i = 0; i < nodes; i++) graph[i] = new ArrayList<>(); return graph; } public static void addEdge(List<Edge>[] graph, int s, int t, int cap) { graph[s].add(new Edge(t, graph[t].size(), cap)); graph[t].add(new Edge(s, graph[s].size() - 1, 0)); } static boolean dinicBfs(List<Edge>[] graph, int src, int dest, int[] dist) { Arrays.fill(dist, -1); dist[src] = 0; int[] Q = new int[graph.length]; int sizeQ = 0; Q[sizeQ++] = src; for (int i = 0; i < sizeQ; i++) { int u = Q[i]; for (Edge e : graph[u]) { if (dist[e.t] < 0 && e.f < e.cap) { dist[e.t] = dist[u] + 1; Q[sizeQ++] = e.t; } } } return dist[dest] >= 0; } static int dinicDfs(List<Edge>[] graph, int[] ptr, int[] dist, int dest, int u, int f) { if (u == dest) return f; for (; ptr[u] < graph[u].size(); ++ptr[u]) { Edge e = graph[u].get(ptr[u]); if (dist[e.t] == dist[u] + 1 && e.f < e.cap) { int df = dinicDfs(graph, ptr, dist, dest, e.t, Math.min(f, e.cap - e.f)); if (df > 0) { e.f += df; graph[e.t].get(e.rev).f -= df; return df; } } } return 0; } public static int maxFlow(List<Edge>[] graph, int src, int dest) { int flow = 0; int[] dist = new int[graph.length]; while (dinicBfs(graph, src, dest, dist)) { int[] ptr = new int[graph.length]; while (true) { int df = dinicDfs(graph, ptr, dist, dest, src, Integer.MAX_VALUE); if (df == 0) break; flow += df; } } return flow; } } class Edge { int t, rev, cap, f; public Edge(int t, int rev, int cap) { this.t = t; this.rev = rev; this.cap = cap; } }
Java
["(??)\n1 2\n2 8"]
1 second
["4\n()()"]
null
Java 8
standard input
[ "greedy" ]
970cd8ce0cf7214b7f2be337990557c9
The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai,  bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one.
2,600
Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them.
standard output
PASSED
6a0f240dbda17bb9ba62a5a44d51a758
train_002.jsonl
1267963200
This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest.
64 megabytes
import java.io.*; import java.util.*; public class CF3D { static class P implements Comparable<P> { int cost, i; P (int cost, int i) { this.cost = cost; this.i = i; } @Override public int compareTo(P p) { return this.cost - p.cost; } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); char[] cc = br.readLine().toCharArray(); int n = cc.length; int m = 0; for (int i = 0; i < n; i++) if (cc[i] == '?') m++; int[][] pp = new int[m][2]; for (int j = 0; j < m; j++) { String[] ss = br.readLine().split(" "); pp[j][0] = Integer.parseInt(ss[0]); pp[j][1] = Integer.parseInt(ss[1]); } int y = 0, ymin = 0; int imin = 0; for (int i = 1, j = 0; i <= n; i++) if (cc[i - 1] == '(') { y++; } else if (cc[i - 1] == ')') { y--; if (y < ymin) { ymin = y; imin = i; } } else { if (pp[j][0] <= pp[j][1]) { y++; } else { y--; if (y < ymin) { ymin = y; imin = i; } } j++; } long cost = 0; PriorityQueue<P> q = new PriorityQueue<>(); y = 0; for (int i = 1, j = 0; i <= imin; i++) { if (cc[i - 1] == '(') { y++; } else if (cc[i - 1] == ')') { y--; } else { if (pp[j][0] <= pp[j][1]) { y++; cc[i - 1] = '('; cost += pp[j][0]; } else { y--; cc[i - 1] = ')'; cost += pp[j][1]; q.add(new P(pp[j][0] - pp[j][1], i - 1)); } j++; } if (y < 0) { P p = q.poll(); if (p == null) { System.out.println(-1); return; } y += 2; cc[p.i] = '('; cost += p.cost; } } q.clear(); y = 0; for (int i = n - 1, j = m - 1; i >= imin; i--) { if (cc[i] == ')') { y++; } else if (cc[i] == '(') { y--; } else { if (pp[j][0] > pp[j][1]) { y++; cc[i] = ')'; cost += pp[j][1]; } else { y--; cc[i] = '('; cost += pp[j][0]; q.add(new P(pp[j][1] - pp[j][0], i)); } j--; } if (y < 0) { P p = q.poll(); if (p == null) { System.out.println(-1); return; } y += 2; cc[p.i] = ')'; cost += p.cost; } } System.out.println(cost); System.out.println(new String(cc)); } }
Java
["(??)\n1 2\n2 8"]
1 second
["4\n()()"]
null
Java 8
standard input
[ "greedy" ]
970cd8ce0cf7214b7f2be337990557c9
The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai,  bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one.
2,600
Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them.
standard output
PASSED
a98a1b31f42b27f2c644cdcd6664e1c8
train_002.jsonl
1267963200
This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest.
64 megabytes
import java.util.*; /** * Created by huang on 17-6-10. */ public class Main { private static class cost { int a, b; public cost(int a, int b) { this.a = a; this.b = b; } } public static void main(String[] args) { Scanner in = new Scanner(System.in); char[] str = in.next().toCharArray(); Queue<cost> queue = new PriorityQueue<>(new Comparator<cost>() { @Override public int compare(cost c1, cost c2) { return c2.b - c1.b; } }); int x = 0; long ans = 0; for (int i = 0; i < str.length; i++) { if (str[i] == '(') { x++; } else if (str[i] == ')') { x--; } else { x--; int a = in.nextInt(), b = in.nextInt(); queue.add(new cost(i , b - a)); str[i] = ')'; ans += b; } if (x < 0 && queue.isEmpty()) { ans = -1; break; } if (x<0) { cost c = queue.poll(); ans -= c.b; str[c.a] = '('; x += 2; } } if (x > 0) { ans = -1; } System.out.println(ans); if (ans != -1) { System.out.println(str); } } }
Java
["(??)\n1 2\n2 8"]
1 second
["4\n()()"]
null
Java 8
standard input
[ "greedy" ]
970cd8ce0cf7214b7f2be337990557c9
The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai,  bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one.
2,600
Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them.
standard output
PASSED
4d5656a294ccf9ccca52c8725d26faf8
train_002.jsonl
1267963200
This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest.
64 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.PriorityQueue; import java.util.StringTokenizer; public class CF3D { static class Pair implements Comparable<Pair> { int idx, cost; Pair(int i, int j) { idx = i; cost = j; } @Override public int compareTo(Pair o) { return cost - o.cost; } } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); char[] s = sc.next().toCharArray(); PriorityQueue<Pair> pq = new PriorityQueue<Pair>(); StringBuilder sb = new StringBuilder(); int curr = 0; long total = 0; boolean check = true; for (int i = 0; i < s.length; i++) { if (s[i] == '(') curr++; else if (s[i] == ')') curr--; else { int open = sc.nextInt(); int close = sc.nextInt(); s[i] = ')'; curr--; total += close; pq.add(new Pair(i, -close + open)); } if (curr < 0) { if (pq.isEmpty()) { check = false; } else { Pair p = pq.remove(); total += p.cost; s[p.idx] = '('; curr += 2; } } } if (!check || curr != 0) System.out.println(-1); else { System.out.println(total); for (int i = 0; i < s.length; i++) sb.append(s[i]); System.out.println(sb); } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader r) { br = new BufferedReader(r); } 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(); } } }
Java
["(??)\n1 2\n2 8"]
1 second
["4\n()()"]
null
Java 8
standard input
[ "greedy" ]
970cd8ce0cf7214b7f2be337990557c9
The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai,  bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one.
2,600
Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them.
standard output
PASSED
939125ea719e7e2502b6badd24b34503
train_002.jsonl
1267963200
This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest.
64 megabytes
import java.io.*; import java.util.*; public class CF3D_brackets { public static class cost implements Comparable<cost> { int cost; int index; cost(int c, int i) { this.cost=c; this.index=i; } public int compareTo(cost a) { return this.cost-a.cost; } } public static void main (String args[]) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); //BufferedReader reader = new BufferedReader(new FileReader("brackets.txt")); char [] items=reader.readLine().toCharArray(); if(items.length%2==1) { System.out.println("-1"); return; } int equality=0; long totalCost=0; PriorityQueue<cost> q = new PriorityQueue<cost>(); for(int i=0; i<items.length; i++) { if(items[i]==')') { equality--; } else if(items[i]=='(') { equality++; } else if(items[i]=='?') { String [] values=reader.readLine().split(" "); int first=Integer.parseInt(values[0]); int second=Integer.parseInt(values[1]); items[i]=')'; equality--; q.add(new cost(first-second,i)); totalCost+=second; } if(!q.isEmpty()&&equality==-1) { cost temp=q.poll(); totalCost+=temp.cost; items[temp.index]='('; equality+=2; } else if(equality<-1) { break; } } StringBuilder sb=new StringBuilder(); if(equality==0) { System.out.println(totalCost); for(int i=0; i<items.length; i++) { sb.append(items[i]); } System.out.println(sb+"\n"); } else { System.out.println("-1"); } } }
Java
["(??)\n1 2\n2 8"]
1 second
["4\n()()"]
null
Java 8
standard input
[ "greedy" ]
970cd8ce0cf7214b7f2be337990557c9
The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai,  bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one.
2,600
Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them.
standard output
PASSED
7212de80f31e7fc11a45ff7ce147fc1a
train_002.jsonl
1267963200
This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest.
64 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.PriorityQueue; import java.util.StringTokenizer; import java.util.TreeMap; public class D3 { public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); String s = in.nextLine(); char [] brackets = new char[s.length()]; PriorityQueue<Pair> pq = new PriorityQueue<>(); long res = 0; int open = 0; for(int i=0;i<s.length();i++) { if(s.charAt(i) == '(') open++; else { if(s.charAt(i) == ')') open--; else { int costop = in.nextInt(); int costcl = in.nextInt(); pq.add(new Pair(i, costop - costcl)); brackets[i] = ')'; res += costcl; open--; } } if(open < 0) { if(pq.isEmpty()) { res = -1; break; } else { Pair min = pq.poll(); brackets[min.idx] = '('; res+=min.cost; open += 2; } } } if(open != 0) res = -1; System.out.println(res); if(res!=-1) { for(int i=0;i<s.length();i++) if(s.charAt(i) == '?') System.out.print(brackets[i]); else System.out.print(s.charAt(i)); } System.out.println(); } static class Pair implements Comparable<Pair> { int idx; int cost; Pair(int x, int y) { idx = x; cost = y; } public int compareTo(Pair o) { if(cost != o.cost) return cost - o.cost; return idx - o.idx; } } 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
["(??)\n1 2\n2 8"]
1 second
["4\n()()"]
null
Java 8
standard input
[ "greedy" ]
970cd8ce0cf7214b7f2be337990557c9
The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai,  bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one.
2,600
Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them.
standard output
PASSED
8c1edffb60d52301d93214bbaf890a01
train_002.jsonl
1267963200
This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest.
64 megabytes
import java.util.PriorityQueue; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; public class Main { public static void main(String[] args) throws IOException { BufferedReader scan = new BufferedReader(new InputStreamReader( System.in)); char[] word = scan.readLine().toCharArray(); int openCount = 0; long total_cost = 0; PriorityQueue<Pair> entries = new PriorityQueue<Pair>(); if (word[0] != ')' && word[word.length - 1] != '(') { for (int i = 0; i < word.length; i++) { char c = word[i]; if (c == '(') openCount++; else if (c == ')') openCount--; else { // always add close brace String[] lines = scan.readLine().split("\\s"); Pair cost = new Pair(i, Integer.parseInt(lines[0]), Integer.parseInt(lines[1])); word[i] = ')'; openCount--; total_cost += cost.close; entries.add(cost); } if (openCount < 0) { // if too many closes, replace with the // best Pair min = entries.poll(); if (min != null) { total_cost += min.open; total_cost -= min.close; word[min.pos] = '('; openCount += 2; } } } if (openCount == 0) { System.out.println(total_cost); System.out.println(word); } else System.out.println(-1); } else System.out.println(-1); } } class Pair implements Comparable { int pos, open, close; public Pair() { pos = -1; } public Pair(int p, int o, int c) { pos = p; open = o; close = c; } @Override public int compareTo(Object o) { Pair other = (Pair) o; Integer me = this.close - this.open; Integer them = other.close - other.open; return them.compareTo(me); } }
Java
["(??)\n1 2\n2 8"]
1 second
["4\n()()"]
null
Java 8
standard input
[ "greedy" ]
970cd8ce0cf7214b7f2be337990557c9
The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai,  bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one.
2,600
Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them.
standard output
PASSED
4014a9f79d7536f731c092a74f5dd1ea
train_002.jsonl
1300033800
Professor Phunsuk Wangdu has performed some experiments on rays. The setup for n rays is as follows.There is a rectangular box having exactly n holes on the opposite faces. All rays enter from the holes of the first side and exit from the holes of the other side of the box. Exactly one ray can enter or exit from each hole. The holes are in a straight line. Professor Wangdu is showing his experiment to his students. He shows that there are cases, when all the rays are intersected by every other ray. A curious student asked the professor: "Sir, there are some groups of rays such that all rays in that group intersect every other ray in that group. Can we determine the number of rays in the largest of such groups?".Professor Wangdu now is in trouble and knowing your intellect he asks you to help him.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.StringTokenizer; public class D implements Runnable { final private int inf = (int)1e+9; private int upper_bound( int[] a, int l, int r, int val ) { while (l < r) { int m = (l + r) >> 1; if (a[m] <= val) l = m + 1; else r = m; } return r; } private void solve( int n ) throws IOException { int[] p = new int[n]; for (int i = 0; i < n; ++i) p[i] = nextInt(); int[] q = new int[n]; for (int i = 0; i < n; ++i) q[i] = nextInt(); int[] id = new int[n]; int nextId = 0; for (int i = 0; i < n; ++i) id[p[i] - 1] = nextId++; for (int i = 0; i < n; i++) { q[i] = id[q[i] - 1]; } for (int l = 0, r = n - 1; l < r; l++, r--) { int t = q[l]; q[l] = q[r]; q[r] = t; } int[] d = new int[n + 1]; int[] no = new int[n + 1]; Arrays.fill(d, +inf ); d[0] = -inf; no[0] = -1; int[] prev = new int[n]; Arrays.fill(prev, -1); for (int i = 0; i < n; i++) { int j = upper_bound(d, 0, i + 1, q[i]); assert(j > 0 && d[j - 1] <= q[i] && q[i] < d[j]); d[j] = q[i]; no[j] = i; prev[i] = no[j - 1]; } ArrayList<Integer> ans = new ArrayList<Integer>(); for (int i = n; i > 0; i--) { if (d[i] < +inf) { for (int j = no[i]; j != -1; j = prev[j]) { ans.add(q[j]); } break; } } Collections.reverse(ans); out.println(ans.size()); } private void solve() throws IOException { Integer n; while ((n = nextInt()) != null) { solve(n); } } public static void main(String[] args) { new Thread(new D()).start(); } private BufferedReader in; private PrintWriter out; private StringTokenizer st; @Override public void run() { // TODO Auto-generated method stub try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); solve(); out.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); System.exit(-1); } } Integer nextInt() throws IOException { String s = next(); return s == null ? null : Integer.parseInt(s); } BigInteger nextBigInteger() throws IOException { String s = next(); return (s == null) ? null : new BigInteger(s); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) { String str = in.readLine(); if (str == null) return null; st = new StringTokenizer(str); } return st.nextToken(); } }
Java
["5\n1 4 5 2 3\n3 4 2 1 5", "3\n3 1 2\n2 3 1"]
5 seconds
["3", "2"]
NoteFor the first test case, the figure is shown above. The output of the first test case is 3, since the rays number 1, 4 and 3 are the ones which are intersected by each other one i.e. 1 is intersected by 4 and 3, 3 is intersected by 4 and 1, and 4 is intersected by 1 and 3. Hence every ray in this group is intersected by each other one. There does not exist any group containing more than 3 rays satisfying the above-mentioned constraint.
Java 6
standard input
[ "dp", "binary search", "data structures" ]
b0ef9cda01a01cad22e7f4c49e74e85c
The first line contains n (1 ≤ n ≤ 106), the number of rays. The second line contains n distinct integers. The i-th integer xi (1 ≤ xi ≤ n) shows that the xi-th ray enters from the i-th hole. Similarly, third line contains n distinct integers. The i-th integer yi (1 ≤ yi ≤ n) shows that the yi-th ray exits from the i-th hole. All rays are numbered from 1 to n.
1,900
Output contains the only integer which is the number of rays in the largest group of rays all of which intersect each other.
standard output
PASSED
4af4a4eebd4a750a0cf3351fc9e693c8
train_002.jsonl
1300033800
Professor Phunsuk Wangdu has performed some experiments on rays. The setup for n rays is as follows.There is a rectangular box having exactly n holes on the opposite faces. All rays enter from the holes of the first side and exit from the holes of the other side of the box. Exactly one ray can enter or exit from each hole. The holes are in a straight line. Professor Wangdu is showing his experiment to his students. He shows that there are cases, when all the rays are intersected by every other ray. A curious student asked the professor: "Sir, there are some groups of rays such that all rays in that group intersect every other ray in that group. Can we determine the number of rays in the largest of such groups?".Professor Wangdu now is in trouble and knowing your intellect he asks you to help him.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class D { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int n = Integer.parseInt(in.readLine()); StringTokenizer st = new StringTokenizer(in.readLine()); int[] x = new int[n]; for (int i = 0; i < n; ++i) { x[i] = Integer.parseInt(st.nextToken()) - 1; } st = new StringTokenizer(in.readLine()); int[] y = new int[n]; for (int i = 0; i < n; ++i) { y[Integer.parseInt(st.nextToken()) - 1] = i; } int[] posl = new int[n]; for (int i = 0; i < n; ++i) { posl[i] = y[x[i]]; } for (int i = 0; i < n; ++i) { posl[i] = n - 1 - posl[i]; } int[] lastOf = new int[n + 1]; Arrays.fill(lastOf, Integer.MAX_VALUE); lastOf[1] = posl[0]; int len = 1; for (int i = 1; i < n; ++i) { int lo = 0, hi = len + 1; while (hi > lo + 1) { int mid = (hi + lo) / 2; if (posl[i] > lastOf[mid]) { lo = mid; } else { hi = mid; } } int max = lo; if (max == len) { ++len; } lastOf[max + 1] = posl[i]; } out.print(len); in.close(); out.close(); } }
Java
["5\n1 4 5 2 3\n3 4 2 1 5", "3\n3 1 2\n2 3 1"]
5 seconds
["3", "2"]
NoteFor the first test case, the figure is shown above. The output of the first test case is 3, since the rays number 1, 4 and 3 are the ones which are intersected by each other one i.e. 1 is intersected by 4 and 3, 3 is intersected by 4 and 1, and 4 is intersected by 1 and 3. Hence every ray in this group is intersected by each other one. There does not exist any group containing more than 3 rays satisfying the above-mentioned constraint.
Java 6
standard input
[ "dp", "binary search", "data structures" ]
b0ef9cda01a01cad22e7f4c49e74e85c
The first line contains n (1 ≤ n ≤ 106), the number of rays. The second line contains n distinct integers. The i-th integer xi (1 ≤ xi ≤ n) shows that the xi-th ray enters from the i-th hole. Similarly, third line contains n distinct integers. The i-th integer yi (1 ≤ yi ≤ n) shows that the yi-th ray exits from the i-th hole. All rays are numbered from 1 to n.
1,900
Output contains the only integer which is the number of rays in the largest group of rays all of which intersect each other.
standard output
PASSED
87dc1b202bc2fbfe7af6c4917671ad63
train_002.jsonl
1300033800
Professor Phunsuk Wangdu has performed some experiments on rays. The setup for n rays is as follows.There is a rectangular box having exactly n holes on the opposite faces. All rays enter from the holes of the first side and exit from the holes of the other side of the box. Exactly one ray can enter or exit from each hole. The holes are in a straight line. Professor Wangdu is showing his experiment to his students. He shows that there are cases, when all the rays are intersected by every other ray. A curious student asked the professor: "Sir, there are some groups of rays such that all rays in that group intersect every other ray in that group. Can we determine the number of rays in the largest of such groups?".Professor Wangdu now is in trouble and knowing your intellect he asks you to help him.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Scanner; import java.util.StringTokenizer; public class D { static HashMap<Integer, Integer> upMap = new HashMap<Integer, Integer>(); public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int N = Integer.parseInt(in.readLine()); StringTokenizer tokens = new StringTokenizer(in.readLine()); for (int i = 1; i <= N; i++) { int a = Integer.parseInt(tokens.nextToken()); upMap.put(a, i); } int [] a = new int[N]; int k=0; tokens = new StringTokenizer(in.readLine()); for (int i = 1; i <= N; i++) { int ab = Integer.parseInt(tokens.nextToken()); a[k++] = -upMap.get(ab); } System.out.println(LongestIncreasingSequence.LISLength(a)); } } class LongestIncreasingSequence { public static int binarySearchNear(int[] arr, int end, int value) { int low = 0, high = end; if (value < arr[0]) return 0; if (value > arr[end]) return end + 1; while (low <= high) { int middle = (low + high) / 2; if (low == high) { if (arr[low] == value) return low; else return low; } else { if (arr[middle] == value) { return middle; } if (value < arr[middle]) { high = middle; } else { low = middle + 1; } } } return -1; } public static int LISLength(int[] arr) { int size = arr.length; int d[] = new int[size]; d[0] = arr[0]; int end = 0; for (int i = 1; i < size; i++) { int index = binarySearchNear(d, end, arr[i]); if (index <= end) d[index] = arr[i]; else { end++; d[end] = arr[i]; } } return end + 1; } public static int[] LIS(int[] arr) { int size = arr.length; int mat[][] = new int[size][size]; int d[] = new int[size]; mat[0][0] = arr[0]; d[0] = arr[0]; int end = 0; for (int i = 1; i < size; i++) { int index = binarySearchNear(d, end, arr[i]); mat[index][index] = arr[i]; for (int j = 0; j < index; j++) mat[index][j] = mat[index - 1][j]; for (int j = 0; j < index; j++) d[j] = mat[index - 1][j]; d[index] = arr[i]; if (index > end) end++; } int ans[] = new int[end + 1]; for (int j = 0; j <= end; j++) ans[j] = mat[end][j]; return ans; } }
Java
["5\n1 4 5 2 3\n3 4 2 1 5", "3\n3 1 2\n2 3 1"]
5 seconds
["3", "2"]
NoteFor the first test case, the figure is shown above. The output of the first test case is 3, since the rays number 1, 4 and 3 are the ones which are intersected by each other one i.e. 1 is intersected by 4 and 3, 3 is intersected by 4 and 1, and 4 is intersected by 1 and 3. Hence every ray in this group is intersected by each other one. There does not exist any group containing more than 3 rays satisfying the above-mentioned constraint.
Java 6
standard input
[ "dp", "binary search", "data structures" ]
b0ef9cda01a01cad22e7f4c49e74e85c
The first line contains n (1 ≤ n ≤ 106), the number of rays. The second line contains n distinct integers. The i-th integer xi (1 ≤ xi ≤ n) shows that the xi-th ray enters from the i-th hole. Similarly, third line contains n distinct integers. The i-th integer yi (1 ≤ yi ≤ n) shows that the yi-th ray exits from the i-th hole. All rays are numbered from 1 to n.
1,900
Output contains the only integer which is the number of rays in the largest group of rays all of which intersect each other.
standard output
PASSED
aee786c9851b98cac259135b98e8689b
train_002.jsonl
1300033800
Professor Phunsuk Wangdu has performed some experiments on rays. The setup for n rays is as follows.There is a rectangular box having exactly n holes on the opposite faces. All rays enter from the holes of the first side and exit from the holes of the other side of the box. Exactly one ray can enter or exit from each hole. The holes are in a straight line. Professor Wangdu is showing his experiment to his students. He shows that there are cases, when all the rays are intersected by every other ray. A curious student asked the professor: "Sir, there are some groups of rays such that all rays in that group intersect every other ray in that group. Can we determine the number of rays in the largest of such groups?".Professor Wangdu now is in trouble and knowing your intellect he asks you to help him.
256 megabytes
import java.util.*; import java.io.File; import java.io.PrintWriter; import java.math.*; import static java.lang.Character.isDigit; import static java.lang.Character.isLowerCase; import static java.lang.Character.isUpperCase; import static java.lang.Math.*; import static java.math.BigInteger.*; import static java.util.Arrays.*; import static java.util.Collections.*; import static java.lang.Character.isDigit; public class Main{ static void debug(Object...os){ System.err.println(deepToString(os)); } void run(){ n=nextInt(); int[] as=new int[n]; for(int i=n-1;i>=0;i--){ as[nextInt()-1]=i; } is=new int[n]; for(int i=0;i<n;i++){ is[i]=as[nextInt()-1]; } System.out.println(solve()); } int n; int[] is; private int solve(){ // debug(is); Node root=new Node(0,n); for(int i=n-1;i>=0;i--){ int val=root.get(is[i]+1,n); // debug(val); root.set(is[i],val+1); } return root.get(0,n); } class Node{ Node left,right; int from,to;// [from,to) int max=0; int[] ms=null; public Node(int from,int to){ this.from=from; this.to=to; // if(from+1==to)return; if(to-from<4){ ms=new int[to-from]; return; } left=new Node(from,(from+to)/2); right=new Node((from+to)/2,to); } void set(int i,int val){ // debug("set",i,val); assert from<=i&&i<to; if(left==null){ ms[i-from]=val; // debug(ms); return; } max=max(max,val); if(i<left.to) left.set(i,val); else right.set(i,val); } int get(int s,int t){ // debug("get",s,t); assert from<=s&&t<=to; if(left==null){ int res=0; for(int i=s;i<t;i++){ res=max(res,ms[i-from]); } // debug("res",res); return res; } if(from==s&&to==t) return max; if(t<=left.to) return left.get(s,t); else if(s>=right.from) return right.get(s,t); else return max(left.get(s,left.to),right.get(right.from,t)); } } int nextInt(){ try{ int c=System.in.read(); if(c==-1) return c; while(c!='-'&&(c<'0'||'9'<c)){ c=System.in.read(); if(c==-1) return c; } if(c=='-') return -nextInt(); int res=0; do{ res*=10; res+=c-'0'; c=System.in.read(); }while('0'<=c&&c<='9'); return res; }catch(Exception e){ return -1; } } long nextLong(){ try{ int c=System.in.read(); if(c==-1) return -1; while(c!='-'&&(c<'0'||'9'<c)){ c=System.in.read(); if(c==-1) return -1; } if(c=='-') return -nextLong(); long res=0; do{ res*=10; res+=c-'0'; c=System.in.read(); }while('0'<=c&&c<='9'); return res; }catch(Exception e){ return -1; } } double nextDouble(){ return Double.parseDouble(next()); } String next(){ try{ StringBuilder res=new StringBuilder(""); int c=System.in.read(); while(Character.isWhitespace(c)) c=System.in.read(); do{ res.append((char)c); }while(!Character.isWhitespace(c=System.in.read())); return res.toString(); }catch(Exception e){ return null; } } String nextLine(){ try{ StringBuilder res=new StringBuilder(""); int c=System.in.read(); while(c=='\r'||c=='\n') c=System.in.read(); do{ res.append((char)c); c=System.in.read(); }while(c!='\r'&&c!='\n'); return res.toString(); }catch(Exception e){ return null; } } public static void main(String[] args){ new Main().run(); } }
Java
["5\n1 4 5 2 3\n3 4 2 1 5", "3\n3 1 2\n2 3 1"]
5 seconds
["3", "2"]
NoteFor the first test case, the figure is shown above. The output of the first test case is 3, since the rays number 1, 4 and 3 are the ones which are intersected by each other one i.e. 1 is intersected by 4 and 3, 3 is intersected by 4 and 1, and 4 is intersected by 1 and 3. Hence every ray in this group is intersected by each other one. There does not exist any group containing more than 3 rays satisfying the above-mentioned constraint.
Java 6
standard input
[ "dp", "binary search", "data structures" ]
b0ef9cda01a01cad22e7f4c49e74e85c
The first line contains n (1 ≤ n ≤ 106), the number of rays. The second line contains n distinct integers. The i-th integer xi (1 ≤ xi ≤ n) shows that the xi-th ray enters from the i-th hole. Similarly, third line contains n distinct integers. The i-th integer yi (1 ≤ yi ≤ n) shows that the yi-th ray exits from the i-th hole. All rays are numbered from 1 to n.
1,900
Output contains the only integer which is the number of rays in the largest group of rays all of which intersect each other.
standard output
PASSED
1a9263773c7900051268dbda2779fb2c
train_002.jsonl
1300033800
Professor Phunsuk Wangdu has performed some experiments on rays. The setup for n rays is as follows.There is a rectangular box having exactly n holes on the opposite faces. All rays enter from the holes of the first side and exit from the holes of the other side of the box. Exactly one ray can enter or exit from each hole. The holes are in a straight line. Professor Wangdu is showing his experiment to his students. He shows that there are cases, when all the rays are intersected by every other ray. A curious student asked the professor: "Sir, there are some groups of rays such that all rays in that group intersect every other ray in that group. Can we determine the number of rays in the largest of such groups?".Professor Wangdu now is in trouble and knowing your intellect he asks you to help him.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Locale; import java.util.StringTokenizer; public class D implements Runnable { int[] line; void setEl(int key, int val) { setEl(key, val, 1 << 20); } void setEl(int key, int val, int shift) { if (shift != 0) { line[key + shift] = Math.max(line[key + shift], val); setEl(key / 2, val, shift >> 1); } } int maxi(int left, int right) { return maxi(left, right, 1 << 20); } int maxi(int left, int right, int shift) { if (shift == 0 || left > right) { return 0; } int res = 0; if (left == right) { return line[left + shift]; } res = left % 2 == 1 ? Math.max(res, line[left + shift]) : res; left += left % 2; res = right % 2 == 0 ? Math.max(res, line[right + shift]) : res; right -= (right + 1) % 2; return Math.max(res, maxi(left / 2, right / 2, shift / 2)); } private void solve() throws IOException { int n = nextInt(); int[] a = new int[n]; int[] b = new int[n]; line = new int[1 << 21]; for (int i = 0; i < n; ++i) { a[nextInt() - 1] = i; } for (int i = 0; i < n; ++i) { b[a[nextInt() - 1]] = i; } //System.err.println(Arrays.toString(b)); for (int i = 0; 2 * i < n; ++i) { int tmp = b[i]; b[i] = b[n - i - 1]; b[n - 1 - i] = tmp; } for (int i = 0; i < n; ++i) { int sz = maxi(0, b[i] - 1); setEl(b[i], sz + 1); } out.println(maxi(0, n)); } /** * @param args */ public static void main(String[] args) { new Thread(new D()).start(); } private BufferedReader br; private StringTokenizer st; private PrintWriter out; @Override public void run() { try { Locale.setDefault(Locale.US); br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(""); out = new PrintWriter(System.out); solve(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } String next() throws IOException { while (!st.hasMoreTokens()) { String temp = br.readLine(); if (temp == null) { return null; } st = new StringTokenizer(temp); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } }
Java
["5\n1 4 5 2 3\n3 4 2 1 5", "3\n3 1 2\n2 3 1"]
5 seconds
["3", "2"]
NoteFor the first test case, the figure is shown above. The output of the first test case is 3, since the rays number 1, 4 and 3 are the ones which are intersected by each other one i.e. 1 is intersected by 4 and 3, 3 is intersected by 4 and 1, and 4 is intersected by 1 and 3. Hence every ray in this group is intersected by each other one. There does not exist any group containing more than 3 rays satisfying the above-mentioned constraint.
Java 6
standard input
[ "dp", "binary search", "data structures" ]
b0ef9cda01a01cad22e7f4c49e74e85c
The first line contains n (1 ≤ n ≤ 106), the number of rays. The second line contains n distinct integers. The i-th integer xi (1 ≤ xi ≤ n) shows that the xi-th ray enters from the i-th hole. Similarly, third line contains n distinct integers. The i-th integer yi (1 ≤ yi ≤ n) shows that the yi-th ray exits from the i-th hole. All rays are numbered from 1 to n.
1,900
Output contains the only integer which is the number of rays in the largest group of rays all of which intersect each other.
standard output
PASSED
9f044be7e86b57ed36d592d1af07eefb
train_002.jsonl
1300033800
Professor Phunsuk Wangdu has performed some experiments on rays. The setup for n rays is as follows.There is a rectangular box having exactly n holes on the opposite faces. All rays enter from the holes of the first side and exit from the holes of the other side of the box. Exactly one ray can enter or exit from each hole. The holes are in a straight line. Professor Wangdu is showing his experiment to his students. He shows that there are cases, when all the rays are intersected by every other ray. A curious student asked the professor: "Sir, there are some groups of rays such that all rays in that group intersect every other ray in that group. Can we determine the number of rays in the largest of such groups?".Professor Wangdu now is in trouble and knowing your intellect he asks you to help him.
256 megabytes
import java.io.*; import java.util.*; public class D{ void solve()throws Exception { int n=nextInt(); int[]x=new int[n]; int[]y=new int[n]; for(int i=0;i<n;i++) { x[i]=nextInt()-1; } for(int i=0;i<n;i++) { y[i]=nextInt()-1; } int[]p=new int[n]; for(int i=0;i<n;i++) { p[y[i]]=i; } int[]a=new int[n]; for(int i=0;i<n;i++) { a[i]=p[x[i]]; } int[]rev=new int[n]; for(int i=0;i<n;i++) rev[i]=a[n-1-i]; int res=get(rev,n); System.out.println(res); } int get(int[]a,int n) { int[]min=new int[n+1]; Arrays.fill(min,-1); min[0]=a[0]; int L=1; for(int i=1;i<n;i++) { if(a[i]<=min[0]) { min[0]=a[i]; continue; } int low=0; int high=L; while(high-low>1) { int mid=(low+high)/2; if(min[mid]<=a[i]) low=mid; else high=mid; } if(low==L-1) { min[L++]=a[i]; } else { min[low+1]=Math.min(min[low+1],a[i]); } } return L; } BufferedReader reader; PrintWriter writer; StringTokenizer stk; void run()throws Exception { reader=new BufferedReader(new InputStreamReader(System.in)); stk=null; writer=new PrintWriter(System.out); solve(); //reader.close(); //writer.close(); } int nextInt()throws Exception { return Integer.parseInt(nextToken()); } long nextLong()throws Exception { return Long.parseLong(nextToken()); } double nextDouble()throws Exception { return Double.parseDouble(nextToken()); } String nextString()throws Exception { return nextToken(); } String nextLine()throws Exception { return reader.readLine(); } String nextToken()throws Exception { if(stk==null || !stk.hasMoreTokens()) { stk=new StringTokenizer(nextLine()); return nextToken(); } return stk.nextToken(); } public static void main(String[]a) throws Exception { new D().run(); } }
Java
["5\n1 4 5 2 3\n3 4 2 1 5", "3\n3 1 2\n2 3 1"]
5 seconds
["3", "2"]
NoteFor the first test case, the figure is shown above. The output of the first test case is 3, since the rays number 1, 4 and 3 are the ones which are intersected by each other one i.e. 1 is intersected by 4 and 3, 3 is intersected by 4 and 1, and 4 is intersected by 1 and 3. Hence every ray in this group is intersected by each other one. There does not exist any group containing more than 3 rays satisfying the above-mentioned constraint.
Java 6
standard input
[ "dp", "binary search", "data structures" ]
b0ef9cda01a01cad22e7f4c49e74e85c
The first line contains n (1 ≤ n ≤ 106), the number of rays. The second line contains n distinct integers. The i-th integer xi (1 ≤ xi ≤ n) shows that the xi-th ray enters from the i-th hole. Similarly, third line contains n distinct integers. The i-th integer yi (1 ≤ yi ≤ n) shows that the yi-th ray exits from the i-th hole. All rays are numbered from 1 to n.
1,900
Output contains the only integer which is the number of rays in the largest group of rays all of which intersect each other.
standard output
PASSED
40409bfeb3c7fe59bc9c23cfc6ec7404
train_002.jsonl
1300033800
Professor Phunsuk Wangdu has performed some experiments on rays. The setup for n rays is as follows.There is a rectangular box having exactly n holes on the opposite faces. All rays enter from the holes of the first side and exit from the holes of the other side of the box. Exactly one ray can enter or exit from each hole. The holes are in a straight line. Professor Wangdu is showing his experiment to his students. He shows that there are cases, when all the rays are intersected by every other ray. A curious student asked the professor: "Sir, there are some groups of rays such that all rays in that group intersect every other ray in that group. Can we determine the number of rays in the largest of such groups?".Professor Wangdu now is in trouble and knowing your intellect he asks you to help him.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; public class Main { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); N = Integer.parseInt(r.readLine()); int[] a = new int[N], b = new int[N]; String[] line = r.readLine().split("[ ]+"); for(int i = 0; i < N; i++) a[i] = Integer.parseInt(line[i]); line = r.readLine().split("[ ]+"); for(int i = 0; i < N; i++) b[N - i - 1] = Integer.parseInt(line[i]); int[] map = new int[N + 10]; for(int i = 0; i < N; i++) map[a[i]] = i + 1; for(int i = 0; i < N; i++) b[i] = map[b[i]]; // System.out.println(Arrays.toString(b)); tree = new int[N + 20]; int max = 1; for(int i = 0; i < N; i++){ int get = read(b[i]); max = Math.max(get + 1, max); // System.out.println(get); update(b[i], get + 1); } System.out.println(max); } private static void update(int i, int v) { while(i <= N + 10){ tree[i] = Math.max(tree[i], v); i += (i & -i); } } private static int read(int i) { int max = 0; while(i > 0){ max = Math.max(max, tree[i]); i -= (i & -i); } return max; } static int[] tree; static int N; }
Java
["5\n1 4 5 2 3\n3 4 2 1 5", "3\n3 1 2\n2 3 1"]
5 seconds
["3", "2"]
NoteFor the first test case, the figure is shown above. The output of the first test case is 3, since the rays number 1, 4 and 3 are the ones which are intersected by each other one i.e. 1 is intersected by 4 and 3, 3 is intersected by 4 and 1, and 4 is intersected by 1 and 3. Hence every ray in this group is intersected by each other one. There does not exist any group containing more than 3 rays satisfying the above-mentioned constraint.
Java 6
standard input
[ "dp", "binary search", "data structures" ]
b0ef9cda01a01cad22e7f4c49e74e85c
The first line contains n (1 ≤ n ≤ 106), the number of rays. The second line contains n distinct integers. The i-th integer xi (1 ≤ xi ≤ n) shows that the xi-th ray enters from the i-th hole. Similarly, third line contains n distinct integers. The i-th integer yi (1 ≤ yi ≤ n) shows that the yi-th ray exits from the i-th hole. All rays are numbered from 1 to n.
1,900
Output contains the only integer which is the number of rays in the largest group of rays all of which intersect each other.
standard output
PASSED
6ab9c272f80de7ec84e4affa6602efde
train_002.jsonl
1300033800
Professor Phunsuk Wangdu has performed some experiments on rays. The setup for n rays is as follows.There is a rectangular box having exactly n holes on the opposite faces. All rays enter from the holes of the first side and exit from the holes of the other side of the box. Exactly one ray can enter or exit from each hole. The holes are in a straight line. Professor Wangdu is showing his experiment to his students. He shows that there are cases, when all the rays are intersected by every other ray. A curious student asked the professor: "Sir, there are some groups of rays such that all rays in that group intersect every other ray in that group. Can we determine the number of rays in the largest of such groups?".Professor Wangdu now is in trouble and knowing your intellect he asks you to help him.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { static int L = 0; public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(r.readLine()); int[] a = new int[n + 1], b = new int[n]; String[] line = r.readLine().split("[ ]+"); for (int i = 0; i < n; i++) a[Integer.parseInt(line[i])] = i + 1; line = r.readLine().split("[ ]+"); for (int i = 0; i < n; i++) b[n - i - 1] = a[Integer.parseInt(line[i])]; // System.out.println(Arrays.toString(b)); int[] m = new int[n + 1]; for (int i = 0; i < n; i++) { int j = binarySearch(b, m, b[i]); if (j == L || b[i] < b[m[j + 1]]) { m[j + 1] = i; L = Math.max(L, j + 1); } } System.out.println(L); } public static int binarySearch(int[] b, int[] m, int val) { int st = 1; int end = L + 1; int itr = 25; // if arr.length <= 100,000 while (itr-- > 0) { int mid = (st + end) / 2; if (b[m[mid]] >= val) { end = mid; } else if (b[m[mid]] < val) { st = mid; } } if (b[m[st]] >= val) return 0; return st; } }
Java
["5\n1 4 5 2 3\n3 4 2 1 5", "3\n3 1 2\n2 3 1"]
5 seconds
["3", "2"]
NoteFor the first test case, the figure is shown above. The output of the first test case is 3, since the rays number 1, 4 and 3 are the ones which are intersected by each other one i.e. 1 is intersected by 4 and 3, 3 is intersected by 4 and 1, and 4 is intersected by 1 and 3. Hence every ray in this group is intersected by each other one. There does not exist any group containing more than 3 rays satisfying the above-mentioned constraint.
Java 6
standard input
[ "dp", "binary search", "data structures" ]
b0ef9cda01a01cad22e7f4c49e74e85c
The first line contains n (1 ≤ n ≤ 106), the number of rays. The second line contains n distinct integers. The i-th integer xi (1 ≤ xi ≤ n) shows that the xi-th ray enters from the i-th hole. Similarly, third line contains n distinct integers. The i-th integer yi (1 ≤ yi ≤ n) shows that the yi-th ray exits from the i-th hole. All rays are numbered from 1 to n.
1,900
Output contains the only integer which is the number of rays in the largest group of rays all of which intersect each other.
standard output
PASSED
24b46bd905c948e464d8928d3b05d76a
train_002.jsonl
1300033800
Professor Phunsuk Wangdu has performed some experiments on rays. The setup for n rays is as follows.There is a rectangular box having exactly n holes on the opposite faces. All rays enter from the holes of the first side and exit from the holes of the other side of the box. Exactly one ray can enter or exit from each hole. The holes are in a straight line. Professor Wangdu is showing his experiment to his students. He shows that there are cases, when all the rays are intersected by every other ray. A curious student asked the professor: "Sir, there are some groups of rays such that all rays in that group intersect every other ray in that group. Can we determine the number of rays in the largest of such groups?".Professor Wangdu now is in trouble and knowing your intellect he asks you to help him.
256 megabytes
import static java.lang.Math.*; import static java.lang.System.currentTimeMillis; import static java.lang.System.exit; import static java.lang.System.arraycopy; import static java.util.Arrays.sort; import static java.util.Arrays.binarySearch; import static java.util.Arrays.fill; import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws IOException { try { if (new File("input.txt").exists()) System.setIn(new FileInputStream("input.txt")); } catch (SecurityException e) { } new Thread(null, new Runnable() { public void run() { try { new Main().run(); } catch (Throwable e) { e.printStackTrace(); exit(999); } } }, "1", 1 << 23).start(); } BufferedReader in; PrintWriter out; StringTokenizer st = new StringTokenizer(""); class RMQ { int m[]; int n, c; RMQ(int nn) { n = nn; c = n << 1; m = new int[c]; } void inc(int pos, int z) { pos += n; m[pos] += z; pos>>=1; for (; pos > 0; pos >>= 1) m[pos] = max(m[(pos << 1) + 1], m[(pos << 1)]); } int gMax(int l, int r) { l += n; r += n; int rez = 0; while(l <= r){ if( (l&1) == 1 ) rez = max(rez,m[l]); if( (r&1) == 0 ) rez = max(rez,m[r]); l = (l + 1)>>1; r = (r - 1)>>1; } return rez; } } private void run() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); int n = nextInt(); int pos[] = new int[n]; int newid[] = new int[n]; for (int i = 0; i < n; i++) newid[nextInt()-1] = i; for (int i = 0; i < n; i++) pos[newid[nextInt()-1]] = i; RMQ rmq = new RMQ(n); for(int i = 0; i < n; i++){ rmq.inc(pos[i],1 + rmq.gMax(pos[i],n-1)); } out.println(rmq.gMax(0,n-1)); in.close(); out.close(); } void chk(boolean b) { if (b) return; System.out.println(new Error().getStackTrace()[1]); exit(999); } void deb(String fmt, Object... args) { System.out.printf(Locale.US, fmt + "%n", args); } String nextToken() throws IOException { while (!st.hasMoreTokens()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextLine() throws IOException { st = new StringTokenizer(""); return in.readLine(); } boolean EOF() throws IOException { while (!st.hasMoreTokens()) { String s = in.readLine(); if (s == null) return true; st = new StringTokenizer(s); } return false; } }
Java
["5\n1 4 5 2 3\n3 4 2 1 5", "3\n3 1 2\n2 3 1"]
5 seconds
["3", "2"]
NoteFor the first test case, the figure is shown above. The output of the first test case is 3, since the rays number 1, 4 and 3 are the ones which are intersected by each other one i.e. 1 is intersected by 4 and 3, 3 is intersected by 4 and 1, and 4 is intersected by 1 and 3. Hence every ray in this group is intersected by each other one. There does not exist any group containing more than 3 rays satisfying the above-mentioned constraint.
Java 6
standard input
[ "dp", "binary search", "data structures" ]
b0ef9cda01a01cad22e7f4c49e74e85c
The first line contains n (1 ≤ n ≤ 106), the number of rays. The second line contains n distinct integers. The i-th integer xi (1 ≤ xi ≤ n) shows that the xi-th ray enters from the i-th hole. Similarly, third line contains n distinct integers. The i-th integer yi (1 ≤ yi ≤ n) shows that the yi-th ray exits from the i-th hole. All rays are numbered from 1 to n.
1,900
Output contains the only integer which is the number of rays in the largest group of rays all of which intersect each other.
standard output
PASSED
f4842683d58bb6388949f00ece673614
train_002.jsonl
1300033800
Professor Phunsuk Wangdu has performed some experiments on rays. The setup for n rays is as follows.There is a rectangular box having exactly n holes on the opposite faces. All rays enter from the holes of the first side and exit from the holes of the other side of the box. Exactly one ray can enter or exit from each hole. The holes are in a straight line. Professor Wangdu is showing his experiment to his students. He shows that there are cases, when all the rays are intersected by every other ray. A curious student asked the professor: "Sir, there are some groups of rays such that all rays in that group intersect every other ray in that group. Can we determine the number of rays in the largest of such groups?".Professor Wangdu now is in trouble and knowing your intellect he asks you to help him.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.InputMismatchException; import java.util.List; /** * @author Egor Kulikov (egor@egork.net) */ public class TaskD { @SuppressWarnings({"FieldCanBeLocal", "UnusedDeclaration"}) private final InputReader in; private final PrintWriter out; private final boolean testMode; private void solve() { int rayCount = in.readInt(); int[] inRays = in.readIntArray(rayCount); int[] outRays = in.readIntArray(rayCount); int[] order = new int[rayCount]; int[] reverseOut = new int[rayCount]; for (int i = 0; i < rayCount; i++) reverseOut[outRays[i] - 1] = i; for (int i = 0; i < rayCount; i++) order[i] = reverseOut[inRays[i] - 1]; int[] d = new int[rayCount + 1]; Arrays.fill(d, -Integer.MAX_VALUE); d[0] = 1; int size = 0; for (int i = 0; i < rayCount; i++) { int index = Arrays.binarySearch(d, 0, size, -order[i]); if (index < 0) { index = -index - 1; d[index] = -order[i]; size = Math.max(size, index + 1); } } out.println(size); } private static List<Test> createTests() { List<Test> tests = new ArrayList<Test>(); tests.add(new Test("5\n" + "1 4 5 2 3\n" + "3 4 2 1 5", "3")); tests.add(new Test("3\n" + "3 1 2\n" + "2 3 1", "2")); tests.add(new Test(generateTest(), "1000000")); // tests.add(new Test("", "")); // tests.add(new Test("", "")); // tests.add(new Test("", "")); // tests.add(new Test("", "")); // tests.add(new Test("", "")); // tests.add(new Test("", "")); // tests.add(new Test("", "")); // tests.add(new Test("", "")); return tests; } private static String generateTest() { StringBuilder builder = new StringBuilder(); builder.append("1000000\n"); for (int i = 1; i <= 1000000; i++) builder.append(i).append(" "); builder.append("\n"); for (int i = 1000000; i >= 1; i--) builder.append(i).append(" "); builder.append("\n"); return builder.toString(); } private void run() { //noinspection InfiniteLoopStatement // while (true) // int testCount = in.readInt(); // for (int i = 0; i < testCount; i++) solve(); exit(); } private TaskD() { @SuppressWarnings({"UnusedDeclaration"}) String id = getClass().getName().toLowerCase(); //noinspection EmptyTryBlock try { // System.setIn(new FileInputStream(id + ".in")); // System.setOut(new PrintStream(new FileOutputStream(id + ".out"))); // System.setIn(new FileInputStream("input.txt")); // System.setOut(new PrintStream(new FileOutputStream("output.txt"))); } catch (Exception e) { throw new RuntimeException(e); } in = new StreamInputReader(System.in); out = new PrintWriter(System.out); testMode = false; } @SuppressWarnings({"UnusedParameters"}) private static String check(String input, String result, String output) { // return strictCheck(result, output); return tokenCheck(result, output); } public static void main(String[] args) { if (args.length != 0 && args[0].equals("42")) test(); else new TaskD().run(); } private static void test() { List<Test> tests = createTests(); int testCase = 0; for (Test test : tests) { System.out.print("Test #" + testCase + ": "); InputReader in = new StringInputReader(test.getInput()); StringWriter out = new StringWriter(test.getOutput().length()); long time = System.currentTimeMillis(); try { new TaskD(in, new PrintWriter(out)).run(); } catch (TestException e) { time = System.currentTimeMillis() - time; String checkResult = check(test.getInput(), out.getBuffer().toString(), test.getOutput()); if (checkResult == null) System.out.print("OK"); else System.out.print("WA (" + checkResult + ")"); System.out.printf(" in %.3f s.\n", time / 1000.); } catch (Throwable e) { System.out.println("Exception thrown:"); e.printStackTrace(System.out); } testCase++; } } private static String tokenCheck(String result, String output) { StringInputReader resultStream = new StringInputReader(result); StringInputReader outputStream = new StringInputReader(output); int index = 0; boolean readingResult = false; try { while (true) { readingResult = true; String resultToken = resultStream.readString(); readingResult = false; String outputToken = outputStream.readString(); if (!resultToken.equals(outputToken)) return "'" + outputToken + "' expected at " + index + " but '" + resultToken + "' received"; index++; } } catch (InputMismatchException e) { if (readingResult) { try { outputStream.readString(); return "only " + index + " tokens received"; } catch (InputMismatchException e1) { return null; } } else return "only " + index + " tokens expected"; } } @SuppressWarnings({"UnusedDeclaration"}) private static String strictCheck(String result, String output) { if (result.equals(output)) return null; return "'" + output + "' expected but '" + result + "' received"; } @SuppressWarnings({"UnusedDeclaration"}) private static boolean isDoubleEquals(double expected, double result, double certainty) { return Math.abs(expected - result) < certainty || Math.abs(expected - result) < certainty * expected; } private TaskD(InputReader in, PrintWriter out) { this.in = in; this.out = out; testMode = true; } @SuppressWarnings({"UnusedDeclaration"}) private void exit() { out.close(); if (testMode) throw new TestException(); System.exit(0); } private static class Test { private final String input; private final String output; private Test(String input, String output) { this.input = input; this.output = output; } public String getInput() { return input; } public String getOutput() { return output; } } @SuppressWarnings({"UnusedDeclaration"}) private abstract static class InputReader { public abstract int read(); public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long readLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0() { StringBuffer buf = new StringBuffer(); int c = read(); while (c != '\n' && c != -1) { if (c != '\r') buf.appendCodePoint(c); c = read(); } return buf.toString(); } public String readLine() { String s = readLine0(); while (s.trim().length() == 0) s = readLine0(); return s; } public String readLine(boolean ignoreEmptyLines) { if (ignoreEmptyLines) return readLine(); else return readLine0(); } public BigInteger readBigInteger() { try { return new BigInteger(readString()); } catch (NumberFormatException e) { throw new InputMismatchException(); } } public char readCharacter() { int c = read(); while (isSpaceChar(c)) c = read(); return (char) c; } public double readDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, readInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, readInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public int[] readIntArray(int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = readInt(); return array; } public long[] readLongArray(int size) { long[] array = new long[size]; for (int i = 0; i < size; i++) array[i] = readLong(); return array; } public double[] readDoubleArray(int size) { double[] array = new double[size]; for (int i = 0; i < size; i++) array[i] = readDouble(); return array; } public String[] readStringArray(int size) { String[] array = new String[size]; for (int i = 0; i < size; i++) array[i] = readString(); return array; } public char[][] readTable(int rowCount, int columnCount) { char[][] table = new char[rowCount][columnCount]; for (int i = 0; i < rowCount; i++) { for (int j = 0; j < columnCount; j++) table[i][j] = readCharacter(); } return table; } public void readIntArrays(int[]... arrays) { for (int i = 0; i < arrays[0].length; i++) { for (int j = 0; j < arrays.length; j++) arrays[j][i] = readInt(); } } } private static class StreamInputReader extends InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar, numChars; public StreamInputReader(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++]; } } private static class StringInputReader extends InputReader { private Reader stream; private char[] buf = new char[1024]; private int curChar, numChars; public StringInputReader(String stream) { this.stream = new StringReader(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++]; } } private static class TestException extends RuntimeException {} }
Java
["5\n1 4 5 2 3\n3 4 2 1 5", "3\n3 1 2\n2 3 1"]
5 seconds
["3", "2"]
NoteFor the first test case, the figure is shown above. The output of the first test case is 3, since the rays number 1, 4 and 3 are the ones which are intersected by each other one i.e. 1 is intersected by 4 and 3, 3 is intersected by 4 and 1, and 4 is intersected by 1 and 3. Hence every ray in this group is intersected by each other one. There does not exist any group containing more than 3 rays satisfying the above-mentioned constraint.
Java 6
standard input
[ "dp", "binary search", "data structures" ]
b0ef9cda01a01cad22e7f4c49e74e85c
The first line contains n (1 ≤ n ≤ 106), the number of rays. The second line contains n distinct integers. The i-th integer xi (1 ≤ xi ≤ n) shows that the xi-th ray enters from the i-th hole. Similarly, third line contains n distinct integers. The i-th integer yi (1 ≤ yi ≤ n) shows that the yi-th ray exits from the i-th hole. All rays are numbered from 1 to n.
1,900
Output contains the only integer which is the number of rays in the largest group of rays all of which intersect each other.
standard output
PASSED
aaa0f05e0bbb77fdcb2e8cf7a1ddd47b
train_002.jsonl
1300033800
Professor Phunsuk Wangdu has performed some experiments on rays. The setup for n rays is as follows.There is a rectangular box having exactly n holes on the opposite faces. All rays enter from the holes of the first side and exit from the holes of the other side of the box. Exactly one ray can enter or exit from each hole. The holes are in a straight line. Professor Wangdu is showing his experiment to his students. He shows that there are cases, when all the rays are intersected by every other ray. A curious student asked the professor: "Sir, there are some groups of rays such that all rays in that group intersect every other ray in that group. Can we determine the number of rays in the largest of such groups?".Professor Wangdu now is in trouble and knowing your intellect he asks you to help him.
256 megabytes
/* * Hello! You are trying to hack my solution, are you? =) * Don't be afraid of the size, it's just a dump of useful methods like gcd, or n-th Fib number. * And I'm just too lazy to create a new .java for every task. * And if you were successful to hack my solution, please, send me this test as a message or to Abrackadabraa@gmail.com. * It can help me improve my skills and i'd be very grateful for that. * Sorry for time you spent reading this message. =) * Good luck, unknown rival. =) * */ import java.io.*; import java.math.*; import java.util.*; public class Abra { // double d = 2.2250738585072012e-308; class p{ p left = null, rigth = null; TreeSet<Integer> v = new TreeSet<Integer>(); void addP(int x) { } boolean d = true; int x = -1; p(int y) { x = y; } p(int y, int z) { d = false; for (int i = y; i <= z; i++) v.add(i); x = y; } void addLeft(int y) { p q = new p(y); left.rigth = q; q.left = left; q.rigth = this; left = q; } void addLeft(int y, int z) { p q = new p(y, z); if (y == z) q = new p(y); left.rigth = q; q.left = left; q.rigth = this; left = q; } p leftest(){ p c = this; while (c.left != null) c = c.left; return c; } } int n, k; void solve1() throws IOException { n = nextInt(); k = nextInt(); p f = null; for (int i = 1; i <= n; i++) { int t = nextInt(); if (i == 1) { f = new p(1); for (int j = 0; j < t; j++) { f.addLeft(i + k, n); } continue; } f = f.leftest(); while (true) { } } } int[] b; void solve() throws IOException { int n = nextInt(); int[] a = new int[n]; b = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt() - 1; TreeMap<Integer, Integer> tm = new TreeMap<Integer, Integer>(); for (int i = 0; i < n; i++) tm.put(nextInt() - 1, i); int c = 0; for (int i = 0; i < n; i++) { b[i] = tm.get(a[i]); } for (int i = 0; i < n; i++) b[i] = n - b[i]; out.print(LISLength(b)); } public static int binarySearchNear(int[] arr, int end, int value){ int low = 0, high = end; if(value<arr[0]) return 0; if(value>arr[end]) return end+1; while (low <=high){ int middle = (low + high)/2; if (low == high) { if (arr[low] == value) return low; else return low; }else{if (arr[middle] == value){ return middle; } if (value < arr[middle]){ high = middle; } else{ low = middle+1; } } }return-1; } public static int LISLength(int [] arr){ int size = arr.length; int d[] = new int[size]; d[0] = arr[0]; int end = 0; for(int i=1; i<size; i++){ int index =binarySearchNear(d, end, arr[i]); if (index<=end) d[index] = arr[i]; else{ end++; d[end] = arr[i]; } }return end+1; } public static void main(String[] args) throws IOException { new Abra().run(); } StreamTokenizer in; PrintWriter out; boolean oj; BufferedReader br; void init() throws IOException { oj = System.getProperty("ONLINE_JUDGE") != null; Reader reader = oj ? new InputStreamReader(System.in) : new FileReader("input.txt"); Writer writer = oj ? new OutputStreamWriter(System.out) : new FileWriter("output.txt"); br = new BufferedReader(reader); in = new StreamTokenizer(br); out = new PrintWriter(writer); } long beginTime; void run() throws IOException { beginTime = System.currentTimeMillis(); long beginMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); init(); solve(); long endMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); long endTime = System.currentTimeMillis(); if (!oj) { System.out.println("Memory used = " + (endMem - beginMem)); System.out.println("Total memory = " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())); System.out.println("Running time = " + (endTime - beginTime)); } out.flush(); } int nextInt() throws IOException { in.nextToken(); return (int) in.nval; } long nextLong() throws IOException { in.nextToken(); return (long) in.nval; } String nextString() throws IOException { in.nextToken(); return in.sval; } double nextDouble() throws IOException { in.nextToken(); return in.nval; } myLib lib = new myLib(); void time() { System.out.print("It's "); System.out.println(System.currentTimeMillis() - beginTime); } static class myLib { long fact(long x) { long a = 1; for (long i = 2; i <= x; i++) { a *= i; } return a; } long digitSum(String x) { long a = 0; for (int i = 0; i < x.length(); i++) { a += x.charAt(i) - '0'; } return a; } long digitSum(long x) { long a = 0; while (x > 0) { a += x % 10; x /= 10; } return a; } long digitMul(long x) { long a = 1; while (x > 0) { a *= x % 10; x /= 10; } return a; } int digitCubesSum(int x) { int a = 0; while (x > 0) { a += (x % 10) * (x % 10) * (x % 10); x /= 10; } return a; } double pif(double ax, double ay, double bx, double by) { return Math.sqrt((ax - bx) * (ax - bx) + (ay - by) * (ay - by)); } double pif3D(double ax, double ay, double az, double bx, double by, double bz) { return Math.sqrt((ax - bx) * (ax - bx) + (ay - by) * (ay - by) + (az - bz) * (az - bz)); } double pif3D(double[] a, double[] b) { return Math.sqrt((a[0] - b[0]) * (a[0] - b[0]) + (a[1] - b[1]) * (a[1] - b[1]) + (a[2] - b[2]) * (a[2] - b[2])); } long gcd(long a, long b) { if (a == 0 || b == 0) return 1; if (a < b) { long c = b; b = a; a = c; } while (a % b != 0) { a = a % b; if (a < b) { long c = b; b = a; a = c; } } return b; } int gcd(int a, int b) { if (a == 0 || b == 0) return 1; if (a < b) { int c = b; b = a; a = c; } while (a % b != 0) { a = a % b; if (a < b) { int c = b; b = a; a = c; } } return b; } long lcm(long a, long b) { return a * b / gcd(a, b); } int lcm(int a, int b) { return a * b / gcd(a, b); } int countOccurences(String x, String y) { int a = 0, i = 0; while (true) { i = y.indexOf(x); if (i == -1) break; a++; y = y.substring(i + 1); } return a; } int[] findPrimes(int x) { boolean[] forErato = new boolean[x - 1]; List<Integer> t = new Vector<Integer>(); int l = 0, j = 0; for (int i = 2; i < x; i++) { if (forErato[i - 2]) continue; t.add(i); l++; j = i * 2; while (j < x) { forErato[j - 2] = true; j += i; } } int[] primes = new int[l]; Iterator<Integer> iterator = t.iterator(); for (int i = 0; iterator.hasNext(); i++) { primes[i] = iterator.next().intValue(); } return primes; } int rev(int x) { int a = 0; while (x > 0) { a = a * 10 + x % 10; x /= 10; } return a; } class myDate { int d, m, y; int[] ml = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; public myDate(int da, int ma, int ya) { d = da; m = ma; y = ya; if ((ma > 12 || ma < 1 || da > ml[ma - 1] || da < 1) && !(d == 29 && m == 2 && y % 4 == 0)) { d = 1; m = 1; y = 9999999; } } void incYear(int x) { for (int i = 0; i < x; i++) { y++; if (m == 2 && d == 29) { m = 3; d = 1; return; } if (m == 3 && d == 1) { if (((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0)) { m = 2; d = 29; } return; } } } boolean less(myDate x) { if (y < x.y) return true; if (y > x.y) return false; if (m < x.m) return true; if (m > x.m) return false; if (d < x.d) return true; if (d > x.d) return false; return true; } void inc() { if ((d == 31) && (m == 12)) { y++; d = 1; m = 1; } else { if (((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0)) { ml[1] = 29; } if (d == ml[m - 1]) { m++; d = 1; } else d++; } } } int partition(int n, int l, int m) {// n - sum, l - length, m - every // part // <= m if (n < l) return 0; if (n < l + 2) return 1; if (l == 1) return 1; int c = 0; for (int i = Math.min(n - l + 1, m); i >= (n + l - 1) / l; i--) { c += partition(n - i, l - 1, i); } return c; } int rifmQuality(String a, String b) { if (a.length() > b.length()) { String c = a; a = b; b = c; } int c = 0, d = b.length() - a.length(); for (int i = a.length() - 1; i >= 0; i--) { if (a.charAt(i) == b.charAt(i + d)) c++; else break; } return c; } String numSym = "0123456789ABCDEF"; String ZFromXToYNotation(int x, int y, String z) { if (z.equals("0")) return "0"; String a = ""; // long q = 0, t = 1; BigInteger q = BigInteger.ZERO, t = BigInteger.ONE; for (int i = z.length() - 1; i >= 0; i--) { q = q.add(t.multiply(BigInteger.valueOf(z.charAt(i) - 48))); t = t.multiply(BigInteger.valueOf(x)); } while (q.compareTo(BigInteger.ZERO) == 1) { a = numSym.charAt((int) (q.mod(BigInteger.valueOf(y)).intValue())) + a; q = q.divide(BigInteger.valueOf(y)); } return a; } double angleFromXY(int x, int y) { if ((x == 0) && (y > 0)) return Math.PI / 2; if ((x == 0) && (y < 0)) return -Math.PI / 2; if ((y == 0) && (x > 0)) return 0; if ((y == 0) && (x < 0)) return Math.PI; if (x > 0) return Math.atan((double) y / x); else { if (y > 0) return Math.atan((double) y / x) + Math.PI; else return Math.atan((double) y / x) - Math.PI; } } static boolean isNumber(String x) { try { Integer.parseInt(x); } catch (NumberFormatException ex) { return false; } return true; } static boolean stringContainsOf(String x, String c) { for (int i = 0; i < x.length(); i++) { if (c.indexOf(x.charAt(i)) == -1) return false; } return true; } long pow(long a, long n) { // b > 0 if (n == 0) return 1; long k = n, b = 1, c = a; while (k != 0) { if (k % 2 == 0) { k /= 2; c *= c; } else { k--; b *= c; } } return b; } int pow(int a, int n) { // b > 0 if (n == 0) return 1; int k = n, b = 1, c = a; while (k != 0) { if (k % 2 == 0) { k /= 2; c *= c; } else { k--; b *= c; } } return b; } double pow(double a, int n) { // b > 0 if (n == 0) return 1; double k = n, b = 1, c = a; while (k != 0) { if (k % 2 == 0) { k /= 2; c *= c; } else { k--; b *= c; } } return b; } double log2(double x) { return Math.log(x) / Math.log(2); } int lpd(int[] primes, int x) {// least prime divisor int i; for (i = 0; primes[i] <= x / 2; i++) { if (x % primes[i] == 0) { return primes[i]; } } ; return x; } int np(int[] primes, int x) {// number of prime number for (int i = 0; true; i++) { if (primes[i] == x) return i; } } int[] dijkstra(int[][] map, int n, int s) { int[] p = new int[n]; boolean[] b = new boolean[n]; Arrays.fill(p, Integer.MAX_VALUE); p[s] = 0; b[s] = true; for (int i = 0; i < n; i++) { if (i != s) p[i] = map[s][i]; } while (true) { int m = Integer.MAX_VALUE, mi = -1; for (int i = 0; i < n; i++) { if (!b[i] && (p[i] < m)) { mi = i; m = p[i]; } } if (mi == -1) break; b[mi] = true; for (int i = 0; i < n; i++) if (p[mi] + map[mi][i] < p[i]) p[i] = p[mi] + map[mi][i]; } return p; } boolean isLatinChar(char x) { if (((x >= 'a') && (x <= 'z')) || ((x >= 'A') && (x <= 'Z'))) return true; else return false; } boolean isBigLatinChar(char x) { if (x >= 'A' && x <= 'Z') return true; else return false; } boolean isSmallLatinChar(char x) { if (x >= 'a' && x <= 'z') return true; else return false; } boolean isDigitChar(char x) { if (x >= '0' && x <= '9') return true; else return false; } class NotANumberException extends Exception { private static final long serialVersionUID = 1L; String mistake; NotANumberException() { mistake = "Unknown."; } NotANumberException(String message) { mistake = message; } } class Real { String num = "0"; long exp = 0; boolean pos = true; long length() { return num.length(); } void check(String x) throws NotANumberException { if (!stringContainsOf(x, "0123456789+-.eE")) throw new NotANumberException("Illegal character."); long j = 0; for (long i = 0; i < x.length(); i++) { if ((x.charAt((int) i) == '-') || (x.charAt((int) i) == '+')) { if (j == 0) j = 1; else if (j == 5) j = 6; else throw new NotANumberException("Unexpected sign."); } else if ("0123456789".indexOf(x.charAt((int) i)) != -1) { if (j == 0) j = 2; else if (j == 1) j = 2; else if (j == 2) ; else if (j == 3) j = 4; else if (j == 4) ; else if (j == 5) j = 6; else if (j == 6) ; else throw new NotANumberException("Unexpected digit."); } else if (x.charAt((int) i) == '.') { if (j == 0) j = 3; else if (j == 1) j = 3; else if (j == 2) j = 3; else throw new NotANumberException("Unexpected dot."); } else if ((x.charAt((int) i) == 'e') || (x.charAt((int) i) == 'E')) { if (j == 2) j = 5; else if (j == 4) j = 5; else throw new NotANumberException("Unexpected exponent."); } else throw new NotANumberException("O_o."); } if ((j == 0) || (j == 1) || (j == 3) || (j == 5)) throw new NotANumberException("Unexpected end."); } public Real(String x) throws NotANumberException { check(x); if (x.charAt(0) == '-') pos = false; long j = 0; String e = ""; boolean epos = true; for (long i = 0; i < x.length(); i++) { if ("0123456789".indexOf(x.charAt((int) i)) != -1) { if (j == 0) num += x.charAt((int) i); if (j == 1) { num += x.charAt((int) i); exp--; } if (j == 2) e += x.charAt((int) i); } if (x.charAt((int) i) == '.') { if (j == 0) j = 1; } if ((x.charAt((int) i) == 'e') || (x.charAt((int) i) == 'E')) { j = 2; if (x.charAt((int) (i + 1)) == '-') epos = false; } } while ((num.length() > 1) && (num.charAt(0) == '0')) num = num.substring(1); while ((num.length() > 1) && (num.charAt(num.length() - 1) == '0')) { num = num.substring(0, num.length() - 1); exp++; } if (num.equals("0")) { exp = 0; pos = true; return; } while ((e.length() > 1) && (e.charAt(0) == '0')) e = e.substring(1); try { if (e != "") if (epos) exp += Long.parseLong(e); else exp -= Long.parseLong(e); } catch (NumberFormatException exc) { if (!epos) { num = "0"; exp = 0; pos = true; } else { throw new NotANumberException("Too long exponent"); } } } public Real() { } String toString(long mantissa) { String a = "", b = ""; if (exp >= 0) { a = num; if (!pos) a = '-' + a; for (long i = 0; i < exp; i++) a += '0'; for (long i = 0; i < mantissa; i++) b += '0'; if (mantissa == 0) return a; else return a + "." + b; } else { if (exp + length() <= 0) { a = "0"; if (mantissa == 0) { return a; } if (mantissa < -(exp + length() - 1)) { for (long i = 0; i < mantissa; i++) b += '0'; return a + "." + b; } else { if (!pos) a = '-' + a; for (long i = 0; i < mantissa; i++) if (i < -(exp + length())) b += '0'; else if (i + exp >= 0) b += '0'; else b += num.charAt((int) (i + exp + length())); return a + "." + b; } } else { if (!pos) a = "-"; for (long i = 0; i < exp + length(); i++) a += num.charAt((int) i); if (mantissa == 0) return a; for (long i = exp + length(); i < exp + length() + mantissa; i++) if (i < length()) b += num.charAt((int) i); else b += '0'; return a + "." + b; } } } } boolean containsRepeats(int... num) { Set<Integer> s = new TreeSet<Integer>(); for (int d : num) if (!s.contains(d)) s.add(d); else return true; return false; } int[] rotateDice(int[] a, int n) { int[] c = new int[6]; if (n == 0) { c[0] = a[1]; c[1] = a[5]; c[2] = a[2]; c[3] = a[0]; c[4] = a[4]; c[5] = a[3]; } if (n == 1) { c[0] = a[2]; c[1] = a[1]; c[2] = a[5]; c[3] = a[3]; c[4] = a[0]; c[5] = a[4]; } if (n == 2) { c[0] = a[3]; c[1] = a[0]; c[2] = a[2]; c[3] = a[5]; c[4] = a[4]; c[5] = a[1]; } if (n == 3) { c[0] = a[4]; c[1] = a[1]; c[2] = a[0]; c[3] = a[3]; c[4] = a[5]; c[5] = a[2]; } if (n == 4) { c[0] = a[0]; c[1] = a[2]; c[2] = a[3]; c[3] = a[4]; c[4] = a[1]; c[5] = a[5]; } if (n == 5) { c[0] = a[0]; c[1] = a[4]; c[2] = a[1]; c[3] = a[2]; c[4] = a[3]; c[5] = a[5]; } return c; } int min(int... a) { int c = Integer.MAX_VALUE; for (int d : a) if (d < c) c = d; return c; } int max(int... a) { int c = Integer.MIN_VALUE; for (int d : a) if (d > c) c = d; return c; } int pos(int x) { if (x > 0) return x; else return 0; } long pos(long x) { if (x > 0) return x; else return 0; } double maxD(double... a) { double c = Double.MIN_VALUE; for (double d : a) if (d > c) c = d; return c; } double minD(double... a) { double c = Double.MAX_VALUE; for (double d : a) if (d < c) c = d; return c; } int[] normalizeDice(int[] a) { int[] c = a.clone(); if (c[0] != 0) if (c[1] == 0) c = rotateDice(c, 0); else if (c[2] == 0) c = rotateDice(c, 1); else if (c[3] == 0) c = rotateDice(c, 2); else if (c[4] == 0) c = rotateDice(c, 3); else if (c[5] == 0) c = rotateDice(rotateDice(c, 0), 0); while (c[1] != min(c[1], c[2], c[3], c[4])) c = rotateDice(c, 4); return c; } boolean sameDice(int[] a, int[] b) { for (int i = 0; i < 6; i++) if (a[i] != b[i]) return false; return true; } final double goldenRatio = (1 + Math.sqrt(5)) / 2; final double aGoldenRatio = (1 - Math.sqrt(5)) / 2; long Fib(int n) { if (n < 0) if (n % 2 == 0) return -Math.round((pow(goldenRatio, -n) - pow(aGoldenRatio, -n)) / Math.sqrt(5)); else return -Math.round((pow(goldenRatio, -n) - pow(aGoldenRatio, -n)) / Math.sqrt(5)); return Math.round((pow(goldenRatio, n) - pow(aGoldenRatio, n)) / Math.sqrt(5)); } class japaneeseComparator implements Comparator<String> { @Override public int compare(String a, String b) { int ai = 0, bi = 0; boolean m = false, ns = false; if (a.charAt(ai) <= '9' && a.charAt(ai) >= '0') { if (b.charAt(bi) <= '9' && b.charAt(bi) >= '0') m = true; else return -1; } if (b.charAt(bi) <= '9' && b.charAt(bi) >= '0') { if (a.charAt(ai) <= '9' && a.charAt(ai) >= '0') m = true; else return 1; } a += "!"; b += "!"; int na = 0, nb = 0; while (true) { if (a.charAt(ai) == '!') { if (b.charAt(bi) == '!') break; return -1; } if (b.charAt(bi) == '!') { return 1; } if (m) { int ab = -1, bb = -1; while (a.charAt(ai) <= '9' && a.charAt(ai) >= '0') { if (ab == -1) ab = ai; ai++; } while (b.charAt(bi) <= '9' && b.charAt(bi) >= '0') { if (bb == -1) bb = bi; bi++; } m = !m; if (ab == -1) { if (bb == -1) continue; else return 1; } if (bb == -1) return -1; while (a.charAt(ab) == '0' && ab + 1 != ai) { ab++; if (!ns) na++; } while (b.charAt(bb) == '0' && bb + 1 != bi) { bb++; if (!ns) nb++; } if (na != nb) ns = true; if (ai - ab < bi - bb) return -1; if (ai - ab > bi - bb) return 1; for (int i = 0; i < ai - ab; i++) { if (a.charAt(ab + i) < b.charAt(bb + i)) return -1; if (a.charAt(ab + i) > b.charAt(bb + i)) return 1; } } else { m = !m; while (true) { if (a.charAt(ai) <= 'z' && a.charAt(ai) >= 'a' && b.charAt(bi) <= 'z' && b.charAt(bi) >= 'a') { if (a.charAt(ai) < b.charAt(bi)) return -1; if (a.charAt(ai) > b.charAt(bi)) return 1; ai++; bi++; } else if (a.charAt(ai) <= 'z' && a.charAt(ai) >= 'a') return 1; else if (b.charAt(bi) <= 'z' && b.charAt(bi) >= 'a') return -1; else break; } } } if (na < nb) return 1; if (na > nb) return -1; return 0; } } Random random = new Random(); } void readIntArray(int[] a) throws IOException { for (int i = 0; i < a.length; i++) a[i] = nextInt(); } String readChars(int l) throws IOException { String r = ""; for (int i = 0; i < l; i++) r += (char) br.read(); return r; } class myFraction { long num = 0, den = 1; void reduce() { long d = lib.gcd(num, den); num /= d; den /= d; } myFraction(long ch, long zn) { num = ch; den = zn; reduce(); } myFraction add(myFraction t) { long nd = lib.lcm(den, t.den); myFraction r = new myFraction(nd / den * num + nd / t.den * t.num, nd); r.reduce(); return r; } public String toString() { return num + "/" + den; } } class myPoint { myPoint(int a, int b) { x = a; y = b; } int x, y; boolean equals(myPoint a) { if (x == a.x && y == a.y) return true; else return false; } public String toString() { return x + ":" + y; } } /* * class cubeWithLetters { String consts = "ЧКТФЭЦ"; char[][] letters = { { * 'А', 'Б', 'Г', 'В' }, { 'Д', 'Е', 'З', 'Ж' }, { 'И', 'Л', 'Н', 'М' }, { * 'О', 'П', 'С', 'Р' }, { 'У', 'Х', 'Щ', 'Ш' }, { 'Ы', 'Ь', 'Я', 'Ю' } }; * * char get(char x) { if (consts.indexOf(x) != -1) return x; for (int i = 0; * i < 7; i++) { for (int j = 0; j < 4; j++) { if (letters[i][j] == x) { if * (j == 0) return letters[i][3]; else return letters[i][j - 1]; } } } * return '!'; } * * void subrotate(int x) { char t = letters[x][0]; letters[x][0] = * letters[x][3]; letters[x][3] = letters[x][2]; letters[x][2] = * letters[x][1]; letters[x][1] = t; } * * void rotate(int x) { subrotate(x); char t; if (x == 0) { t = * letters[1][0]; letters[1][0] = letters[2][0]; letters[2][0] = * letters[3][0]; letters[3][0] = letters[5][2]; letters[5][2] = t; * * t = letters[1][1]; letters[1][1] = letters[2][1]; letters[2][1] = * letters[3][1]; letters[3][1] = letters[5][3]; letters[5][3] = t; } if (x * == 1) { t = letters[2][0]; letters[2][0] = letters[0][0]; letters[0][0] = * letters[5][0]; letters[5][0] = letters[4][0]; letters[4][0] = t; * * t = letters[2][3]; letters[2][3] = letters[0][3]; letters[0][3] = * letters[5][3]; letters[5][3] = letters[4][3]; letters[4][3] = t; } if (x * == 2) { t = letters[0][3]; letters[0][3] = letters[1][2]; letters[1][2] = * letters[4][1]; letters[4][1] = letters[3][0]; letters[3][0] = t; * * t = letters[0][2]; letters[0][2] = letters[1][1]; letters[1][1] = * letters[4][0]; letters[4][0] = letters[3][3]; letters[3][3] = t; } if (x * == 3) { t = letters[2][1]; letters[2][1] = letters[4][1]; letters[4][1] = * letters[5][1]; letters[5][1] = letters[0][1]; letters[0][1] = t; * * t = letters[2][2]; letters[2][2] = letters[4][2]; letters[4][2] = * letters[5][2]; letters[5][2] = letters[0][2]; letters[0][2] = t; } if (x * == 4) { t = letters[2][3]; letters[2][3] = letters[1][3]; letters[1][3] = * letters[5][1]; letters[5][1] = letters[3][3]; letters[3][3] = t; * * t = letters[2][2]; letters[2][2] = letters[1][2]; letters[1][2] = * letters[5][0]; letters[5][0] = letters[3][2]; letters[3][2] = t; } if (x * == 5) { t = letters[4][3]; letters[4][3] = letters[1][0]; letters[1][0] = * letters[0][1]; letters[0][1] = letters[3][2]; letters[3][2] = t; * * t = letters[4][2]; letters[4][2] = letters[1][3]; letters[1][3] = * letters[0][0]; letters[0][0] = letters[3][1]; letters[3][1] = t; } } * * public String toString(){ return " " + letters[0][0] + letters[0][1] + * "\n" + " " + letters[0][3] + letters[0][2] + "\n" + letters[1][0] + * letters[1][1] + letters[2][0] + letters[2][1] + letters[3][0] + * letters[3][1] + "\n" + letters[1][3] + letters[1][2] + letters[2][3] + * letters[2][2] + letters[3][3] + letters[3][2] + "\n" + " " + * letters[4][0] + letters[4][1] + "\n" + " " + letters[4][3] + * letters[4][2] + "\n" + " " + letters[5][0] + letters[5][1] + "\n" + " " * + letters[5][3] + letters[5][2] + "\n"; } } * * * Vector<Integer>[] a; int n, mc, c1, c2; int[] col; * * void wave(int x, int p) { for (Iterator<Integer> i = a[x].iterator(); * i.hasNext(); ) { int t = i.next(); if (t == x || t == p) continue; if * (col[t] == 0) { col[t] = mc; wave(t, x); } else { c1 = x; c2 = t; } } } * * void solve() throws IOException { * * String s = "ЕПОЕЬРИТСГХЖЗТЯПСТАПДСБИСТЧК"; //String s = * "ЗЬУОЫТВЗТЯПУБОЫТЕАЫШХЯАТЧК"; cubeWithLetters cube = new * cubeWithLetters(); for (int x = 0; x < 4; x++) { for (int y = x + 1; y < * 5; y++) { for (int z = y + 1; z < 6; z++) { cube = new cubeWithLetters(); * out.println(cube.toString()); cube.rotate(x); * out.println(cube.toString()); cube.rotate(y); * out.println(cube.toString()); cube.rotate(z); * out.println(cube.toString()); out.print(x + " " + y + " " + z + " = "); * for (int i = 0; i < s.length(); i++) { out.print(cube.get(s.charAt(i))); * } out.println(); } } } * * int a = nextInt(), b = nextInt(), x = nextInt(), y = nextInt(); * out.print((lib.min(a / (x / lib.gcd(x, y)), b / (y / lib.gcd(x, y))) * (x * / lib.gcd(x, y))) + " " + (lib.min(a / (x / lib.gcd(x, y)), b / (y / * lib.gcd(x, y))) * (y / lib.gcd(x, y)))); } */ }
Java
["5\n1 4 5 2 3\n3 4 2 1 5", "3\n3 1 2\n2 3 1"]
5 seconds
["3", "2"]
NoteFor the first test case, the figure is shown above. The output of the first test case is 3, since the rays number 1, 4 and 3 are the ones which are intersected by each other one i.e. 1 is intersected by 4 and 3, 3 is intersected by 4 and 1, and 4 is intersected by 1 and 3. Hence every ray in this group is intersected by each other one. There does not exist any group containing more than 3 rays satisfying the above-mentioned constraint.
Java 6
standard input
[ "dp", "binary search", "data structures" ]
b0ef9cda01a01cad22e7f4c49e74e85c
The first line contains n (1 ≤ n ≤ 106), the number of rays. The second line contains n distinct integers. The i-th integer xi (1 ≤ xi ≤ n) shows that the xi-th ray enters from the i-th hole. Similarly, third line contains n distinct integers. The i-th integer yi (1 ≤ yi ≤ n) shows that the yi-th ray exits from the i-th hole. All rays are numbered from 1 to n.
1,900
Output contains the only integer which is the number of rays in the largest group of rays all of which intersect each other.
standard output
PASSED
fb21d5dd111d96995d20d1389e053c71
train_002.jsonl
1300033800
Professor Phunsuk Wangdu has performed some experiments on rays. The setup for n rays is as follows.There is a rectangular box having exactly n holes on the opposite faces. All rays enter from the holes of the first side and exit from the holes of the other side of the box. Exactly one ray can enter or exit from each hole. The holes are in a straight line. Professor Wangdu is showing his experiment to his students. He shows that there are cases, when all the rays are intersected by every other ray. A curious student asked the professor: "Sir, there are some groups of rays such that all rays in that group intersect every other ray in that group. Can we determine the number of rays in the largest of such groups?".Professor Wangdu now is in trouble and knowing your intellect he asks you to help him.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class D { private final boolean useStandardIO = true; private final String inFile = "d.in"; private final String outFile = "d.out"; private void solve() throws IOException { int n = nextInt(); int[] a = new int[n]; int[] b = new int[n]; int[] c = new int[n + 1]; int[] d = new int[n]; int[] e = new int[n + 2]; for (int i = 0; i < n; ++i) a[i] = nextInt(); for (int i = 0; i < n; ++i) { b[i] = nextInt(); c[b[i]] = i; } for (int i = 0; i < n; ++i) { d[c[a[i]]] = n - i; } e[0] = Integer.MAX_VALUE; int sz = 1; for (int i = 0; i < n; ++i) { int k; if (e[0] > d[i]) { k = 0; } else { int l = 0, r = sz - 1; while (l + 1 < r) { int m = (l + r) >> 1; if (e[m] > d[i]) r = m; else l = m; } k = r; } if (k == sz - 1) { e[k] = d[i]; e[sz++] = Integer.MAX_VALUE; } else e[k] = d[i]; } writer.println(sz - 1); } public static void main(String[] args) { new D().run(); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; public void run() { try { Locale.setDefault(Locale.US); if (useStandardIO) { reader = new BufferedReader(new InputStreamReader(System.in)); writer = new PrintWriter(System.out); } else { reader = new BufferedReader(new FileReader(inFile)); writer = new PrintWriter(new FileWriter(outFile)); } tokenizer = null; solve(); reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } BigInteger nextBigInteger() throws IOException { return new BigInteger(nextToken()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }
Java
["5\n1 4 5 2 3\n3 4 2 1 5", "3\n3 1 2\n2 3 1"]
5 seconds
["3", "2"]
NoteFor the first test case, the figure is shown above. The output of the first test case is 3, since the rays number 1, 4 and 3 are the ones which are intersected by each other one i.e. 1 is intersected by 4 and 3, 3 is intersected by 4 and 1, and 4 is intersected by 1 and 3. Hence every ray in this group is intersected by each other one. There does not exist any group containing more than 3 rays satisfying the above-mentioned constraint.
Java 6
standard input
[ "dp", "binary search", "data structures" ]
b0ef9cda01a01cad22e7f4c49e74e85c
The first line contains n (1 ≤ n ≤ 106), the number of rays. The second line contains n distinct integers. The i-th integer xi (1 ≤ xi ≤ n) shows that the xi-th ray enters from the i-th hole. Similarly, third line contains n distinct integers. The i-th integer yi (1 ≤ yi ≤ n) shows that the yi-th ray exits from the i-th hole. All rays are numbered from 1 to n.
1,900
Output contains the only integer which is the number of rays in the largest group of rays all of which intersect each other.
standard output
PASSED
d3c683be221f9412a7ee1f0a49630470
train_002.jsonl
1300033800
Professor Phunsuk Wangdu has performed some experiments on rays. The setup for n rays is as follows.There is a rectangular box having exactly n holes on the opposite faces. All rays enter from the holes of the first side and exit from the holes of the other side of the box. Exactly one ray can enter or exit from each hole. The holes are in a straight line. Professor Wangdu is showing his experiment to his students. He shows that there are cases, when all the rays are intersected by every other ray. A curious student asked the professor: "Sir, there are some groups of rays such that all rays in that group intersect every other ray in that group. Can we determine the number of rays in the largest of such groups?".Professor Wangdu now is in trouble and knowing your intellect he asks you to help him.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main implements Runnable { final String filename="test"; final int base = 1<<20; int[] tree = new int[base*2]; void set(int x, int val) { x+=base; while (x>0) { tree[x] = Math.max(tree[x], val); x /=2; } } int getmax(int left, int right) { left+=base; right +=base; int ans = 0; while (left+1<right) { if (left%2!=0) { ans = Math.max(ans, tree[left]); left++; } if (right%2!=0) { right--; ans = Math.max(ans, tree[right]); } left/=2; right/=2; } if (left<right) ans = Math.max(ans, tree[left]); return ans; } void solve() throws Exception { int n = iread(); int[] x = new int[n]; int[] y = new int[n]; for (int i=0; i<n; i++) { x[i] = iread()-1; } for (int j=0; j<n; j++) { y[iread()-1] = j; } for (int i=0; i<n; i++) x[i] = n-y[x[i]]-1; int ans = 0; for (int i=0; i<n; i++) { int v = getmax(0, x[i]) + 1; set(x[i], v); ans = Math.max(ans, v); } out.write(ans+"\n"); } public static void main(String[] args) { Main inst = new Main(); new Thread(inst).run(); } int iread() { return Integer.parseInt(readword()); } long lread() { return Long.parseLong(readword()); } double dread() { return Double.parseDouble(readword()); } String readword() { try { int c = in.read(); while (c<=32) { if (c<0) return ""; c = in.read(); } StringBuilder sb = new StringBuilder(); while (c>32) { sb.append((char)c); c = in.read(); } return sb.toString(); } catch (Exception e) { e.printStackTrace(); System.exit(1); return ""; } } BufferedReader in; BufferedWriter out; public void run() { try { //in = new BufferedReader(new FileReader(filename+".in")); //out = new BufferedWriter(new FileWriter(filename+".out")); in = new BufferedReader(new InputStreamReader(System.in)); out = new BufferedWriter(new OutputStreamWriter(System.out)); solve(); out.flush(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } }
Java
["5\n1 4 5 2 3\n3 4 2 1 5", "3\n3 1 2\n2 3 1"]
5 seconds
["3", "2"]
NoteFor the first test case, the figure is shown above. The output of the first test case is 3, since the rays number 1, 4 and 3 are the ones which are intersected by each other one i.e. 1 is intersected by 4 and 3, 3 is intersected by 4 and 1, and 4 is intersected by 1 and 3. Hence every ray in this group is intersected by each other one. There does not exist any group containing more than 3 rays satisfying the above-mentioned constraint.
Java 6
standard input
[ "dp", "binary search", "data structures" ]
b0ef9cda01a01cad22e7f4c49e74e85c
The first line contains n (1 ≤ n ≤ 106), the number of rays. The second line contains n distinct integers. The i-th integer xi (1 ≤ xi ≤ n) shows that the xi-th ray enters from the i-th hole. Similarly, third line contains n distinct integers. The i-th integer yi (1 ≤ yi ≤ n) shows that the yi-th ray exits from the i-th hole. All rays are numbered from 1 to n.
1,900
Output contains the only integer which is the number of rays in the largest group of rays all of which intersect each other.
standard output
PASSED
79272f4dce68db761aef4f6ad2a38640
train_002.jsonl
1300033800
Professor Phunsuk Wangdu has performed some experiments on rays. The setup for n rays is as follows.There is a rectangular box having exactly n holes on the opposite faces. All rays enter from the holes of the first side and exit from the holes of the other side of the box. Exactly one ray can enter or exit from each hole. The holes are in a straight line. Professor Wangdu is showing his experiment to his students. He shows that there are cases, when all the rays are intersected by every other ray. A curious student asked the professor: "Sir, there are some groups of rays such that all rays in that group intersect every other ray in that group. Can we determine the number of rays in the largest of such groups?".Professor Wangdu now is in trouble and knowing your intellect he asks you to help him.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Arrays; import java.util.Locale; import java.util.StringTokenizer; @SuppressWarnings("unchecked") public class DD implements Runnable { class ITree { int shift; int[] val; public ITree(int len) { shift = len + 1; val = new int[len * 2 + 1]; for (int i = 0; i <= len * 2; i++) { val[i] = -1; } } public int findMax(int l, int r) { // System.err.println("max [" + l + ", " + r); int max = -1; l += shift; r += shift; while (l <= r) { if ((l & 1) != 0) { max = Math.max(max, val[l]); l++; } if ((r & 1) == 0) { max = Math.max(max, val[r]); r--; } l /= 2; r /= 2; } return max; } public void update(int pos, int valu) { // System.err.println("set " + pos + " = " + valu); pos += shift; while (pos >= 1) { val[pos] = Math.max(val[pos], valu); pos /= 2; } } } private void solve() throws Exception { int n = nextInt(); int[] a1 = new int[n]; int[] a2 = new int[n]; int[] inv = new int[n]; for (int i = 0; i < n; ++i) { a1[i] = nextInt() - 1; inv[a1[i]] = i; } int[] a = new int[n]; for (int i = 0; i < n; ++i) { a2[i] = nextInt() - 1; a[i] = inv[a2[i]]; } println(get(a)); } private int get(int[] a) { ITree tree = new ITree(1 << 20); int n = a.length; int ans = 0; for (int i = 0; i < n; ++i) { int val = Math.max(0, tree.findMax(a[i] + 1, n + 1)); ++val; ans = Math.max(ans, val); tree.update(a[i], val); // System.err.print(val + " "); } // System.err.println(); return ans; } private BufferedReader reader; private PrintWriter writer; private StringTokenizer tokenizer; public void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); // reader = new BufferedReader(new FileReader("a.in")); writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); solve(); reader.close(); writer.close(); } catch (Throwable e) { throw new AssertionError(e); } } private void print(final Object o) { writer.print(o); } private void println(final Object o) { writer.println(o); } private void printf(final String format, final Object... o) { writer.printf(format, o); } private double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } private String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } public static void main(String[] args) throws InterruptedException { final long startTime = System.currentTimeMillis(); Locale.setDefault(Locale.US); final Thread thread = new Thread(null, new DD(), "", 1 << 23); thread.start(); thread.join(); System.err.printf("%.3f\n", (System.currentTimeMillis() - startTime) * 0.001); } }
Java
["5\n1 4 5 2 3\n3 4 2 1 5", "3\n3 1 2\n2 3 1"]
5 seconds
["3", "2"]
NoteFor the first test case, the figure is shown above. The output of the first test case is 3, since the rays number 1, 4 and 3 are the ones which are intersected by each other one i.e. 1 is intersected by 4 and 3, 3 is intersected by 4 and 1, and 4 is intersected by 1 and 3. Hence every ray in this group is intersected by each other one. There does not exist any group containing more than 3 rays satisfying the above-mentioned constraint.
Java 6
standard input
[ "dp", "binary search", "data structures" ]
b0ef9cda01a01cad22e7f4c49e74e85c
The first line contains n (1 ≤ n ≤ 106), the number of rays. The second line contains n distinct integers. The i-th integer xi (1 ≤ xi ≤ n) shows that the xi-th ray enters from the i-th hole. Similarly, third line contains n distinct integers. The i-th integer yi (1 ≤ yi ≤ n) shows that the yi-th ray exits from the i-th hole. All rays are numbered from 1 to n.
1,900
Output contains the only integer which is the number of rays in the largest group of rays all of which intersect each other.
standard output
PASSED
81be9eb2f6e2967af054cd8d7bcec11b
train_002.jsonl
1300033800
Professor Phunsuk Wangdu has performed some experiments on rays. The setup for n rays is as follows.There is a rectangular box having exactly n holes on the opposite faces. All rays enter from the holes of the first side and exit from the holes of the other side of the box. Exactly one ray can enter or exit from each hole. The holes are in a straight line. Professor Wangdu is showing his experiment to his students. He shows that there are cases, when all the rays are intersected by every other ray. A curious student asked the professor: "Sir, there are some groups of rays such that all rays in that group intersect every other ray in that group. Can we determine the number of rays in the largest of such groups?".Professor Wangdu now is in trouble and knowing your intellect he asks you to help him.
256 megabytes
import java.io.*; import java.util.*; public class Main { // static Scanner in; static PrintWriter out; static StreamTokenizer in; static int next() throws Exception {in.nextToken(); return (int) in.nval;} static int[] max; static void add(int i, int val) { if (i == 0) return; max[i] = Math.max(max[i], val); add(i >> 1, val); } static int max(int l, int r) { if (l > r) return 0; if (l == r) return max[l]; int answ = 0; if (l % 2 == 1) { answ = Math.max(answ, max[l]); } if (r % 2 == 0) { answ = Math.max(answ, max[r]); } return Math.max(answ, max((l + 1) >> 1, (r - 1) >> 1)); } public static void main(String[] args) throws Exception { // in = new Scanner(System.in); out = new PrintWriter(System.out); in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); int n = next(); int[] x = new int[n]; int[] y = new int[n]; for (int i = 0; i < n; i++) x[next() - 1] = i; for (int i = 0; i < n; i++) y[next() - 1] = i; int[] p = new int[n]; for (int i = 0; i < n; i++) p[y[i]] = x[i]; int m = 1; while (m < n) m <<= 1; max = new int[2*m]; int answ = 0; for (int i = 0; i < n; i++) { int t = max(m + p[i], m + m - 1) + 1; // out.println(t); answ = Math.max(answ, t); add(p[i] + m, t); // for (int j = 0; j < 2*m; j++) out.print(max[j] + " "); // out.println(); } out.println(answ); out.close(); } }
Java
["5\n1 4 5 2 3\n3 4 2 1 5", "3\n3 1 2\n2 3 1"]
5 seconds
["3", "2"]
NoteFor the first test case, the figure is shown above. The output of the first test case is 3, since the rays number 1, 4 and 3 are the ones which are intersected by each other one i.e. 1 is intersected by 4 and 3, 3 is intersected by 4 and 1, and 4 is intersected by 1 and 3. Hence every ray in this group is intersected by each other one. There does not exist any group containing more than 3 rays satisfying the above-mentioned constraint.
Java 6
standard input
[ "dp", "binary search", "data structures" ]
b0ef9cda01a01cad22e7f4c49e74e85c
The first line contains n (1 ≤ n ≤ 106), the number of rays. The second line contains n distinct integers. The i-th integer xi (1 ≤ xi ≤ n) shows that the xi-th ray enters from the i-th hole. Similarly, third line contains n distinct integers. The i-th integer yi (1 ≤ yi ≤ n) shows that the yi-th ray exits from the i-th hole. All rays are numbered from 1 to n.
1,900
Output contains the only integer which is the number of rays in the largest group of rays all of which intersect each other.
standard output
PASSED
5e73ac5f7a8e806bad046a454cb88e23
train_002.jsonl
1300033800
Professor Phunsuk Wangdu has performed some experiments on rays. The setup for n rays is as follows.There is a rectangular box having exactly n holes on the opposite faces. All rays enter from the holes of the first side and exit from the holes of the other side of the box. Exactly one ray can enter or exit from each hole. The holes are in a straight line. Professor Wangdu is showing his experiment to his students. He shows that there are cases, when all the rays are intersected by every other ray. A curious student asked the professor: "Sir, there are some groups of rays such that all rays in that group intersect every other ray in that group. Can we determine the number of rays in the largest of such groups?".Professor Wangdu now is in trouble and knowing your intellect he asks you to help him.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class Main { static final int INF = (int) 1e9; int decSeq(int[] arr) { int n = arr.length; int [] din = new int[n + 1]; Arrays.fill(din, -INF); for (int i = 0; i < n; ++i) { int l = -1; int r = din.length; //[) while(r - l > 1) { int m = l + (r - l) / 2; if (din[m] < arr[i]) { r = m; } else { l = m; } } din[l + 1] = arr[i]; } int ans = 1; for (int i = din.length - 1; i > 0; --i) { if (din[i] != -INF) { ans = i + 1; break; } } return ans; } void solve() { int n = nextInt(); int[] inp = new int[n]; for (int i = 0; i < n; ++i) { inp[nextInt() - 1] = i; } int[] arr = new int[n]; for (int i = 0 ; i < n; ++i) { arr[i] = inp[nextInt() - 1]; } out.println(decSeq(arr)); } void run() { try { in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); } catch (Exception e){ e.printStackTrace(); } solve(); out.close(); } StreamTokenizer in; PrintWriter out; /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub new Main().run(); } int nextInt() { try { in.nextToken(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return (int)in.nval; } String next() { try { in.nextToken(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return in.sval; } long nextLong() { try { in.nextToken(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return (long)in.nval; } double nextDouble() { try { in.nextToken(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return in.nval; } }
Java
["5\n1 4 5 2 3\n3 4 2 1 5", "3\n3 1 2\n2 3 1"]
5 seconds
["3", "2"]
NoteFor the first test case, the figure is shown above. The output of the first test case is 3, since the rays number 1, 4 and 3 are the ones which are intersected by each other one i.e. 1 is intersected by 4 and 3, 3 is intersected by 4 and 1, and 4 is intersected by 1 and 3. Hence every ray in this group is intersected by each other one. There does not exist any group containing more than 3 rays satisfying the above-mentioned constraint.
Java 6
standard input
[ "dp", "binary search", "data structures" ]
b0ef9cda01a01cad22e7f4c49e74e85c
The first line contains n (1 ≤ n ≤ 106), the number of rays. The second line contains n distinct integers. The i-th integer xi (1 ≤ xi ≤ n) shows that the xi-th ray enters from the i-th hole. Similarly, third line contains n distinct integers. The i-th integer yi (1 ≤ yi ≤ n) shows that the yi-th ray exits from the i-th hole. All rays are numbered from 1 to n.
1,900
Output contains the only integer which is the number of rays in the largest group of rays all of which intersect each other.
standard output
PASSED
4bb5725cb70b7a9f07149336900accd0
train_002.jsonl
1300033800
Professor Phunsuk Wangdu has performed some experiments on rays. The setup for n rays is as follows.There is a rectangular box having exactly n holes on the opposite faces. All rays enter from the holes of the first side and exit from the holes of the other side of the box. Exactly one ray can enter or exit from each hole. The holes are in a straight line. Professor Wangdu is showing his experiment to his students. He shows that there are cases, when all the rays are intersected by every other ray. A curious student asked the professor: "Sir, there are some groups of rays such that all rays in that group intersect every other ray in that group. Can we determine the number of rays in the largest of such groups?".Professor Wangdu now is in trouble and knowing your intellect he asks you to help him.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; import javax.print.attribute.standard.Finishings; public class CodeE { static class Scanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public String nextLine() { try { return br.readLine(); } catch(Exception e) { throw(new RuntimeException()); } } public String next() { while(!st.hasMoreTokens()) { String l = nextLine(); if(l == null) return null; st = new StringTokenizer(l); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public int[] nextIntArray(int n) { int[] res = new int[n]; for(int i = 0; i < res.length; i++) res[i] = nextInt(); return res; } public long[] nextLongArray(int n) { long[] res = new long[n]; for(int i = 0; i < res.length; i++) res[i] = nextLong(); return res; } public double[] nextDoubleArray(int n) { double[] res = new double[n]; for(int i = 0; i < res.length; i++) res[i] = nextLong(); return res; } public void sortIntArray(int[] array) { Integer[] vals = new Integer[array.length]; for(int i = 0; i < array.length; i++) vals[i] = array[i]; Arrays.sort(vals); for(int i = 0; i < array.length; i++) array[i] = vals[i]; } public void sortLongArray(long[] array) { Long[] vals = new Long[array.length]; for(int i = 0; i < array.length; i++) vals[i] = array[i]; Arrays.sort(vals); for(int i = 0; i < array.length; i++) array[i] = vals[i]; } public void sortDoubleArray(double[] array) { Double[] vals = new Double[array.length]; for(int i = 0; i < array.length; i++) vals[i] = array[i]; Arrays.sort(vals); for(int i = 0; i < array.length; i++) array[i] = vals[i]; } } static int find_lis(int[] a) { ArrayList <Integer> b = new ArrayList <Integer> (); int[] p = new int[a.length]; int u, v; if (a.length == 0) return 0; b.add(0); for (int i = 1; i < a.length; i++) { if (a[b.get(b.size() - 1)] < a[i]) { p[i] = b.get(b.size() - 1); b.add(i); continue; } for (u = 0, v = b.size()-1; u < v;) { int c = (u + v) / 2; if (a[b.get(c)] < a[i]) u=c+1; else v=c; } if (a[i] < a[b.get(u)]) { if (u > 0) p[i] = b.get(u-1); b.set(u, i); } } for (u = b.size(), v = b.get(b.size() - 1); u-- != 0; v = p[v]) b.set(u, v); return b.size(); } public static void main(String[] args) { Scanner sc = new Scanner(); int n = sc.nextInt(); int[] vals = new int[n]; int[] reales = new int[n]; for(int i = 0; i < n; i++) reales[sc.nextInt() - 1] = i; for(int i = 0; i < n; i++) vals[reales[sc.nextInt() - 1]] = -i; System.out.println(find_lis(vals)); } }
Java
["5\n1 4 5 2 3\n3 4 2 1 5", "3\n3 1 2\n2 3 1"]
5 seconds
["3", "2"]
NoteFor the first test case, the figure is shown above. The output of the first test case is 3, since the rays number 1, 4 and 3 are the ones which are intersected by each other one i.e. 1 is intersected by 4 and 3, 3 is intersected by 4 and 1, and 4 is intersected by 1 and 3. Hence every ray in this group is intersected by each other one. There does not exist any group containing more than 3 rays satisfying the above-mentioned constraint.
Java 6
standard input
[ "dp", "binary search", "data structures" ]
b0ef9cda01a01cad22e7f4c49e74e85c
The first line contains n (1 ≤ n ≤ 106), the number of rays. The second line contains n distinct integers. The i-th integer xi (1 ≤ xi ≤ n) shows that the xi-th ray enters from the i-th hole. Similarly, third line contains n distinct integers. The i-th integer yi (1 ≤ yi ≤ n) shows that the yi-th ray exits from the i-th hole. All rays are numbered from 1 to n.
1,900
Output contains the only integer which is the number of rays in the largest group of rays all of which intersect each other.
standard output
PASSED
72bd52f0c2637acd955f98e913383e12
train_002.jsonl
1300033800
Professor Phunsuk Wangdu has performed some experiments on rays. The setup for n rays is as follows.There is a rectangular box having exactly n holes on the opposite faces. All rays enter from the holes of the first side and exit from the holes of the other side of the box. Exactly one ray can enter or exit from each hole. The holes are in a straight line. Professor Wangdu is showing his experiment to his students. He shows that there are cases, when all the rays are intersected by every other ray. A curious student asked the professor: "Sir, there are some groups of rays such that all rays in that group intersect every other ray in that group. Can we determine the number of rays in the largest of such groups?".Professor Wangdu now is in trouble and knowing your intellect he asks you to help him.
256 megabytes
import java.io.*; import java.util.*; public class Solution { private BufferedReader in; private PrintWriter out; private StringTokenizer st; void solve() throws IOException { int n = nextInt(); if (n == 0) { throw new AssertionError(); } int[] a = new int[n]; Arrays.fill(a, -1); int[] le = new int[n]; int[] ri = new int[n]; for (int i = 0; i < n; ++i) { le[nextInt() - 1] = i; } for (int i = 0; i < n; ++i) { ri[nextInt() - 1] = i; } for (int i = 0; i < n; ++i) { int u = le[i]; int v = ri[i]; if (a[u] != -1) { throw new AssertionError(); } a[u] = v; } int[] last = new int[n + 1]; Arrays.fill(last, -1); last[0] = n; for (int i : a) { int l = 0, r = n + 1; while (l < r - 1) { int mid = (l + r) / 2; if (last[mid] > i) { l = mid; } else { r = mid; } } last[r] = i; } int ans = 0; while (ans < n && last[ans + 1] != -1) { ans++; } out.println(ans); // int ans2 = 0; // int[] d = new int[n]; // for (int i = 0; i < n; ++i) { // d[i] = 1; // for (int j = 0; j < i; ++j) { // if (a[j] > a[i]) { // d[i] = Math.max(d[i], d[j] + 1); // } // } // ans2 = Math.max(ans2, d[i]); // } // if (ans != ans2) { // throw new AssertionError(); // } } Solution() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); eat(""); // Random rnd = new Random(); // while (rnd != null) { // int n = 7; // ArrayList<Integer> a = new ArrayList<Integer>(); // for (int i = 0; i < n; ++i) { // a.add(i + 1); // } // StringBuilder sb = new StringBuilder(); // sb.append(n + "\n"); // Collections.shuffle(a, rnd); // for (int i : a) { // sb.append(i + " "); // } // Collections.shuffle(a, rnd); // for (int i : a) { // sb.append(i + " "); // } // eat(sb.toString()); // solve(); // } solve(); in.close(); out.close(); } private void eat(String str) { st = new StringTokenizer(str); } String next() throws IOException { while (!st.hasMoreTokens()) { String line = in.readLine(); if (line == null) { return null; } eat(line); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } public static void main(String[] args) throws IOException { new Solution(); } }
Java
["5\n1 4 5 2 3\n3 4 2 1 5", "3\n3 1 2\n2 3 1"]
5 seconds
["3", "2"]
NoteFor the first test case, the figure is shown above. The output of the first test case is 3, since the rays number 1, 4 and 3 are the ones which are intersected by each other one i.e. 1 is intersected by 4 and 3, 3 is intersected by 4 and 1, and 4 is intersected by 1 and 3. Hence every ray in this group is intersected by each other one. There does not exist any group containing more than 3 rays satisfying the above-mentioned constraint.
Java 6
standard input
[ "dp", "binary search", "data structures" ]
b0ef9cda01a01cad22e7f4c49e74e85c
The first line contains n (1 ≤ n ≤ 106), the number of rays. The second line contains n distinct integers. The i-th integer xi (1 ≤ xi ≤ n) shows that the xi-th ray enters from the i-th hole. Similarly, third line contains n distinct integers. The i-th integer yi (1 ≤ yi ≤ n) shows that the yi-th ray exits from the i-th hole. All rays are numbered from 1 to n.
1,900
Output contains the only integer which is the number of rays in the largest group of rays all of which intersect each other.
standard output
PASSED
03135634826cfa656e3c7fb1bb6d6ac4
train_002.jsonl
1300033800
Professor Phunsuk Wangdu has performed some experiments on rays. The setup for n rays is as follows.There is a rectangular box having exactly n holes on the opposite faces. All rays enter from the holes of the first side and exit from the holes of the other side of the box. Exactly one ray can enter or exit from each hole. The holes are in a straight line. Professor Wangdu is showing his experiment to his students. He shows that there are cases, when all the rays are intersected by every other ray. A curious student asked the professor: "Sir, there are some groups of rays such that all rays in that group intersect every other ray in that group. Can we determine the number of rays in the largest of such groups?".Professor Wangdu now is in trouble and knowing your intellect he asks you to help him.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.util.Arrays; public class D61 { static StreamTokenizer in; static PrintWriter out; static int nextInt() throws IOException { in.nextToken(); return (int)in.nval; } static String nextString() throws IOException { in.nextToken(); return in.sval; } public static void main(String[] args) throws IOException { in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); int n = nextInt(); int[] a = new int[n]; int[] p = new int[n]; for (int i = 0; i < n; i++) p[nextInt()-1] = i; for (int i = 0; i < n; i++) a[p[nextInt()-1]] = i; int[] A = new int[n+1]; Arrays.fill(A, Integer.MIN_VALUE); A[0] = Integer.MAX_VALUE; int m = 0; for (int i = 0; i < n; i++) { if (a[i] < A[m]) { A[++m] = a[i]; } else { int lo = 0, hi = m; while (lo < hi) { int cur = (lo + hi + 1)/2; if (a[i] >= A[cur]) hi = cur - 1; else lo = cur; } A[lo+1] = Math.max(A[lo+1], a[i]); } } out.println(m); out.flush(); } }
Java
["5\n1 4 5 2 3\n3 4 2 1 5", "3\n3 1 2\n2 3 1"]
5 seconds
["3", "2"]
NoteFor the first test case, the figure is shown above. The output of the first test case is 3, since the rays number 1, 4 and 3 are the ones which are intersected by each other one i.e. 1 is intersected by 4 and 3, 3 is intersected by 4 and 1, and 4 is intersected by 1 and 3. Hence every ray in this group is intersected by each other one. There does not exist any group containing more than 3 rays satisfying the above-mentioned constraint.
Java 6
standard input
[ "dp", "binary search", "data structures" ]
b0ef9cda01a01cad22e7f4c49e74e85c
The first line contains n (1 ≤ n ≤ 106), the number of rays. The second line contains n distinct integers. The i-th integer xi (1 ≤ xi ≤ n) shows that the xi-th ray enters from the i-th hole. Similarly, third line contains n distinct integers. The i-th integer yi (1 ≤ yi ≤ n) shows that the yi-th ray exits from the i-th hole. All rays are numbered from 1 to n.
1,900
Output contains the only integer which is the number of rays in the largest group of rays all of which intersect each other.
standard output
PASSED
e5ca72c20a9e6a78c95cef56ef6bfc68
train_002.jsonl
1300033800
Professor Phunsuk Wangdu has performed some experiments on rays. The setup for n rays is as follows.There is a rectangular box having exactly n holes on the opposite faces. All rays enter from the holes of the first side and exit from the holes of the other side of the box. Exactly one ray can enter or exit from each hole. The holes are in a straight line. Professor Wangdu is showing his experiment to his students. He shows that there are cases, when all the rays are intersected by every other ray. A curious student asked the professor: "Sir, there are some groups of rays such that all rays in that group intersect every other ray in that group. Can we determine the number of rays in the largest of such groups?".Professor Wangdu now is in trouble and knowing your intellect he asks you to help him.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; public class OpticalExperiment { public static void update(int i, int val, int[] bit) { while (i < bit.length) { if (val > bit[i]) bit[i] = val; i += i & -i; } } public static int query(int i, int[] bit) { int max = bit[i]; while (i > 0) { if (bit[i] > max) max = bit[i]; i -= i & -i; } return max; } public static void main(String[] args) throws Exception { InputReader in = new InputReader(System.in); int n = in.nextInt(); int[] arr = new int[n + 1]; for (int i = 1; i <= n; i++) arr[i] = in.nextInt(); int[] pos = new int[n + 1]; for (int i = 0; i < n; i++) pos[in.nextInt()] = i + 1; int[] dp = new int[n + 1]; for (int i = 1; i <= n; i++) dp[i] = pos[arr[i]]; int[] lis = new int[n + 1]; int[] bit = new int[n + 1]; for (int i = n; i >= 1; i--) { lis[i] = 1 + query(dp[i] - 1, bit); update(dp[i], lis[i], bit); } int max = 0; for (int i = 1; i <= n; i++) max = (lis[i] > max) ? lis[i] : max; System.out.println(max); } static class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["5\n1 4 5 2 3\n3 4 2 1 5", "3\n3 1 2\n2 3 1"]
5 seconds
["3", "2"]
NoteFor the first test case, the figure is shown above. The output of the first test case is 3, since the rays number 1, 4 and 3 are the ones which are intersected by each other one i.e. 1 is intersected by 4 and 3, 3 is intersected by 4 and 1, and 4 is intersected by 1 and 3. Hence every ray in this group is intersected by each other one. There does not exist any group containing more than 3 rays satisfying the above-mentioned constraint.
Java 6
standard input
[ "dp", "binary search", "data structures" ]
b0ef9cda01a01cad22e7f4c49e74e85c
The first line contains n (1 ≤ n ≤ 106), the number of rays. The second line contains n distinct integers. The i-th integer xi (1 ≤ xi ≤ n) shows that the xi-th ray enters from the i-th hole. Similarly, third line contains n distinct integers. The i-th integer yi (1 ≤ yi ≤ n) shows that the yi-th ray exits from the i-th hole. All rays are numbered from 1 to n.
1,900
Output contains the only integer which is the number of rays in the largest group of rays all of which intersect each other.
standard output
PASSED
1aff99e62dcd48bdc7eb213de4ddbc82
train_002.jsonl
1300033800
Professor Phunsuk Wangdu has performed some experiments on rays. The setup for n rays is as follows.There is a rectangular box having exactly n holes on the opposite faces. All rays enter from the holes of the first side and exit from the holes of the other side of the box. Exactly one ray can enter or exit from each hole. The holes are in a straight line. Professor Wangdu is showing his experiment to his students. He shows that there are cases, when all the rays are intersected by every other ray. A curious student asked the professor: "Sir, there are some groups of rays such that all rays in that group intersect every other ray in that group. Can we determine the number of rays in the largest of such groups?".Professor Wangdu now is in trouble and knowing your intellect he asks you to help him.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Scanner; public class D { public static int LIS(int[] x) { int n = x.length; int[] L = new int[n + 1]; Arrays.fill(L, Integer.MAX_VALUE); int max = 1; L[1] = x[0]; for (int i = 1; i < n; i++) { int lo = 1; int hi = max + 1; for (int j = 0; j < 21; j++) { int mid = (lo + hi) / 2; if (L[mid] >= x[i]) hi = mid; else lo = mid; } if (L[lo] < x[i]) { L[lo + 1] = Math.min(L[lo + 1], x[i]); max = Math.max(max, lo + 1); } else { L[1] = Math.min(L[1], x[i]); } } return max; } public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(in.readLine()); int[] A = new int[n]; String[] S = in.readLine().split(" "); for (int i = 0; i < n; i++) A[Integer.parseInt(S[i]) - 1] = i + 1; int[] B = new int[n]; S = in.readLine().split(" "); for (int i = n - 1; i >= 0; i--) B[i] = A[Integer.parseInt(S[n - i - 1]) - 1]; System.out.println(LIS(B)); } }
Java
["5\n1 4 5 2 3\n3 4 2 1 5", "3\n3 1 2\n2 3 1"]
5 seconds
["3", "2"]
NoteFor the first test case, the figure is shown above. The output of the first test case is 3, since the rays number 1, 4 and 3 are the ones which are intersected by each other one i.e. 1 is intersected by 4 and 3, 3 is intersected by 4 and 1, and 4 is intersected by 1 and 3. Hence every ray in this group is intersected by each other one. There does not exist any group containing more than 3 rays satisfying the above-mentioned constraint.
Java 6
standard input
[ "dp", "binary search", "data structures" ]
b0ef9cda01a01cad22e7f4c49e74e85c
The first line contains n (1 ≤ n ≤ 106), the number of rays. The second line contains n distinct integers. The i-th integer xi (1 ≤ xi ≤ n) shows that the xi-th ray enters from the i-th hole. Similarly, third line contains n distinct integers. The i-th integer yi (1 ≤ yi ≤ n) shows that the yi-th ray exits from the i-th hole. All rays are numbered from 1 to n.
1,900
Output contains the only integer which is the number of rays in the largest group of rays all of which intersect each other.
standard output
PASSED
d8e425e5905ad8439d65d64f91c1fffb
train_002.jsonl
1300033800
Professor Phunsuk Wangdu has performed some experiments on rays. The setup for n rays is as follows.There is a rectangular box having exactly n holes on the opposite faces. All rays enter from the holes of the first side and exit from the holes of the other side of the box. Exactly one ray can enter or exit from each hole. The holes are in a straight line. Professor Wangdu is showing his experiment to his students. He shows that there are cases, when all the rays are intersected by every other ray. A curious student asked the professor: "Sir, there are some groups of rays such that all rays in that group intersect every other ray in that group. Can we determine the number of rays in the largest of such groups?".Professor Wangdu now is in trouble and knowing your intellect he asks you to help him.
256 megabytes
import java.io.*; import java.util.*; public class D { int n; int[] x, y; int[] a; private void solve() throws IOException { n = nextInt(); x = new int[n]; y = new int[n]; for (int i = 0; i < n; i++) { x[i] = nextInt() - 1; } int[] start = new int[n]; for (int i = 0; i < n; i++) { start[x[i]] = i; } a = new int[n]; for (int i = 0; i < n; i++) { y[i] = nextInt() - 1; a[start[y[i]]] = i; } int res = get(); out.println(res); } final int INF = Integer.MAX_VALUE; int get() { int[] d = new int[n + 1]; Arrays.fill(d, -INF); d[0] = INF; for (int i = 0; i < n; i++) { int l = -1, r = i + 1; while (r - l > 1) { int m = (r + l) / 2; if (d[m] > a[i]) { l = m; } else { r = m; } } if (l == -1) continue; if (d[r] < a[i]) { d[r] = a[i]; } } for (int i = n; i >= 0; i--) { if (d[i] != -INF) return i; } return -1; } public static void main(String[] args) { new D().run(); } BufferedReader br; StringTokenizer st; PrintWriter out; boolean eof = false; public void run() { try { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); st = new StringTokenizer(""); solve(); out.close(); } catch (Throwable e) { e.printStackTrace(); System.exit(239); } } String nextToken() throws IOException { while (!st.hasMoreTokens()) { String line = br.readLine(); if (line == null) { eof = true; line = "0"; } st = new StringTokenizer(line); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
Java
["5\n1 4 5 2 3\n3 4 2 1 5", "3\n3 1 2\n2 3 1"]
5 seconds
["3", "2"]
NoteFor the first test case, the figure is shown above. The output of the first test case is 3, since the rays number 1, 4 and 3 are the ones which are intersected by each other one i.e. 1 is intersected by 4 and 3, 3 is intersected by 4 and 1, and 4 is intersected by 1 and 3. Hence every ray in this group is intersected by each other one. There does not exist any group containing more than 3 rays satisfying the above-mentioned constraint.
Java 6
standard input
[ "dp", "binary search", "data structures" ]
b0ef9cda01a01cad22e7f4c49e74e85c
The first line contains n (1 ≤ n ≤ 106), the number of rays. The second line contains n distinct integers. The i-th integer xi (1 ≤ xi ≤ n) shows that the xi-th ray enters from the i-th hole. Similarly, third line contains n distinct integers. The i-th integer yi (1 ≤ yi ≤ n) shows that the yi-th ray exits from the i-th hole. All rays are numbered from 1 to n.
1,900
Output contains the only integer which is the number of rays in the largest group of rays all of which intersect each other.
standard output
PASSED
58beb60d6ec81e97023b72e49dec30ff
train_002.jsonl
1300033800
Professor Phunsuk Wangdu has performed some experiments on rays. The setup for n rays is as follows.There is a rectangular box having exactly n holes on the opposite faces. All rays enter from the holes of the first side and exit from the holes of the other side of the box. Exactly one ray can enter or exit from each hole. The holes are in a straight line. Professor Wangdu is showing his experiment to his students. He shows that there are cases, when all the rays are intersected by every other ray. A curious student asked the professor: "Sir, there are some groups of rays such that all rays in that group intersect every other ray in that group. Can we determine the number of rays in the largest of such groups?".Professor Wangdu now is in trouble and knowing your intellect he asks you to help him.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.awt.*; public class D { MyScanner in; PrintWriter out; public static void main(String[] args) throws Exception { new D().run(); } public void run() throws Exception { in = new MyScanner(); out = new PrintWriter(System.out); solve(); out.close(); } public void solve() throws Exception { int n = in.nextInt(); int[] x = new int[n]; int[] y = new int[n]; int[] z = new int[n]; for (int i = 0; i < n; i++) { x[in.nextInt() - 1] = i; } for (int i = 0; i < n; i++) { y[x[in.nextInt() - 1]] = i; } int[] a = new int[n + 1]; int ans = 0; for (int i = 0; i < n; i++) { int l = 0; int r = ans; while (l < r) { int m = (l + r + 1) / 2; if (a[m] > y[i]) { l = m; } else { r = m - 1; } } a[l + 1] = y[i]; ans = Math.max(ans, l + 1); } out.println(ans); } class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() throws Exception { br = new BufferedReader(new InputStreamReader(System.in)); } String next() throws Exception { if ((st == null) || (!st.hasMoreTokens())) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } int nextInt() throws Exception { return Integer.parseInt(next()); } double nextDouble() throws Exception { return Double.parseDouble(next()); } boolean nextBoolean() throws Exception { return Boolean.parseBoolean(next()); } long nextLong() throws Exception { return Long.parseLong(next()); } } }
Java
["5\n1 4 5 2 3\n3 4 2 1 5", "3\n3 1 2\n2 3 1"]
5 seconds
["3", "2"]
NoteFor the first test case, the figure is shown above. The output of the first test case is 3, since the rays number 1, 4 and 3 are the ones which are intersected by each other one i.e. 1 is intersected by 4 and 3, 3 is intersected by 4 and 1, and 4 is intersected by 1 and 3. Hence every ray in this group is intersected by each other one. There does not exist any group containing more than 3 rays satisfying the above-mentioned constraint.
Java 6
standard input
[ "dp", "binary search", "data structures" ]
b0ef9cda01a01cad22e7f4c49e74e85c
The first line contains n (1 ≤ n ≤ 106), the number of rays. The second line contains n distinct integers. The i-th integer xi (1 ≤ xi ≤ n) shows that the xi-th ray enters from the i-th hole. Similarly, third line contains n distinct integers. The i-th integer yi (1 ≤ yi ≤ n) shows that the yi-th ray exits from the i-th hole. All rays are numbered from 1 to n.
1,900
Output contains the only integer which is the number of rays in the largest group of rays all of which intersect each other.
standard output
PASSED
2027eb69a417ba006c8908b6b9d9de31
train_002.jsonl
1300033800
Professor Phunsuk Wangdu has performed some experiments on rays. The setup for n rays is as follows.There is a rectangular box having exactly n holes on the opposite faces. All rays enter from the holes of the first side and exit from the holes of the other side of the box. Exactly one ray can enter or exit from each hole. The holes are in a straight line. Professor Wangdu is showing his experiment to his students. He shows that there are cases, when all the rays are intersected by every other ray. A curious student asked the professor: "Sir, there are some groups of rays such that all rays in that group intersect every other ray in that group. Can we determine the number of rays in the largest of such groups?".Professor Wangdu now is in trouble and knowing your intellect he asks you to help him.
256 megabytes
import java.io.*; import java.util.Arrays; import java.util.Locale; import java.util.StringTokenizer; public class D implements Runnable { BufferedReader in; StringTokenizer st = new StringTokenizer(""); PrintWriter out; public void solve() throws IOException { int n = nextInt(); int[] x = new int[n]; int[] px = new int[n]; int[] y = new int[n]; int[] py = new int[n]; for (int i = 0; i < n; i++) { x[i] = nextInt() - 1; px[x[i]] = i; } for (int i = 0; i < n; i++) { y[i] = nextInt() - 1; py[y[i]] = i; } int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = py[x[i]]; } // System.out.println(Arrays.toString(a)); int maxL = 1; int[] d = new int[n+1]; Arrays.fill(d, -1); d[1] = 0; for (int i = 1; i < n; i++) { int l = 0; int r = maxL; while (l < r) { int m = (l + r + 1) / 2; // if (m > n || d[m] == -1) { // r = m - 1; // } if (a[d[m]] > a[i]) { l = m; } else { r = m - 1; } } if (l == maxL || a[i] > a[d[l+1]]) { d[l + 1] = i; maxL = Math.max(maxL, l + 1); } } out.println(maxL); } public void run() { try { Locale.setDefault(Locale.US); in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); } catch (Exception ex) { ex.printStackTrace(); throw new RuntimeException(); } finally { out.close(); } } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } private double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } private String nextToken() throws IOException { while (!st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } public static void main(String[] args) { new Thread(new D()).start(); } }
Java
["5\n1 4 5 2 3\n3 4 2 1 5", "3\n3 1 2\n2 3 1"]
5 seconds
["3", "2"]
NoteFor the first test case, the figure is shown above. The output of the first test case is 3, since the rays number 1, 4 and 3 are the ones which are intersected by each other one i.e. 1 is intersected by 4 and 3, 3 is intersected by 4 and 1, and 4 is intersected by 1 and 3. Hence every ray in this group is intersected by each other one. There does not exist any group containing more than 3 rays satisfying the above-mentioned constraint.
Java 6
standard input
[ "dp", "binary search", "data structures" ]
b0ef9cda01a01cad22e7f4c49e74e85c
The first line contains n (1 ≤ n ≤ 106), the number of rays. The second line contains n distinct integers. The i-th integer xi (1 ≤ xi ≤ n) shows that the xi-th ray enters from the i-th hole. Similarly, third line contains n distinct integers. The i-th integer yi (1 ≤ yi ≤ n) shows that the yi-th ray exits from the i-th hole. All rays are numbered from 1 to n.
1,900
Output contains the only integer which is the number of rays in the largest group of rays all of which intersect each other.
standard output
PASSED
66b2ab2b929911d3a30bd7d05218be09
train_002.jsonl
1300033800
Professor Phunsuk Wangdu has performed some experiments on rays. The setup for n rays is as follows.There is a rectangular box having exactly n holes on the opposite faces. All rays enter from the holes of the first side and exit from the holes of the other side of the box. Exactly one ray can enter or exit from each hole. The holes are in a straight line. Professor Wangdu is showing his experiment to his students. He shows that there are cases, when all the rays are intersected by every other ray. A curious student asked the professor: "Sir, there are some groups of rays such that all rays in that group intersect every other ray in that group. Can we determine the number of rays in the largest of such groups?".Professor Wangdu now is in trouble and knowing your intellect he asks you to help him.
256 megabytes
import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Random; import java.io.Writer; import java.util.AbstractCollection; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.TreeMap; import java.util.ArrayList; import java.util.TreeSet; import java.util.StringTokenizer; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } } class TaskD { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int a[] = in.nextIntArray(n); int b[] = in.nextIntArray(n); int c[] = new int[n]; int i,j; int w[] = new int[n]; for(i=0;i<n;++i) w[a[i]-1] = i; for(i=0;i<n;++i) c[n-i-1] = w[b[i]-1]; out.writeln(ArrayUtils.longestIncreasingSubsequence_2(c)); } } class InputReader{ private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream){ reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next(){ while(tokenizer==null || !tokenizer.hasMoreTokens()){ try{ tokenizer = new StringTokenizer(reader.readLine()); }catch(Exception e){ throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt(){ return Integer.parseInt(next()); } public int[] nextIntArray(int size){ int array[] = new int[size]; for(int i=0; i<size; ++i) array[i] = nextInt(); return array; } } class OutputWriter{ private PrintWriter out; public OutputWriter(Writer out){ this.out = new PrintWriter(out); } public OutputWriter(OutputStream out){ this.out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(out))); } public void close(){ out.close(); } public void writeln(Object ... o){ for(Object x : o) out.print(x); out.println(); } } class ArrayUtils{ public static int longestIncreasingSubsequence_2(int a[]){ int i, n = a.length; int t[] = new int[n+1]; int d[] = new int[n]; for(i=0;i<=n;++i) t[i] = Integer.MAX_VALUE; int ans = 0; for(i=0;i<n;++i){ int j = Arrays.binarySearch(t, a[i]); if(j<0) j=-j-1; d[j] = (j>0?d[j-1]:0)+1; ans = Math.max(ans, d[j]); t[j] = a[i]; } return ans; } }
Java
["5\n1 4 5 2 3\n3 4 2 1 5", "3\n3 1 2\n2 3 1"]
5 seconds
["3", "2"]
NoteFor the first test case, the figure is shown above. The output of the first test case is 3, since the rays number 1, 4 and 3 are the ones which are intersected by each other one i.e. 1 is intersected by 4 and 3, 3 is intersected by 4 and 1, and 4 is intersected by 1 and 3. Hence every ray in this group is intersected by each other one. There does not exist any group containing more than 3 rays satisfying the above-mentioned constraint.
Java 6
standard input
[ "dp", "binary search", "data structures" ]
b0ef9cda01a01cad22e7f4c49e74e85c
The first line contains n (1 ≤ n ≤ 106), the number of rays. The second line contains n distinct integers. The i-th integer xi (1 ≤ xi ≤ n) shows that the xi-th ray enters from the i-th hole. Similarly, third line contains n distinct integers. The i-th integer yi (1 ≤ yi ≤ n) shows that the yi-th ray exits from the i-th hole. All rays are numbered from 1 to n.
1,900
Output contains the only integer which is the number of rays in the largest group of rays all of which intersect each other.
standard output
PASSED
b9b55d59d37b0b6f4b4336c69f2e919b
train_002.jsonl
1300033800
Professor Phunsuk Wangdu has performed some experiments on rays. The setup for n rays is as follows.There is a rectangular box having exactly n holes on the opposite faces. All rays enter from the holes of the first side and exit from the holes of the other side of the box. Exactly one ray can enter or exit from each hole. The holes are in a straight line. Professor Wangdu is showing his experiment to his students. He shows that there are cases, when all the rays are intersected by every other ray. A curious student asked the professor: "Sir, there are some groups of rays such that all rays in that group intersect every other ray in that group. Can we determine the number of rays in the largest of such groups?".Professor Wangdu now is in trouble and knowing your intellect he asks you to help him.
256 megabytes
import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.util.TreeMap; import java.util.InputMismatchException; import java.util.ArrayList; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Random; import java.util.TreeSet; import java.io.Writer; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } } class TaskD { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int a[] = in.nextIntArray(n); int b[] = in.nextIntArray(n); int c[] = new int[n]; int i,j; int w[] = new int[n]; for(i=0;i<n;++i) w[a[i]-1] = i; for(i=0;i<n;++i) c[n-i-1] = w[b[i]-1]; out.writeln(ArrayUtils.longestIncreasingSubsequence(c)); } } class InputReader{ InputStream in; byte buffer[] = new byte[1<<10]; int cur, end; public InputReader(InputStream stream){ in = stream; } public int read(){ if(end<0) throw new InputMismatchException(); if(cur>=end){ cur = 0; try{ end = in.read(buffer); }catch(IOException e){ throw new InputMismatchException(); } if(end<=0) return -1; } return buffer[cur++]; } public boolean isSpace(int c){ return c==' ' || c=='\n' || c=='\r' || c=='\t' || c==-1; } public int nextInt(){ int c = read(), res = 0, sign = 1; while(isSpace(c)) c = read(); if(c=='-'){ sign = -1; c = read(); } do{ if(c>'9' || c<'0') throw new InputMismatchException(); res = res*10 + (c-'0'); c = read(); }while(!isSpace(c)); return res*sign; } public int[] nextIntArray(int n){ int res[] = new int[n]; for(int i=0;i<n;++i) res[i] = nextInt(); return res; } } class OutputWriter{ private PrintWriter out; public OutputWriter(Writer out){ this.out = new PrintWriter(out); } public OutputWriter(OutputStream out){ this.out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(out))); } public void close(){ out.close(); } public void writeln(Object ... o){ for(Object x : o) out.print(x); out.println(); } } class ArrayUtils{ public static int longestIncreasingSubsequence(int a[]){ int i, n = a.length; int t[] = new int[n]; int d[] = new int[n]; for(i=0;i<n;++i) t[i] = Integer.MAX_VALUE; int ans = 0; for(i=0;i<n;++i){ int j = Arrays.binarySearch(t, a[i]); if(j<0) j=-j-1; t[j] = a[i]; d[j] = (j>0?d[j-1]:0)+1; ans = Math.max(ans, d[j]); } return ans; } }
Java
["5\n1 4 5 2 3\n3 4 2 1 5", "3\n3 1 2\n2 3 1"]
5 seconds
["3", "2"]
NoteFor the first test case, the figure is shown above. The output of the first test case is 3, since the rays number 1, 4 and 3 are the ones which are intersected by each other one i.e. 1 is intersected by 4 and 3, 3 is intersected by 4 and 1, and 4 is intersected by 1 and 3. Hence every ray in this group is intersected by each other one. There does not exist any group containing more than 3 rays satisfying the above-mentioned constraint.
Java 6
standard input
[ "dp", "binary search", "data structures" ]
b0ef9cda01a01cad22e7f4c49e74e85c
The first line contains n (1 ≤ n ≤ 106), the number of rays. The second line contains n distinct integers. The i-th integer xi (1 ≤ xi ≤ n) shows that the xi-th ray enters from the i-th hole. Similarly, third line contains n distinct integers. The i-th integer yi (1 ≤ yi ≤ n) shows that the yi-th ray exits from the i-th hole. All rays are numbered from 1 to n.
1,900
Output contains the only integer which is the number of rays in the largest group of rays all of which intersect each other.
standard output
PASSED
2be1d4f44d85abb61e0c3253e77b8350
train_002.jsonl
1300033800
Professor Phunsuk Wangdu has performed some experiments on rays. The setup for n rays is as follows.There is a rectangular box having exactly n holes on the opposite faces. All rays enter from the holes of the first side and exit from the holes of the other side of the box. Exactly one ray can enter or exit from each hole. The holes are in a straight line. Professor Wangdu is showing his experiment to his students. He shows that there are cases, when all the rays are intersected by every other ray. A curious student asked the professor: "Sir, there are some groups of rays such that all rays in that group intersect every other ray in that group. Can we determine the number of rays in the largest of such groups?".Professor Wangdu now is in trouble and knowing your intellect he asks you to help him.
256 megabytes
import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.util.TreeMap; import java.util.InputMismatchException; import java.util.ArrayList; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Random; import java.util.TreeSet; import java.io.Writer; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } } class TaskD { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int a[] = in.nextIntArray(n); int b[] = in.nextIntArray(n); int c[] = new int[n]; int i,j; int w[] = new int[n]; for(i=0;i<n;++i) w[a[i]-1] = i; for(i=0;i<n;++i) c[n-i-1] = w[b[i]-1]; out.writeln(ArrayUtils.longestIncreasingSubsequence(c)); } } class InputReader{ InputStream in; byte buffer[] = new byte[1<<11]; int cur, end; public InputReader(InputStream stream){ in = stream; } public int read(){ if(end<0) throw new InputMismatchException(); if(cur>=end){ cur = 0; try{ end = in.read(buffer); }catch(IOException e){ throw new InputMismatchException(); } if(end<=0) return -1; } return buffer[cur++]; } public boolean isSpace(int c){ return c==' ' || c=='\n' || c=='\r' || c=='\t' || c==-1; } public int nextInt(){ int c = read(), res = 0, sign = 1; while(isSpace(c)) c = read(); if(c=='-'){ sign = -1; c = read(); } do{ if(c>'9' || c<'0') throw new InputMismatchException(); res = res*10 + (c-'0'); c = read(); }while(!isSpace(c)); return res*sign; } public int[] nextIntArray(int n){ int res[] = new int[n]; for(int i=0;i<n;++i) res[i] = nextInt(); return res; } } class OutputWriter{ private PrintWriter out; public OutputWriter(Writer out){ this.out = new PrintWriter(out); } public OutputWriter(OutputStream out){ this.out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(out))); } public void close(){ out.close(); } public void writeln(Object ... o){ for(Object x : o) out.print(x); out.println(); } } class ArrayUtils{ public static int longestIncreasingSubsequence(int a[]){ int i, n = a.length; int t[] = new int[n]; int d[] = new int[n]; for(i=0;i<n;++i) t[i] = Integer.MAX_VALUE; int ans = 0; for(i=0;i<n;++i){ int j = Arrays.binarySearch(t, a[i]); if(j<0) j=-j-1; t[j] = a[i]; d[j] = (j>0?d[j-1]:0)+1; ans = Math.max(ans, d[j]); } return ans; } }
Java
["5\n1 4 5 2 3\n3 4 2 1 5", "3\n3 1 2\n2 3 1"]
5 seconds
["3", "2"]
NoteFor the first test case, the figure is shown above. The output of the first test case is 3, since the rays number 1, 4 and 3 are the ones which are intersected by each other one i.e. 1 is intersected by 4 and 3, 3 is intersected by 4 and 1, and 4 is intersected by 1 and 3. Hence every ray in this group is intersected by each other one. There does not exist any group containing more than 3 rays satisfying the above-mentioned constraint.
Java 6
standard input
[ "dp", "binary search", "data structures" ]
b0ef9cda01a01cad22e7f4c49e74e85c
The first line contains n (1 ≤ n ≤ 106), the number of rays. The second line contains n distinct integers. The i-th integer xi (1 ≤ xi ≤ n) shows that the xi-th ray enters from the i-th hole. Similarly, third line contains n distinct integers. The i-th integer yi (1 ≤ yi ≤ n) shows that the yi-th ray exits from the i-th hole. All rays are numbered from 1 to n.
1,900
Output contains the only integer which is the number of rays in the largest group of rays all of which intersect each other.
standard output
PASSED
3d5601065ac0f49b3fdf2dc08fcabc56
train_002.jsonl
1300033800
Professor Phunsuk Wangdu has performed some experiments on rays. The setup for n rays is as follows.There is a rectangular box having exactly n holes on the opposite faces. All rays enter from the holes of the first side and exit from the holes of the other side of the box. Exactly one ray can enter or exit from each hole. The holes are in a straight line. Professor Wangdu is showing his experiment to his students. He shows that there are cases, when all the rays are intersected by every other ray. A curious student asked the professor: "Sir, there are some groups of rays such that all rays in that group intersect every other ray in that group. Can we determine the number of rays in the largest of such groups?".Professor Wangdu now is in trouble and knowing your intellect he asks you to help him.
256 megabytes
import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.util.ArrayList; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Random; import java.io.Writer; 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; InputReaderFast in = new InputReaderFast(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } } class TaskD { public void solve(int testNumber, InputReaderFast in, OutputWriter out) { int i,n = in.nextInt(); int a[] = in.nextIntArray(n); int b[] = in.nextIntArray(n); int w[] = new int[n+1]; for(i=0;i<n;++i) w[a[i]] = i; for(i=0;i<n;++i) a[n-i-1] = w[b[i]]; out.writeln(ArrayUtils.longestIncreasingSubsequence(a)); } } class InputReaderFast { private InputStream reader; public InputReaderFast(InputStream stream){ reader = stream; } public int read(){ try { return reader.read(); } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } return -1; } public int nextInt(){ int sign = 1, x = 0, c; do{ c=read(); }while (c<=32); if(c=='-'){ c=read(); sign=-1; } while (c>='0' && c<='9'){ x = x*10 + c-'0'; c = read(); } return x*sign; } public int[] nextIntArray(int n){ int res[] = new int[n]; for(int i=0;i<n;++i) res[i] = nextInt(); return res; } } class OutputWriter{ private PrintWriter out; public OutputWriter(Writer out){ this.out = new PrintWriter(out); } public OutputWriter(OutputStream out){ this.out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(out))); } public void write(Object ... o){ for(Object x : o) out.print(x); } public void writeln(Object ... o){ write(o); out.println(); } public void close(){ out.close(); } } class ArrayUtils{ public static int longestIncreasingSubsequence(int a[]){ int i, n = a.length; int t[] = new int[n]; int d[] = new int[n]; for(i=0;i<n;++i) t[i] = Integer.MAX_VALUE; int ans = 0; for(i=0;i<n;++i){ int j = Arrays.binarySearch(t, a[i]); if(j<0) j=-j-1; t[j] = a[i]; d[j] = (j>0?d[j-1]:0)+1; ans = Math.max(ans, d[j]); } return ans; } }
Java
["5\n1 4 5 2 3\n3 4 2 1 5", "3\n3 1 2\n2 3 1"]
5 seconds
["3", "2"]
NoteFor the first test case, the figure is shown above. The output of the first test case is 3, since the rays number 1, 4 and 3 are the ones which are intersected by each other one i.e. 1 is intersected by 4 and 3, 3 is intersected by 4 and 1, and 4 is intersected by 1 and 3. Hence every ray in this group is intersected by each other one. There does not exist any group containing more than 3 rays satisfying the above-mentioned constraint.
Java 6
standard input
[ "dp", "binary search", "data structures" ]
b0ef9cda01a01cad22e7f4c49e74e85c
The first line contains n (1 ≤ n ≤ 106), the number of rays. The second line contains n distinct integers. The i-th integer xi (1 ≤ xi ≤ n) shows that the xi-th ray enters from the i-th hole. Similarly, third line contains n distinct integers. The i-th integer yi (1 ≤ yi ≤ n) shows that the yi-th ray exits from the i-th hole. All rays are numbered from 1 to n.
1,900
Output contains the only integer which is the number of rays in the largest group of rays all of which intersect each other.
standard output