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
8dc17cfedd61713c2ad3574be7471061
train_001.jsonl
1590503700
Maria is the most active old lady in her house. She was tired of sitting at home. She decided to organize a ceremony against the coronavirus.She has $$$n$$$ friends who are also grannies (Maria is not included in this number). The $$$i$$$-th granny is ready to attend the ceremony, provided that at the time of her appearance in the courtyard there will be at least $$$a_i$$$ other grannies there. Note that grannies can come into the courtyard at the same time. Formally, the granny $$$i$$$ agrees to come if the number of other grannies who came earlier or at the same time with her is greater than or equal to $$$a_i$$$.Grannies gather in the courtyard like that. Initially, only Maria is in the courtyard (that is, the initial number of grannies in the courtyard is $$$1$$$). All the remaining $$$n$$$ grannies are still sitting at home. On each step Maria selects a subset of grannies, none of whom have yet to enter the courtyard. She promises each of them that at the time of her appearance there will be at least $$$a_i$$$ other grannies (including Maria) in the courtyard. Maria can call several grannies at once. In this case, the selected grannies will go out into the courtyard at the same moment of time. She cannot deceive grannies, that is, the situation when the $$$i$$$-th granny in the moment of appearing in the courtyard, finds that now there are strictly less than $$$a_i$$$ other grannies (except herself, but including Maria), is prohibited. Please note that if several grannies appeared in the yard at the same time, then each of them sees others at the time of appearance. Your task is to find what maximum number of grannies (including herself) Maria can collect in the courtyard for the ceremony. After all, the more people in one place during quarantine, the more effective the ceremony!Consider an example: if $$$n=6$$$ and $$$a=[1,5,4,5,1,9]$$$, then: at the first step Maria can call grannies with numbers $$$1$$$ and $$$5$$$, each of them will see two grannies at the moment of going out into the yard (note that $$$a_1=1 \le 2$$$ and $$$a_5=1 \le 2$$$); at the second step, Maria can call grannies with numbers $$$2$$$, $$$3$$$ and $$$4$$$, each of them will see five grannies at the moment of going out into the yard (note that $$$a_2=5 \le 5$$$, $$$a_3=4 \le 5$$$ and $$$a_4=5 \le 5$$$); the $$$6$$$-th granny cannot be called into the yard  — therefore, the answer is $$$6$$$ (Maria herself and another $$$5$$$ grannies).
256 megabytes
import java.util.*; public class file{ public static void main(String[] ags){ Scanner scan=new Scanner(System.in); int test=scan.nextInt(); for(int i=0;i<test;i++){ int a=scan.nextInt(); int[] arr=new int[a]; for(int j=0;j<a;j++){ arr[j]=scan.nextInt(); } Arrays.sort(arr); boolean flag=true; for(int j=a-1;j>=0;j--){ if(arr[j] <= j+1){ System.out.println(j+2); flag=false; break; } } if(flag) { System.out.println("1"); } } } }
Java
["4\n5\n1 1 2 2 1\n6\n2 3 4 5 6 7\n6\n1 5 4 5 1 9\n5\n1 2 3 5 6"]
2 seconds
["6\n1\n6\n4"]
NoteIn the first test case in the example, on the first step Maria can call all the grannies. Then each of them will see five grannies when they come out. Therefore, Maria and five other grannies will be in the yard.In the second test case in the example, no one can be in the yard, so Maria will remain there alone.The third test case in the example is described in the details above.In the fourth test case in the example, on the first step Maria can call grannies with numbers $$$1$$$, $$$2$$$ and $$$3$$$. If on the second step Maria calls $$$4$$$ or $$$5$$$ (one of them), then when a granny appears in the yard, she will see only four grannies (but it is forbidden). It means that Maria can't call the $$$4$$$-th granny or the $$$5$$$-th granny separately (one of them). If she calls both: $$$4$$$ and $$$5$$$, then when they appear, they will see $$$4+1=5$$$ grannies. Despite the fact that it is enough for the $$$4$$$-th granny, the $$$5$$$-th granny is not satisfied. So, Maria cannot call both the $$$4$$$-th granny and the $$$5$$$-th granny at the same time. That is, Maria and three grannies from the first step will be in the yard in total.
Java 8
standard input
[ "sortings", "greedy" ]
718cea81f609055cece58cae5310f703
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then test cases follow. The first line of a test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of grannies (Maria is not included in this number). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 2\cdot10^5$$$). It is guaranteed that the sum of the values $$$n$$$ over all test cases of the input does not exceed $$$10^5$$$.
1,000
For each test case, print a single integer $$$k$$$ ($$$1 \le k \le n + 1$$$) — the maximum possible number of grannies in the courtyard.
standard output
PASSED
dcfdccc61f1cb4edc00f3dc7928ea6f0
train_001.jsonl
1590503700
Maria is the most active old lady in her house. She was tired of sitting at home. She decided to organize a ceremony against the coronavirus.She has $$$n$$$ friends who are also grannies (Maria is not included in this number). The $$$i$$$-th granny is ready to attend the ceremony, provided that at the time of her appearance in the courtyard there will be at least $$$a_i$$$ other grannies there. Note that grannies can come into the courtyard at the same time. Formally, the granny $$$i$$$ agrees to come if the number of other grannies who came earlier or at the same time with her is greater than or equal to $$$a_i$$$.Grannies gather in the courtyard like that. Initially, only Maria is in the courtyard (that is, the initial number of grannies in the courtyard is $$$1$$$). All the remaining $$$n$$$ grannies are still sitting at home. On each step Maria selects a subset of grannies, none of whom have yet to enter the courtyard. She promises each of them that at the time of her appearance there will be at least $$$a_i$$$ other grannies (including Maria) in the courtyard. Maria can call several grannies at once. In this case, the selected grannies will go out into the courtyard at the same moment of time. She cannot deceive grannies, that is, the situation when the $$$i$$$-th granny in the moment of appearing in the courtyard, finds that now there are strictly less than $$$a_i$$$ other grannies (except herself, but including Maria), is prohibited. Please note that if several grannies appeared in the yard at the same time, then each of them sees others at the time of appearance. Your task is to find what maximum number of grannies (including herself) Maria can collect in the courtyard for the ceremony. After all, the more people in one place during quarantine, the more effective the ceremony!Consider an example: if $$$n=6$$$ and $$$a=[1,5,4,5,1,9]$$$, then: at the first step Maria can call grannies with numbers $$$1$$$ and $$$5$$$, each of them will see two grannies at the moment of going out into the yard (note that $$$a_1=1 \le 2$$$ and $$$a_5=1 \le 2$$$); at the second step, Maria can call grannies with numbers $$$2$$$, $$$3$$$ and $$$4$$$, each of them will see five grannies at the moment of going out into the yard (note that $$$a_2=5 \le 5$$$, $$$a_3=4 \le 5$$$ and $$$a_4=5 \le 5$$$); the $$$6$$$-th granny cannot be called into the yard  — therefore, the answer is $$$6$$$ (Maria herself and another $$$5$$$ grannies).
256 megabytes
import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Solution{ public static void main(String...args) throws Exception { OutputStream outputStream =System.out; PrintWriter out =new PrintWriter(outputStream); Reader s=new Reader(); int T = s.nextInt(); while(T-->0) { int N=s.nextInt(); int A[]=new int[N+1]; for(int i=1;i<=N;i++) { A[i]=s.nextInt(); } Arrays.sort(A); int ans=1; for(int i=N;i>=1;i--) { if(i>=A[i]) { ans=i+1; break; } } out.println(ans); } out.close(); } } 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(); } }
Java
["4\n5\n1 1 2 2 1\n6\n2 3 4 5 6 7\n6\n1 5 4 5 1 9\n5\n1 2 3 5 6"]
2 seconds
["6\n1\n6\n4"]
NoteIn the first test case in the example, on the first step Maria can call all the grannies. Then each of them will see five grannies when they come out. Therefore, Maria and five other grannies will be in the yard.In the second test case in the example, no one can be in the yard, so Maria will remain there alone.The third test case in the example is described in the details above.In the fourth test case in the example, on the first step Maria can call grannies with numbers $$$1$$$, $$$2$$$ and $$$3$$$. If on the second step Maria calls $$$4$$$ or $$$5$$$ (one of them), then when a granny appears in the yard, she will see only four grannies (but it is forbidden). It means that Maria can't call the $$$4$$$-th granny or the $$$5$$$-th granny separately (one of them). If she calls both: $$$4$$$ and $$$5$$$, then when they appear, they will see $$$4+1=5$$$ grannies. Despite the fact that it is enough for the $$$4$$$-th granny, the $$$5$$$-th granny is not satisfied. So, Maria cannot call both the $$$4$$$-th granny and the $$$5$$$-th granny at the same time. That is, Maria and three grannies from the first step will be in the yard in total.
Java 8
standard input
[ "sortings", "greedy" ]
718cea81f609055cece58cae5310f703
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then test cases follow. The first line of a test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of grannies (Maria is not included in this number). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 2\cdot10^5$$$). It is guaranteed that the sum of the values $$$n$$$ over all test cases of the input does not exceed $$$10^5$$$.
1,000
For each test case, print a single integer $$$k$$$ ($$$1 \le k \le n + 1$$$) — the maximum possible number of grannies in the courtyard.
standard output
PASSED
5adda3cee7fcaf5d3396033999e0fbb4
train_001.jsonl
1590503700
Maria is the most active old lady in her house. She was tired of sitting at home. She decided to organize a ceremony against the coronavirus.She has $$$n$$$ friends who are also grannies (Maria is not included in this number). The $$$i$$$-th granny is ready to attend the ceremony, provided that at the time of her appearance in the courtyard there will be at least $$$a_i$$$ other grannies there. Note that grannies can come into the courtyard at the same time. Formally, the granny $$$i$$$ agrees to come if the number of other grannies who came earlier or at the same time with her is greater than or equal to $$$a_i$$$.Grannies gather in the courtyard like that. Initially, only Maria is in the courtyard (that is, the initial number of grannies in the courtyard is $$$1$$$). All the remaining $$$n$$$ grannies are still sitting at home. On each step Maria selects a subset of grannies, none of whom have yet to enter the courtyard. She promises each of them that at the time of her appearance there will be at least $$$a_i$$$ other grannies (including Maria) in the courtyard. Maria can call several grannies at once. In this case, the selected grannies will go out into the courtyard at the same moment of time. She cannot deceive grannies, that is, the situation when the $$$i$$$-th granny in the moment of appearing in the courtyard, finds that now there are strictly less than $$$a_i$$$ other grannies (except herself, but including Maria), is prohibited. Please note that if several grannies appeared in the yard at the same time, then each of them sees others at the time of appearance. Your task is to find what maximum number of grannies (including herself) Maria can collect in the courtyard for the ceremony. After all, the more people in one place during quarantine, the more effective the ceremony!Consider an example: if $$$n=6$$$ and $$$a=[1,5,4,5,1,9]$$$, then: at the first step Maria can call grannies with numbers $$$1$$$ and $$$5$$$, each of them will see two grannies at the moment of going out into the yard (note that $$$a_1=1 \le 2$$$ and $$$a_5=1 \le 2$$$); at the second step, Maria can call grannies with numbers $$$2$$$, $$$3$$$ and $$$4$$$, each of them will see five grannies at the moment of going out into the yard (note that $$$a_2=5 \le 5$$$, $$$a_3=4 \le 5$$$ and $$$a_4=5 \le 5$$$); the $$$6$$$-th granny cannot be called into the yard  — therefore, the answer is $$$6$$$ (Maria herself and another $$$5$$$ grannies).
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class B1358 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int cases = scanner.nextInt(); for(int i = 0; i < cases; i++) { int length = scanner.nextInt(); int[] arrange = new int[length]; for(int j = 0; j < length; j++) arrange[j] = scanner.nextInt(); Arrays.sort(arrange); int people = 1; for(int j = 0; j < length; j++) if(arrange[j] <= j + 1) people = j + 2; System.out.println(people); } } }
Java
["4\n5\n1 1 2 2 1\n6\n2 3 4 5 6 7\n6\n1 5 4 5 1 9\n5\n1 2 3 5 6"]
2 seconds
["6\n1\n6\n4"]
NoteIn the first test case in the example, on the first step Maria can call all the grannies. Then each of them will see five grannies when they come out. Therefore, Maria and five other grannies will be in the yard.In the second test case in the example, no one can be in the yard, so Maria will remain there alone.The third test case in the example is described in the details above.In the fourth test case in the example, on the first step Maria can call grannies with numbers $$$1$$$, $$$2$$$ and $$$3$$$. If on the second step Maria calls $$$4$$$ or $$$5$$$ (one of them), then when a granny appears in the yard, she will see only four grannies (but it is forbidden). It means that Maria can't call the $$$4$$$-th granny or the $$$5$$$-th granny separately (one of them). If she calls both: $$$4$$$ and $$$5$$$, then when they appear, they will see $$$4+1=5$$$ grannies. Despite the fact that it is enough for the $$$4$$$-th granny, the $$$5$$$-th granny is not satisfied. So, Maria cannot call both the $$$4$$$-th granny and the $$$5$$$-th granny at the same time. That is, Maria and three grannies from the first step will be in the yard in total.
Java 8
standard input
[ "sortings", "greedy" ]
718cea81f609055cece58cae5310f703
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then test cases follow. The first line of a test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of grannies (Maria is not included in this number). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 2\cdot10^5$$$). It is guaranteed that the sum of the values $$$n$$$ over all test cases of the input does not exceed $$$10^5$$$.
1,000
For each test case, print a single integer $$$k$$$ ($$$1 \le k \le n + 1$$$) — the maximum possible number of grannies in the courtyard.
standard output
PASSED
05ee1fb4dff6a0c53a24803e412a5dec
train_001.jsonl
1590503700
Maria is the most active old lady in her house. She was tired of sitting at home. She decided to organize a ceremony against the coronavirus.She has $$$n$$$ friends who are also grannies (Maria is not included in this number). The $$$i$$$-th granny is ready to attend the ceremony, provided that at the time of her appearance in the courtyard there will be at least $$$a_i$$$ other grannies there. Note that grannies can come into the courtyard at the same time. Formally, the granny $$$i$$$ agrees to come if the number of other grannies who came earlier or at the same time with her is greater than or equal to $$$a_i$$$.Grannies gather in the courtyard like that. Initially, only Maria is in the courtyard (that is, the initial number of grannies in the courtyard is $$$1$$$). All the remaining $$$n$$$ grannies are still sitting at home. On each step Maria selects a subset of grannies, none of whom have yet to enter the courtyard. She promises each of them that at the time of her appearance there will be at least $$$a_i$$$ other grannies (including Maria) in the courtyard. Maria can call several grannies at once. In this case, the selected grannies will go out into the courtyard at the same moment of time. She cannot deceive grannies, that is, the situation when the $$$i$$$-th granny in the moment of appearing in the courtyard, finds that now there are strictly less than $$$a_i$$$ other grannies (except herself, but including Maria), is prohibited. Please note that if several grannies appeared in the yard at the same time, then each of them sees others at the time of appearance. Your task is to find what maximum number of grannies (including herself) Maria can collect in the courtyard for the ceremony. After all, the more people in one place during quarantine, the more effective the ceremony!Consider an example: if $$$n=6$$$ and $$$a=[1,5,4,5,1,9]$$$, then: at the first step Maria can call grannies with numbers $$$1$$$ and $$$5$$$, each of them will see two grannies at the moment of going out into the yard (note that $$$a_1=1 \le 2$$$ and $$$a_5=1 \le 2$$$); at the second step, Maria can call grannies with numbers $$$2$$$, $$$3$$$ and $$$4$$$, each of them will see five grannies at the moment of going out into the yard (note that $$$a_2=5 \le 5$$$, $$$a_3=4 \le 5$$$ and $$$a_4=5 \le 5$$$); the $$$6$$$-th granny cannot be called into the yard  — therefore, the answer is $$$6$$$ (Maria herself and another $$$5$$$ grannies).
256 megabytes
import javax.print.DocFlavor; import java.util.*; import java.lang.*; import java.util.*; import java.util.stream.*; import java.io.*; import java.util.stream.Collectors; /* Name of the class has to be "Main" only if the class is public. */ public class common { public static void main(String[] args) throws java.lang.Exception { FastReader sc = new FastReader(); BufferedWriter w=new BufferedWriter(new PrintWriter(System.out)); //System.out.println("enter the number of test cases"); int t =sc.nextInt(); for(int i=0;i<t;i++) { int n=sc.nextInt(); int a[]=new int [n]; for(int j=0;j<n;j++) { a[j]=sc.nextInt(); } Arrays.sort(a); //System.out.println("ARRAYS "+Arrays.toString(a)); int count =1; int end=1; int flag=1; for(int j=0;j<n;j++) { if(count>=a[j]) { count++; flag=0; if(j==n-1) { end=count; } } else { if(flag==0) { end=count; flag=1; } count++; } //System.out.println("i "+i+" COUNT: "+count+"a[j]: "+a[j]); } w.write(end+"\n"); } w.close(); } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); } String next() throws NumberFormatException,IOException,NullPointerException { while (st == null || !st.hasMoreElements()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } int nextInt()throws NumberFormatException,IOException,NullPointerException { return Integer.parseInt(next()); } long nextLong()throws NumberFormatException,IOException,NullPointerException { return Long.parseLong(next()); } double nextDouble()throws NumberFormatException,IOException,NullPointerException { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
Java
["4\n5\n1 1 2 2 1\n6\n2 3 4 5 6 7\n6\n1 5 4 5 1 9\n5\n1 2 3 5 6"]
2 seconds
["6\n1\n6\n4"]
NoteIn the first test case in the example, on the first step Maria can call all the grannies. Then each of them will see five grannies when they come out. Therefore, Maria and five other grannies will be in the yard.In the second test case in the example, no one can be in the yard, so Maria will remain there alone.The third test case in the example is described in the details above.In the fourth test case in the example, on the first step Maria can call grannies with numbers $$$1$$$, $$$2$$$ and $$$3$$$. If on the second step Maria calls $$$4$$$ or $$$5$$$ (one of them), then when a granny appears in the yard, she will see only four grannies (but it is forbidden). It means that Maria can't call the $$$4$$$-th granny or the $$$5$$$-th granny separately (one of them). If she calls both: $$$4$$$ and $$$5$$$, then when they appear, they will see $$$4+1=5$$$ grannies. Despite the fact that it is enough for the $$$4$$$-th granny, the $$$5$$$-th granny is not satisfied. So, Maria cannot call both the $$$4$$$-th granny and the $$$5$$$-th granny at the same time. That is, Maria and three grannies from the first step will be in the yard in total.
Java 8
standard input
[ "sortings", "greedy" ]
718cea81f609055cece58cae5310f703
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then test cases follow. The first line of a test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of grannies (Maria is not included in this number). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 2\cdot10^5$$$). It is guaranteed that the sum of the values $$$n$$$ over all test cases of the input does not exceed $$$10^5$$$.
1,000
For each test case, print a single integer $$$k$$$ ($$$1 \le k \le n + 1$$$) — the maximum possible number of grannies in the courtyard.
standard output
PASSED
5935cfcff9c55c584f1760bf3738efd3
train_001.jsonl
1590503700
Maria is the most active old lady in her house. She was tired of sitting at home. She decided to organize a ceremony against the coronavirus.She has $$$n$$$ friends who are also grannies (Maria is not included in this number). The $$$i$$$-th granny is ready to attend the ceremony, provided that at the time of her appearance in the courtyard there will be at least $$$a_i$$$ other grannies there. Note that grannies can come into the courtyard at the same time. Formally, the granny $$$i$$$ agrees to come if the number of other grannies who came earlier or at the same time with her is greater than or equal to $$$a_i$$$.Grannies gather in the courtyard like that. Initially, only Maria is in the courtyard (that is, the initial number of grannies in the courtyard is $$$1$$$). All the remaining $$$n$$$ grannies are still sitting at home. On each step Maria selects a subset of grannies, none of whom have yet to enter the courtyard. She promises each of them that at the time of her appearance there will be at least $$$a_i$$$ other grannies (including Maria) in the courtyard. Maria can call several grannies at once. In this case, the selected grannies will go out into the courtyard at the same moment of time. She cannot deceive grannies, that is, the situation when the $$$i$$$-th granny in the moment of appearing in the courtyard, finds that now there are strictly less than $$$a_i$$$ other grannies (except herself, but including Maria), is prohibited. Please note that if several grannies appeared in the yard at the same time, then each of them sees others at the time of appearance. Your task is to find what maximum number of grannies (including herself) Maria can collect in the courtyard for the ceremony. After all, the more people in one place during quarantine, the more effective the ceremony!Consider an example: if $$$n=6$$$ and $$$a=[1,5,4,5,1,9]$$$, then: at the first step Maria can call grannies with numbers $$$1$$$ and $$$5$$$, each of them will see two grannies at the moment of going out into the yard (note that $$$a_1=1 \le 2$$$ and $$$a_5=1 \le 2$$$); at the second step, Maria can call grannies with numbers $$$2$$$, $$$3$$$ and $$$4$$$, each of them will see five grannies at the moment of going out into the yard (note that $$$a_2=5 \le 5$$$, $$$a_3=4 \le 5$$$ and $$$a_4=5 \le 5$$$); the $$$6$$$-th granny cannot be called into the yard  — therefore, the answer is $$$6$$$ (Maria herself and another $$$5$$$ grannies).
256 megabytes
import java.io.*; import java.util.*; public class Solution{ 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]; for(int i=0;i<n;i++) arr[i]=sc.nextInt(); Arrays.sort(arr); int grannie=1; for(int i=n-1;i>=0;i--) { if(arr[i]<=i+1){grannie+=i+1;break;} } System.out.println(grannie); } } }
Java
["4\n5\n1 1 2 2 1\n6\n2 3 4 5 6 7\n6\n1 5 4 5 1 9\n5\n1 2 3 5 6"]
2 seconds
["6\n1\n6\n4"]
NoteIn the first test case in the example, on the first step Maria can call all the grannies. Then each of them will see five grannies when they come out. Therefore, Maria and five other grannies will be in the yard.In the second test case in the example, no one can be in the yard, so Maria will remain there alone.The third test case in the example is described in the details above.In the fourth test case in the example, on the first step Maria can call grannies with numbers $$$1$$$, $$$2$$$ and $$$3$$$. If on the second step Maria calls $$$4$$$ or $$$5$$$ (one of them), then when a granny appears in the yard, she will see only four grannies (but it is forbidden). It means that Maria can't call the $$$4$$$-th granny or the $$$5$$$-th granny separately (one of them). If she calls both: $$$4$$$ and $$$5$$$, then when they appear, they will see $$$4+1=5$$$ grannies. Despite the fact that it is enough for the $$$4$$$-th granny, the $$$5$$$-th granny is not satisfied. So, Maria cannot call both the $$$4$$$-th granny and the $$$5$$$-th granny at the same time. That is, Maria and three grannies from the first step will be in the yard in total.
Java 8
standard input
[ "sortings", "greedy" ]
718cea81f609055cece58cae5310f703
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then test cases follow. The first line of a test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of grannies (Maria is not included in this number). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 2\cdot10^5$$$). It is guaranteed that the sum of the values $$$n$$$ over all test cases of the input does not exceed $$$10^5$$$.
1,000
For each test case, print a single integer $$$k$$$ ($$$1 \le k \le n + 1$$$) — the maximum possible number of grannies in the courtyard.
standard output
PASSED
a8b99592213191bfe3017a2a7181b748
train_001.jsonl
1590503700
Maria is the most active old lady in her house. She was tired of sitting at home. She decided to organize a ceremony against the coronavirus.She has $$$n$$$ friends who are also grannies (Maria is not included in this number). The $$$i$$$-th granny is ready to attend the ceremony, provided that at the time of her appearance in the courtyard there will be at least $$$a_i$$$ other grannies there. Note that grannies can come into the courtyard at the same time. Formally, the granny $$$i$$$ agrees to come if the number of other grannies who came earlier or at the same time with her is greater than or equal to $$$a_i$$$.Grannies gather in the courtyard like that. Initially, only Maria is in the courtyard (that is, the initial number of grannies in the courtyard is $$$1$$$). All the remaining $$$n$$$ grannies are still sitting at home. On each step Maria selects a subset of grannies, none of whom have yet to enter the courtyard. She promises each of them that at the time of her appearance there will be at least $$$a_i$$$ other grannies (including Maria) in the courtyard. Maria can call several grannies at once. In this case, the selected grannies will go out into the courtyard at the same moment of time. She cannot deceive grannies, that is, the situation when the $$$i$$$-th granny in the moment of appearing in the courtyard, finds that now there are strictly less than $$$a_i$$$ other grannies (except herself, but including Maria), is prohibited. Please note that if several grannies appeared in the yard at the same time, then each of them sees others at the time of appearance. Your task is to find what maximum number of grannies (including herself) Maria can collect in the courtyard for the ceremony. After all, the more people in one place during quarantine, the more effective the ceremony!Consider an example: if $$$n=6$$$ and $$$a=[1,5,4,5,1,9]$$$, then: at the first step Maria can call grannies with numbers $$$1$$$ and $$$5$$$, each of them will see two grannies at the moment of going out into the yard (note that $$$a_1=1 \le 2$$$ and $$$a_5=1 \le 2$$$); at the second step, Maria can call grannies with numbers $$$2$$$, $$$3$$$ and $$$4$$$, each of them will see five grannies at the moment of going out into the yard (note that $$$a_2=5 \le 5$$$, $$$a_3=4 \le 5$$$ and $$$a_4=5 \le 5$$$); the $$$6$$$-th granny cannot be called into the yard  — therefore, the answer is $$$6$$$ (Maria herself and another $$$5$$$ grannies).
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); final int T = in.nextInt(); for (int t = 0; t < T; t += 1) { final int n = in.nextInt(); final long[] a = new long[n]; for (int i = 0; i < n; i += 1) a[i] = in.nextLong(); Arrays.sort(a); long count = 1; long wave = 0; for (int i = 0; i < n; i += 1) { if (count + wave >= a[i]) { count += wave + 1; wave = 0; } else wave += 1; } System.out.println(count); } } }
Java
["4\n5\n1 1 2 2 1\n6\n2 3 4 5 6 7\n6\n1 5 4 5 1 9\n5\n1 2 3 5 6"]
2 seconds
["6\n1\n6\n4"]
NoteIn the first test case in the example, on the first step Maria can call all the grannies. Then each of them will see five grannies when they come out. Therefore, Maria and five other grannies will be in the yard.In the second test case in the example, no one can be in the yard, so Maria will remain there alone.The third test case in the example is described in the details above.In the fourth test case in the example, on the first step Maria can call grannies with numbers $$$1$$$, $$$2$$$ and $$$3$$$. If on the second step Maria calls $$$4$$$ or $$$5$$$ (one of them), then when a granny appears in the yard, she will see only four grannies (but it is forbidden). It means that Maria can't call the $$$4$$$-th granny or the $$$5$$$-th granny separately (one of them). If she calls both: $$$4$$$ and $$$5$$$, then when they appear, they will see $$$4+1=5$$$ grannies. Despite the fact that it is enough for the $$$4$$$-th granny, the $$$5$$$-th granny is not satisfied. So, Maria cannot call both the $$$4$$$-th granny and the $$$5$$$-th granny at the same time. That is, Maria and three grannies from the first step will be in the yard in total.
Java 8
standard input
[ "sortings", "greedy" ]
718cea81f609055cece58cae5310f703
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then test cases follow. The first line of a test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of grannies (Maria is not included in this number). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 2\cdot10^5$$$). It is guaranteed that the sum of the values $$$n$$$ over all test cases of the input does not exceed $$$10^5$$$.
1,000
For each test case, print a single integer $$$k$$$ ($$$1 \le k \le n + 1$$$) — the maximum possible number of grannies in the courtyard.
standard output
PASSED
325fd20f8af850da6fd2abd74763e8f4
train_001.jsonl
1590503700
Maria is the most active old lady in her house. She was tired of sitting at home. She decided to organize a ceremony against the coronavirus.She has $$$n$$$ friends who are also grannies (Maria is not included in this number). The $$$i$$$-th granny is ready to attend the ceremony, provided that at the time of her appearance in the courtyard there will be at least $$$a_i$$$ other grannies there. Note that grannies can come into the courtyard at the same time. Formally, the granny $$$i$$$ agrees to come if the number of other grannies who came earlier or at the same time with her is greater than or equal to $$$a_i$$$.Grannies gather in the courtyard like that. Initially, only Maria is in the courtyard (that is, the initial number of grannies in the courtyard is $$$1$$$). All the remaining $$$n$$$ grannies are still sitting at home. On each step Maria selects a subset of grannies, none of whom have yet to enter the courtyard. She promises each of them that at the time of her appearance there will be at least $$$a_i$$$ other grannies (including Maria) in the courtyard. Maria can call several grannies at once. In this case, the selected grannies will go out into the courtyard at the same moment of time. She cannot deceive grannies, that is, the situation when the $$$i$$$-th granny in the moment of appearing in the courtyard, finds that now there are strictly less than $$$a_i$$$ other grannies (except herself, but including Maria), is prohibited. Please note that if several grannies appeared in the yard at the same time, then each of them sees others at the time of appearance. Your task is to find what maximum number of grannies (including herself) Maria can collect in the courtyard for the ceremony. After all, the more people in one place during quarantine, the more effective the ceremony!Consider an example: if $$$n=6$$$ and $$$a=[1,5,4,5,1,9]$$$, then: at the first step Maria can call grannies with numbers $$$1$$$ and $$$5$$$, each of them will see two grannies at the moment of going out into the yard (note that $$$a_1=1 \le 2$$$ and $$$a_5=1 \le 2$$$); at the second step, Maria can call grannies with numbers $$$2$$$, $$$3$$$ and $$$4$$$, each of them will see five grannies at the moment of going out into the yard (note that $$$a_2=5 \le 5$$$, $$$a_3=4 \le 5$$$ and $$$a_4=5 \le 5$$$); the $$$6$$$-th granny cannot be called into the yard  — therefore, the answer is $$$6$$$ (Maria herself and another $$$5$$$ grannies).
256 megabytes
/*package whatever //do not write package name here */ import java.util.*; import java.lang.*; import java.io.*; public class GFG { public static long fun(long arr[],int n){ Arrays.sort(arr); long c=1,m=1; for(int i=0;i<n;i++){ if(arr[i]<=c){ c++; m=c; } else{ c++; } } return m; } public static void main (String[] args) throws Exception { Parserdoubt77771112225 sc = new Parserdoubt77771112225(System.in); // Scanner sc=new Scanner(System.in); int t = sc.nextInt(); while(t-->0){ int n =sc.nextInt(); long arr[]=new long[n]; for(int i=0;i<n;i++){ arr[i]=sc.nextLong(); } System.out.println(fun(arr,n)); } } } class Parserdoubt77771112225 { final private int BUFFER_SIZE = 1 << 17; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Parserdoubt77771112225(InputStream in) { din = new DataInputStream(in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String nextLine() throws Exception { StringBuffer sb=new StringBuffer(""); byte c = read(); while (c <= ' ') c = read(); do { sb.append((char)c); c=read(); }while(c>' '); return sb.toString(); } public char nextChar() throws Exception { byte c=read(); while(c<=' ') c= read(); return (char)c; } public int nextInt() throws Exception { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = c == '-'; if (neg) c = read(); do { ret = ret * 10 + c - '0'; c = read(); } while (c > ' '); if (neg) return -ret; return ret; } public long nextLong() throws Exception { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = c == '-'; if (neg) c = read(); do { ret = ret * 10 + c - '0'; c = read(); } while (c > ' '); if (neg) return -ret; return ret; } private void fillBuffer() throws Exception { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws Exception { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } }
Java
["4\n5\n1 1 2 2 1\n6\n2 3 4 5 6 7\n6\n1 5 4 5 1 9\n5\n1 2 3 5 6"]
2 seconds
["6\n1\n6\n4"]
NoteIn the first test case in the example, on the first step Maria can call all the grannies. Then each of them will see five grannies when they come out. Therefore, Maria and five other grannies will be in the yard.In the second test case in the example, no one can be in the yard, so Maria will remain there alone.The third test case in the example is described in the details above.In the fourth test case in the example, on the first step Maria can call grannies with numbers $$$1$$$, $$$2$$$ and $$$3$$$. If on the second step Maria calls $$$4$$$ or $$$5$$$ (one of them), then when a granny appears in the yard, she will see only four grannies (but it is forbidden). It means that Maria can't call the $$$4$$$-th granny or the $$$5$$$-th granny separately (one of them). If she calls both: $$$4$$$ and $$$5$$$, then when they appear, they will see $$$4+1=5$$$ grannies. Despite the fact that it is enough for the $$$4$$$-th granny, the $$$5$$$-th granny is not satisfied. So, Maria cannot call both the $$$4$$$-th granny and the $$$5$$$-th granny at the same time. That is, Maria and three grannies from the first step will be in the yard in total.
Java 8
standard input
[ "sortings", "greedy" ]
718cea81f609055cece58cae5310f703
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then test cases follow. The first line of a test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of grannies (Maria is not included in this number). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 2\cdot10^5$$$). It is guaranteed that the sum of the values $$$n$$$ over all test cases of the input does not exceed $$$10^5$$$.
1,000
For each test case, print a single integer $$$k$$$ ($$$1 \le k \le n + 1$$$) — the maximum possible number of grannies in the courtyard.
standard output
PASSED
7cbfd158134983691c6ffed0be816bc0
train_001.jsonl
1590503700
Maria is the most active old lady in her house. She was tired of sitting at home. She decided to organize a ceremony against the coronavirus.She has $$$n$$$ friends who are also grannies (Maria is not included in this number). The $$$i$$$-th granny is ready to attend the ceremony, provided that at the time of her appearance in the courtyard there will be at least $$$a_i$$$ other grannies there. Note that grannies can come into the courtyard at the same time. Formally, the granny $$$i$$$ agrees to come if the number of other grannies who came earlier or at the same time with her is greater than or equal to $$$a_i$$$.Grannies gather in the courtyard like that. Initially, only Maria is in the courtyard (that is, the initial number of grannies in the courtyard is $$$1$$$). All the remaining $$$n$$$ grannies are still sitting at home. On each step Maria selects a subset of grannies, none of whom have yet to enter the courtyard. She promises each of them that at the time of her appearance there will be at least $$$a_i$$$ other grannies (including Maria) in the courtyard. Maria can call several grannies at once. In this case, the selected grannies will go out into the courtyard at the same moment of time. She cannot deceive grannies, that is, the situation when the $$$i$$$-th granny in the moment of appearing in the courtyard, finds that now there are strictly less than $$$a_i$$$ other grannies (except herself, but including Maria), is prohibited. Please note that if several grannies appeared in the yard at the same time, then each of them sees others at the time of appearance. Your task is to find what maximum number of grannies (including herself) Maria can collect in the courtyard for the ceremony. After all, the more people in one place during quarantine, the more effective the ceremony!Consider an example: if $$$n=6$$$ and $$$a=[1,5,4,5,1,9]$$$, then: at the first step Maria can call grannies with numbers $$$1$$$ and $$$5$$$, each of them will see two grannies at the moment of going out into the yard (note that $$$a_1=1 \le 2$$$ and $$$a_5=1 \le 2$$$); at the second step, Maria can call grannies with numbers $$$2$$$, $$$3$$$ and $$$4$$$, each of them will see five grannies at the moment of going out into the yard (note that $$$a_2=5 \le 5$$$, $$$a_3=4 \le 5$$$ and $$$a_4=5 \le 5$$$); the $$$6$$$-th granny cannot be called into the yard  — therefore, the answer is $$$6$$$ (Maria herself and another $$$5$$$ grannies).
256 megabytes
import java.util.*; public class MariaBreakstheSelfIsolation { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t; t=sc.nextInt(); while(t-->0) { int n,i,count=1; n=sc.nextInt(); int a[]=new int[n]; for(i=0;i<n;i++) a[i]=sc.nextInt(); Arrays.parallelSort(a); for(i=n-1;i>=0;i--) { if(a[i]<=i+1) { count+=i+1; break; } } System.out.println(count); } } }
Java
["4\n5\n1 1 2 2 1\n6\n2 3 4 5 6 7\n6\n1 5 4 5 1 9\n5\n1 2 3 5 6"]
2 seconds
["6\n1\n6\n4"]
NoteIn the first test case in the example, on the first step Maria can call all the grannies. Then each of them will see five grannies when they come out. Therefore, Maria and five other grannies will be in the yard.In the second test case in the example, no one can be in the yard, so Maria will remain there alone.The third test case in the example is described in the details above.In the fourth test case in the example, on the first step Maria can call grannies with numbers $$$1$$$, $$$2$$$ and $$$3$$$. If on the second step Maria calls $$$4$$$ or $$$5$$$ (one of them), then when a granny appears in the yard, she will see only four grannies (but it is forbidden). It means that Maria can't call the $$$4$$$-th granny or the $$$5$$$-th granny separately (one of them). If she calls both: $$$4$$$ and $$$5$$$, then when they appear, they will see $$$4+1=5$$$ grannies. Despite the fact that it is enough for the $$$4$$$-th granny, the $$$5$$$-th granny is not satisfied. So, Maria cannot call both the $$$4$$$-th granny and the $$$5$$$-th granny at the same time. That is, Maria and three grannies from the first step will be in the yard in total.
Java 8
standard input
[ "sortings", "greedy" ]
718cea81f609055cece58cae5310f703
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then test cases follow. The first line of a test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of grannies (Maria is not included in this number). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 2\cdot10^5$$$). It is guaranteed that the sum of the values $$$n$$$ over all test cases of the input does not exceed $$$10^5$$$.
1,000
For each test case, print a single integer $$$k$$$ ($$$1 \le k \le n + 1$$$) — the maximum possible number of grannies in the courtyard.
standard output
PASSED
2409b7dfdfa36a1a22a269e47927d90a
train_001.jsonl
1590503700
Maria is the most active old lady in her house. She was tired of sitting at home. She decided to organize a ceremony against the coronavirus.She has $$$n$$$ friends who are also grannies (Maria is not included in this number). The $$$i$$$-th granny is ready to attend the ceremony, provided that at the time of her appearance in the courtyard there will be at least $$$a_i$$$ other grannies there. Note that grannies can come into the courtyard at the same time. Formally, the granny $$$i$$$ agrees to come if the number of other grannies who came earlier or at the same time with her is greater than or equal to $$$a_i$$$.Grannies gather in the courtyard like that. Initially, only Maria is in the courtyard (that is, the initial number of grannies in the courtyard is $$$1$$$). All the remaining $$$n$$$ grannies are still sitting at home. On each step Maria selects a subset of grannies, none of whom have yet to enter the courtyard. She promises each of them that at the time of her appearance there will be at least $$$a_i$$$ other grannies (including Maria) in the courtyard. Maria can call several grannies at once. In this case, the selected grannies will go out into the courtyard at the same moment of time. She cannot deceive grannies, that is, the situation when the $$$i$$$-th granny in the moment of appearing in the courtyard, finds that now there are strictly less than $$$a_i$$$ other grannies (except herself, but including Maria), is prohibited. Please note that if several grannies appeared in the yard at the same time, then each of them sees others at the time of appearance. Your task is to find what maximum number of grannies (including herself) Maria can collect in the courtyard for the ceremony. After all, the more people in one place during quarantine, the more effective the ceremony!Consider an example: if $$$n=6$$$ and $$$a=[1,5,4,5,1,9]$$$, then: at the first step Maria can call grannies with numbers $$$1$$$ and $$$5$$$, each of them will see two grannies at the moment of going out into the yard (note that $$$a_1=1 \le 2$$$ and $$$a_5=1 \le 2$$$); at the second step, Maria can call grannies with numbers $$$2$$$, $$$3$$$ and $$$4$$$, each of them will see five grannies at the moment of going out into the yard (note that $$$a_2=5 \le 5$$$, $$$a_3=4 \le 5$$$ and $$$a_4=5 \le 5$$$); the $$$6$$$-th granny cannot be called into the yard  — therefore, the answer is $$$6$$$ (Maria herself and another $$$5$$$ grannies).
256 megabytes
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Main { // public static void swap(int a[],int i,int j) public static void main (String[] args) throws java.lang.Exception { // your code goes here Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0){ int n=sc.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++){ a[i]=sc.nextInt(); } Arrays.sort(a); int ans=0; for(int i=0;i<n;i++){ if(a[i]<=i+1) ans=i+1; } //if(a[0]>1) //System.out.println("1"); //else System.out.println(ans+1); } } }
Java
["4\n5\n1 1 2 2 1\n6\n2 3 4 5 6 7\n6\n1 5 4 5 1 9\n5\n1 2 3 5 6"]
2 seconds
["6\n1\n6\n4"]
NoteIn the first test case in the example, on the first step Maria can call all the grannies. Then each of them will see five grannies when they come out. Therefore, Maria and five other grannies will be in the yard.In the second test case in the example, no one can be in the yard, so Maria will remain there alone.The third test case in the example is described in the details above.In the fourth test case in the example, on the first step Maria can call grannies with numbers $$$1$$$, $$$2$$$ and $$$3$$$. If on the second step Maria calls $$$4$$$ or $$$5$$$ (one of them), then when a granny appears in the yard, she will see only four grannies (but it is forbidden). It means that Maria can't call the $$$4$$$-th granny or the $$$5$$$-th granny separately (one of them). If she calls both: $$$4$$$ and $$$5$$$, then when they appear, they will see $$$4+1=5$$$ grannies. Despite the fact that it is enough for the $$$4$$$-th granny, the $$$5$$$-th granny is not satisfied. So, Maria cannot call both the $$$4$$$-th granny and the $$$5$$$-th granny at the same time. That is, Maria and three grannies from the first step will be in the yard in total.
Java 8
standard input
[ "sortings", "greedy" ]
718cea81f609055cece58cae5310f703
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then test cases follow. The first line of a test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of grannies (Maria is not included in this number). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 2\cdot10^5$$$). It is guaranteed that the sum of the values $$$n$$$ over all test cases of the input does not exceed $$$10^5$$$.
1,000
For each test case, print a single integer $$$k$$$ ($$$1 \le k \le n + 1$$$) — the maximum possible number of grannies in the courtyard.
standard output
PASSED
1efe517666a061005fd9643445a3b5c0
train_001.jsonl
1590503700
Maria is the most active old lady in her house. She was tired of sitting at home. She decided to organize a ceremony against the coronavirus.She has $$$n$$$ friends who are also grannies (Maria is not included in this number). The $$$i$$$-th granny is ready to attend the ceremony, provided that at the time of her appearance in the courtyard there will be at least $$$a_i$$$ other grannies there. Note that grannies can come into the courtyard at the same time. Formally, the granny $$$i$$$ agrees to come if the number of other grannies who came earlier or at the same time with her is greater than or equal to $$$a_i$$$.Grannies gather in the courtyard like that. Initially, only Maria is in the courtyard (that is, the initial number of grannies in the courtyard is $$$1$$$). All the remaining $$$n$$$ grannies are still sitting at home. On each step Maria selects a subset of grannies, none of whom have yet to enter the courtyard. She promises each of them that at the time of her appearance there will be at least $$$a_i$$$ other grannies (including Maria) in the courtyard. Maria can call several grannies at once. In this case, the selected grannies will go out into the courtyard at the same moment of time. She cannot deceive grannies, that is, the situation when the $$$i$$$-th granny in the moment of appearing in the courtyard, finds that now there are strictly less than $$$a_i$$$ other grannies (except herself, but including Maria), is prohibited. Please note that if several grannies appeared in the yard at the same time, then each of them sees others at the time of appearance. Your task is to find what maximum number of grannies (including herself) Maria can collect in the courtyard for the ceremony. After all, the more people in one place during quarantine, the more effective the ceremony!Consider an example: if $$$n=6$$$ and $$$a=[1,5,4,5,1,9]$$$, then: at the first step Maria can call grannies with numbers $$$1$$$ and $$$5$$$, each of them will see two grannies at the moment of going out into the yard (note that $$$a_1=1 \le 2$$$ and $$$a_5=1 \le 2$$$); at the second step, Maria can call grannies with numbers $$$2$$$, $$$3$$$ and $$$4$$$, each of them will see five grannies at the moment of going out into the yard (note that $$$a_2=5 \le 5$$$, $$$a_3=4 \le 5$$$ and $$$a_4=5 \le 5$$$); the $$$6$$$-th granny cannot be called into the yard  — therefore, the answer is $$$6$$$ (Maria herself and another $$$5$$$ grannies).
256 megabytes
// Working program with FastReader import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; import java.util.Arrays; public class Main { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { FastReader s=new FastReader(); int n = s.nextInt(); while (n-- > 0) { int r = s.nextInt(); int[] arr = new int[r]; for(int i = 0; i < r; i++){ int c = s.nextInt(); arr[i] = c; } Arrays.sort(arr); int currentAllowed = 1; int lastAllowedIndex = -1; for(int i = 0; i < r; i++){ if(arr[i] <= currentAllowed){ lastAllowedIndex = i; currentAllowed++; continue; } if(arr[i] <= (currentAllowed + i - (lastAllowedIndex + 1))){ currentAllowed += (i - lastAllowedIndex); lastAllowedIndex = i; } } System.out.println(currentAllowed); } } }
Java
["4\n5\n1 1 2 2 1\n6\n2 3 4 5 6 7\n6\n1 5 4 5 1 9\n5\n1 2 3 5 6"]
2 seconds
["6\n1\n6\n4"]
NoteIn the first test case in the example, on the first step Maria can call all the grannies. Then each of them will see five grannies when they come out. Therefore, Maria and five other grannies will be in the yard.In the second test case in the example, no one can be in the yard, so Maria will remain there alone.The third test case in the example is described in the details above.In the fourth test case in the example, on the first step Maria can call grannies with numbers $$$1$$$, $$$2$$$ and $$$3$$$. If on the second step Maria calls $$$4$$$ or $$$5$$$ (one of them), then when a granny appears in the yard, she will see only four grannies (but it is forbidden). It means that Maria can't call the $$$4$$$-th granny or the $$$5$$$-th granny separately (one of them). If she calls both: $$$4$$$ and $$$5$$$, then when they appear, they will see $$$4+1=5$$$ grannies. Despite the fact that it is enough for the $$$4$$$-th granny, the $$$5$$$-th granny is not satisfied. So, Maria cannot call both the $$$4$$$-th granny and the $$$5$$$-th granny at the same time. That is, Maria and three grannies from the first step will be in the yard in total.
Java 8
standard input
[ "sortings", "greedy" ]
718cea81f609055cece58cae5310f703
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then test cases follow. The first line of a test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of grannies (Maria is not included in this number). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 2\cdot10^5$$$). It is guaranteed that the sum of the values $$$n$$$ over all test cases of the input does not exceed $$$10^5$$$.
1,000
For each test case, print a single integer $$$k$$$ ($$$1 \le k \le n + 1$$$) — the maximum possible number of grannies in the courtyard.
standard output
PASSED
315cc82e38c1add46337ec66d37141b8
train_001.jsonl
1590503700
Maria is the most active old lady in her house. She was tired of sitting at home. She decided to organize a ceremony against the coronavirus.She has $$$n$$$ friends who are also grannies (Maria is not included in this number). The $$$i$$$-th granny is ready to attend the ceremony, provided that at the time of her appearance in the courtyard there will be at least $$$a_i$$$ other grannies there. Note that grannies can come into the courtyard at the same time. Formally, the granny $$$i$$$ agrees to come if the number of other grannies who came earlier or at the same time with her is greater than or equal to $$$a_i$$$.Grannies gather in the courtyard like that. Initially, only Maria is in the courtyard (that is, the initial number of grannies in the courtyard is $$$1$$$). All the remaining $$$n$$$ grannies are still sitting at home. On each step Maria selects a subset of grannies, none of whom have yet to enter the courtyard. She promises each of them that at the time of her appearance there will be at least $$$a_i$$$ other grannies (including Maria) in the courtyard. Maria can call several grannies at once. In this case, the selected grannies will go out into the courtyard at the same moment of time. She cannot deceive grannies, that is, the situation when the $$$i$$$-th granny in the moment of appearing in the courtyard, finds that now there are strictly less than $$$a_i$$$ other grannies (except herself, but including Maria), is prohibited. Please note that if several grannies appeared in the yard at the same time, then each of them sees others at the time of appearance. Your task is to find what maximum number of grannies (including herself) Maria can collect in the courtyard for the ceremony. After all, the more people in one place during quarantine, the more effective the ceremony!Consider an example: if $$$n=6$$$ and $$$a=[1,5,4,5,1,9]$$$, then: at the first step Maria can call grannies with numbers $$$1$$$ and $$$5$$$, each of them will see two grannies at the moment of going out into the yard (note that $$$a_1=1 \le 2$$$ and $$$a_5=1 \le 2$$$); at the second step, Maria can call grannies with numbers $$$2$$$, $$$3$$$ and $$$4$$$, each of them will see five grannies at the moment of going out into the yard (note that $$$a_2=5 \le 5$$$, $$$a_3=4 \le 5$$$ and $$$a_4=5 \le 5$$$); the $$$6$$$-th granny cannot be called into the yard  — therefore, the answer is $$$6$$$ (Maria herself and another $$$5$$$ grannies).
256 megabytes
import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.regex.*; public class sol24 { private static final Scanner scanner = new Scanner(System.in); public static void main(String[] args) throws IOException { int test; test = scanner.nextInt(); while(test > 0){ test--; int num = scanner.nextInt(); int[] vals = new int[100003*2]; int maxN = -1; int minN = 100003*2+5; for(int i=0; i<num; ++i){ int v = scanner.nextInt(); vals[v]++; if(v > maxN){ maxN = v; } if(v < minN ){ minN = v; } } int cur = num; for(int i = maxN; i>= minN; --i ){ if( i > cur){ cur = cur - vals[i]; } } System.out.println(cur+1); } } }
Java
["4\n5\n1 1 2 2 1\n6\n2 3 4 5 6 7\n6\n1 5 4 5 1 9\n5\n1 2 3 5 6"]
2 seconds
["6\n1\n6\n4"]
NoteIn the first test case in the example, on the first step Maria can call all the grannies. Then each of them will see five grannies when they come out. Therefore, Maria and five other grannies will be in the yard.In the second test case in the example, no one can be in the yard, so Maria will remain there alone.The third test case in the example is described in the details above.In the fourth test case in the example, on the first step Maria can call grannies with numbers $$$1$$$, $$$2$$$ and $$$3$$$. If on the second step Maria calls $$$4$$$ or $$$5$$$ (one of them), then when a granny appears in the yard, she will see only four grannies (but it is forbidden). It means that Maria can't call the $$$4$$$-th granny or the $$$5$$$-th granny separately (one of them). If she calls both: $$$4$$$ and $$$5$$$, then when they appear, they will see $$$4+1=5$$$ grannies. Despite the fact that it is enough for the $$$4$$$-th granny, the $$$5$$$-th granny is not satisfied. So, Maria cannot call both the $$$4$$$-th granny and the $$$5$$$-th granny at the same time. That is, Maria and three grannies from the first step will be in the yard in total.
Java 8
standard input
[ "sortings", "greedy" ]
718cea81f609055cece58cae5310f703
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then test cases follow. The first line of a test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of grannies (Maria is not included in this number). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 2\cdot10^5$$$). It is guaranteed that the sum of the values $$$n$$$ over all test cases of the input does not exceed $$$10^5$$$.
1,000
For each test case, print a single integer $$$k$$$ ($$$1 \le k \le n + 1$$$) — the maximum possible number of grannies in the courtyard.
standard output
PASSED
59ba561485e6cbdcac0286138e0e959e
train_001.jsonl
1590503700
Maria is the most active old lady in her house. She was tired of sitting at home. She decided to organize a ceremony against the coronavirus.She has $$$n$$$ friends who are also grannies (Maria is not included in this number). The $$$i$$$-th granny is ready to attend the ceremony, provided that at the time of her appearance in the courtyard there will be at least $$$a_i$$$ other grannies there. Note that grannies can come into the courtyard at the same time. Formally, the granny $$$i$$$ agrees to come if the number of other grannies who came earlier or at the same time with her is greater than or equal to $$$a_i$$$.Grannies gather in the courtyard like that. Initially, only Maria is in the courtyard (that is, the initial number of grannies in the courtyard is $$$1$$$). All the remaining $$$n$$$ grannies are still sitting at home. On each step Maria selects a subset of grannies, none of whom have yet to enter the courtyard. She promises each of them that at the time of her appearance there will be at least $$$a_i$$$ other grannies (including Maria) in the courtyard. Maria can call several grannies at once. In this case, the selected grannies will go out into the courtyard at the same moment of time. She cannot deceive grannies, that is, the situation when the $$$i$$$-th granny in the moment of appearing in the courtyard, finds that now there are strictly less than $$$a_i$$$ other grannies (except herself, but including Maria), is prohibited. Please note that if several grannies appeared in the yard at the same time, then each of them sees others at the time of appearance. Your task is to find what maximum number of grannies (including herself) Maria can collect in the courtyard for the ceremony. After all, the more people in one place during quarantine, the more effective the ceremony!Consider an example: if $$$n=6$$$ and $$$a=[1,5,4,5,1,9]$$$, then: at the first step Maria can call grannies with numbers $$$1$$$ and $$$5$$$, each of them will see two grannies at the moment of going out into the yard (note that $$$a_1=1 \le 2$$$ and $$$a_5=1 \le 2$$$); at the second step, Maria can call grannies with numbers $$$2$$$, $$$3$$$ and $$$4$$$, each of them will see five grannies at the moment of going out into the yard (note that $$$a_2=5 \le 5$$$, $$$a_3=4 \le 5$$$ and $$$a_4=5 \le 5$$$); the $$$6$$$-th granny cannot be called into the yard  — therefore, the answer is $$$6$$$ (Maria herself and another $$$5$$$ grannies).
256 megabytes
import java.util.*; import java.io.*; public class code{ 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[] arg) throws IOException{ Reader in=new Reader(); int t=in.nextInt(); while(t-- > 0){ int n=in.nextInt(); int[] arr=new int[n]; int count=n; for(int i=0;i<n;i++){ arr[i]=in.nextInt(); } Arrays.sort(arr); for(int i=n-1;i>=0;i--){ if(arr[i]>count){ count--; } } int res=count+1; System.out.println(res); } } }
Java
["4\n5\n1 1 2 2 1\n6\n2 3 4 5 6 7\n6\n1 5 4 5 1 9\n5\n1 2 3 5 6"]
2 seconds
["6\n1\n6\n4"]
NoteIn the first test case in the example, on the first step Maria can call all the grannies. Then each of them will see five grannies when they come out. Therefore, Maria and five other grannies will be in the yard.In the second test case in the example, no one can be in the yard, so Maria will remain there alone.The third test case in the example is described in the details above.In the fourth test case in the example, on the first step Maria can call grannies with numbers $$$1$$$, $$$2$$$ and $$$3$$$. If on the second step Maria calls $$$4$$$ or $$$5$$$ (one of them), then when a granny appears in the yard, she will see only four grannies (but it is forbidden). It means that Maria can't call the $$$4$$$-th granny or the $$$5$$$-th granny separately (one of them). If she calls both: $$$4$$$ and $$$5$$$, then when they appear, they will see $$$4+1=5$$$ grannies. Despite the fact that it is enough for the $$$4$$$-th granny, the $$$5$$$-th granny is not satisfied. So, Maria cannot call both the $$$4$$$-th granny and the $$$5$$$-th granny at the same time. That is, Maria and three grannies from the first step will be in the yard in total.
Java 8
standard input
[ "sortings", "greedy" ]
718cea81f609055cece58cae5310f703
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then test cases follow. The first line of a test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of grannies (Maria is not included in this number). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 2\cdot10^5$$$). It is guaranteed that the sum of the values $$$n$$$ over all test cases of the input does not exceed $$$10^5$$$.
1,000
For each test case, print a single integer $$$k$$$ ($$$1 \le k \le n + 1$$$) — the maximum possible number of grannies in the courtyard.
standard output
PASSED
bb8c2623a212222766ee95a9546a60d1
train_001.jsonl
1590503700
Maria is the most active old lady in her house. She was tired of sitting at home. She decided to organize a ceremony against the coronavirus.She has $$$n$$$ friends who are also grannies (Maria is not included in this number). The $$$i$$$-th granny is ready to attend the ceremony, provided that at the time of her appearance in the courtyard there will be at least $$$a_i$$$ other grannies there. Note that grannies can come into the courtyard at the same time. Formally, the granny $$$i$$$ agrees to come if the number of other grannies who came earlier or at the same time with her is greater than or equal to $$$a_i$$$.Grannies gather in the courtyard like that. Initially, only Maria is in the courtyard (that is, the initial number of grannies in the courtyard is $$$1$$$). All the remaining $$$n$$$ grannies are still sitting at home. On each step Maria selects a subset of grannies, none of whom have yet to enter the courtyard. She promises each of them that at the time of her appearance there will be at least $$$a_i$$$ other grannies (including Maria) in the courtyard. Maria can call several grannies at once. In this case, the selected grannies will go out into the courtyard at the same moment of time. She cannot deceive grannies, that is, the situation when the $$$i$$$-th granny in the moment of appearing in the courtyard, finds that now there are strictly less than $$$a_i$$$ other grannies (except herself, but including Maria), is prohibited. Please note that if several grannies appeared in the yard at the same time, then each of them sees others at the time of appearance. Your task is to find what maximum number of grannies (including herself) Maria can collect in the courtyard for the ceremony. After all, the more people in one place during quarantine, the more effective the ceremony!Consider an example: if $$$n=6$$$ and $$$a=[1,5,4,5,1,9]$$$, then: at the first step Maria can call grannies with numbers $$$1$$$ and $$$5$$$, each of them will see two grannies at the moment of going out into the yard (note that $$$a_1=1 \le 2$$$ and $$$a_5=1 \le 2$$$); at the second step, Maria can call grannies with numbers $$$2$$$, $$$3$$$ and $$$4$$$, each of them will see five grannies at the moment of going out into the yard (note that $$$a_2=5 \le 5$$$, $$$a_3=4 \le 5$$$ and $$$a_4=5 \le 5$$$); the $$$6$$$-th granny cannot be called into the yard  — therefore, the answer is $$$6$$$ (Maria herself and another $$$5$$$ grannies).
256 megabytes
import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.PrintWriter; import java.math.BigInteger; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.PriorityQueue; import java.util.TreeMap; import java.util.TreeSet; public class A { static void merge(int arr[], int l, int m, int r) { int n1 = m - l + 1; int n2 = r - m; int L[] = new int [n1]; int R[] = new int [n2]; for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; int i = 0, j = 0; int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } while (i < n1) { arr[k] = L[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; j++; k++; } } static void sort(int arr[], int l, int r) { if (l < r) { int m = (l+r)/2; sort(arr, l, m); sort(arr , m+1, r); merge(arr, l, m, r); } } static void revOrder(int[] arr) { int[] a = new int[arr.length]; for(int i=0;i<arr.length;i++) { a[i] = arr[arr.length-i-1]; } for(int i=0;i<arr.length;i++) arr[i] = a[i]; } static int next(long target, long[] arr) { int start = 0, end = arr.length - 1; int ans = -1; while (start < end) { int mid = start + (end-start) / 2; if (arr[mid] <=target) { start = mid + 1; ans = mid; } else { end = mid - 1; } } return ans; } static void pf(int n, ArrayList<Integer> al) { for (int i=1; i<=Math.sqrt(n); i++) { if (n%i==0) { if (n/i == i) { al.add(i); } else{ al.add(i); al.add(n/i); } } } } static long power(long x, long y, long p) { long res = 1; x = x % p; if (x == 0) return 0; while (y > 0) { if((y & 1)==1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } static int gcd(int a, int b) { if (a == 0) return b; if (b == 0) return a; int k; for (k = 0; ((a | b) & 1) == 0; ++k) { a >>= 1; b >>= 1; } while ((a & 1) == 0) a >>= 1; do { while ((b & 1) == 0) b >>= 1; if (a > b) { int temp = a; a = b; b = temp; } b = (b - a); } while (b != 0); return a << k; } static long inv(long a, long m){ return power(a, m-2, m); } static DecimalFormat df = new DecimalFormat("0.0000000000"); static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { try { BufferInput in = new BufferInput(); int t = in.nextInt(); while(t-->0) { int n = in.nextInt(); int[] arr = in.nextIntArray(n); sort(arr, 0, n-1); int cnt = 1; int ans = 1; for(int i=0;i<n;i++) { if(arr[i]<=cnt) { cnt++; ans = cnt; } else { ArrayList<Integer> al = new ArrayList<>(); while(i<n&&arr[i]>cnt+al.size()) { al.add(arr[i]); i++; } if(i!=n) { ans = cnt+al.size()+1; cnt=ans; } else { break; } } } out.println(ans); } out.close(); }catch(Exception e) {} } static class Pair implements Comparable<Pair> { int x;int y; Pair(int i,int o) { x=i;y=o; } public int compareTo(Pair n) { if(this.x!=n.x) return this.x-n.x; return this.y-n.y; } } static class BufferInput { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public BufferInput() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public BufferInput(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]; int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public String nextString() throws IOException{ byte c = read(); while(Character.isWhitespace(c)){ c = read(); } StringBuilder builder = new StringBuilder(); builder.append((char)c); c = read(); while(!Character.isWhitespace(c)){ builder.append((char)c); c = read(); } return builder.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 arr[] = new int[n]; for(int i = 0; i < n; i++){ arr[i] = nextInt(); } return arr; } 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 long[] nextLongArray(int n) throws IOException { long arr[] = new long[n]; for(int i = 0; i < n; i++){ arr[i] = nextLong(); } return arr; } public char nextChar() throws IOException{ byte c = read(); while(Character.isWhitespace(c)){ c = read(); } return (char) c; } 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; } public double[] nextDoubleArray(int n) throws IOException { double arr[] = new double[n]; for(int i = 0; i < n; i++){ arr[i] = nextDouble(); } return arr; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } }
Java
["4\n5\n1 1 2 2 1\n6\n2 3 4 5 6 7\n6\n1 5 4 5 1 9\n5\n1 2 3 5 6"]
2 seconds
["6\n1\n6\n4"]
NoteIn the first test case in the example, on the first step Maria can call all the grannies. Then each of them will see five grannies when they come out. Therefore, Maria and five other grannies will be in the yard.In the second test case in the example, no one can be in the yard, so Maria will remain there alone.The third test case in the example is described in the details above.In the fourth test case in the example, on the first step Maria can call grannies with numbers $$$1$$$, $$$2$$$ and $$$3$$$. If on the second step Maria calls $$$4$$$ or $$$5$$$ (one of them), then when a granny appears in the yard, she will see only four grannies (but it is forbidden). It means that Maria can't call the $$$4$$$-th granny or the $$$5$$$-th granny separately (one of them). If she calls both: $$$4$$$ and $$$5$$$, then when they appear, they will see $$$4+1=5$$$ grannies. Despite the fact that it is enough for the $$$4$$$-th granny, the $$$5$$$-th granny is not satisfied. So, Maria cannot call both the $$$4$$$-th granny and the $$$5$$$-th granny at the same time. That is, Maria and three grannies from the first step will be in the yard in total.
Java 8
standard input
[ "sortings", "greedy" ]
718cea81f609055cece58cae5310f703
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then test cases follow. The first line of a test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of grannies (Maria is not included in this number). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 2\cdot10^5$$$). It is guaranteed that the sum of the values $$$n$$$ over all test cases of the input does not exceed $$$10^5$$$.
1,000
For each test case, print a single integer $$$k$$$ ($$$1 \le k \le n + 1$$$) — the maximum possible number of grannies in the courtyard.
standard output
PASSED
408c6968d0c0a2b3fb8066c301d6e025
train_001.jsonl
1590503700
Maria is the most active old lady in her house. She was tired of sitting at home. She decided to organize a ceremony against the coronavirus.She has $$$n$$$ friends who are also grannies (Maria is not included in this number). The $$$i$$$-th granny is ready to attend the ceremony, provided that at the time of her appearance in the courtyard there will be at least $$$a_i$$$ other grannies there. Note that grannies can come into the courtyard at the same time. Formally, the granny $$$i$$$ agrees to come if the number of other grannies who came earlier or at the same time with her is greater than or equal to $$$a_i$$$.Grannies gather in the courtyard like that. Initially, only Maria is in the courtyard (that is, the initial number of grannies in the courtyard is $$$1$$$). All the remaining $$$n$$$ grannies are still sitting at home. On each step Maria selects a subset of grannies, none of whom have yet to enter the courtyard. She promises each of them that at the time of her appearance there will be at least $$$a_i$$$ other grannies (including Maria) in the courtyard. Maria can call several grannies at once. In this case, the selected grannies will go out into the courtyard at the same moment of time. She cannot deceive grannies, that is, the situation when the $$$i$$$-th granny in the moment of appearing in the courtyard, finds that now there are strictly less than $$$a_i$$$ other grannies (except herself, but including Maria), is prohibited. Please note that if several grannies appeared in the yard at the same time, then each of them sees others at the time of appearance. Your task is to find what maximum number of grannies (including herself) Maria can collect in the courtyard for the ceremony. After all, the more people in one place during quarantine, the more effective the ceremony!Consider an example: if $$$n=6$$$ and $$$a=[1,5,4,5,1,9]$$$, then: at the first step Maria can call grannies with numbers $$$1$$$ and $$$5$$$, each of them will see two grannies at the moment of going out into the yard (note that $$$a_1=1 \le 2$$$ and $$$a_5=1 \le 2$$$); at the second step, Maria can call grannies with numbers $$$2$$$, $$$3$$$ and $$$4$$$, each of them will see five grannies at the moment of going out into the yard (note that $$$a_2=5 \le 5$$$, $$$a_3=4 \le 5$$$ and $$$a_4=5 \le 5$$$); the $$$6$$$-th granny cannot be called into the yard  — therefore, the answer is $$$6$$$ (Maria herself and another $$$5$$$ grannies).
256 megabytes
import java.io.*; import java.util.*; public class CfA { static class Reader { BufferedReader br; StringTokenizer st; public Reader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static long binpow(int a, int b) { if (b == 0) return 1; long res = binpow(a, b / 2); if (b % 2 == 1) return res * res * a; else return res * res; } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static int n, m; static int[] arr; public static void main(String[] args) throws Exception { Reader in = new Reader(); // Scanner in = new Scanner(System.in); OutputStream outputStream = System.out; PrintWriter out = new PrintWriter(outputStream); int T = in.nextInt(); while (T-- > 0) { n = in.nextInt(); arr = new int[n]; HashMap<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < n; i++) { arr[i] = in.nextInt(); map.putIfAbsent(arr[i],0); map.put(arr[i],map.get(arr[i])+1); } List<Integer> unique = new ArrayList<>(); unique.addAll(map.keySet()); Collections.sort(unique); // System.out.println(unique); int curr = 1; boolean flag = true; for (int i = 0;i < unique.size();i++) { int val = unique.get(i); // System.out.println("val = " + val); if (curr + map.get(val) > val) curr+=map.get(val); else { // System.out.println("\tcurr = "+curr+" val = "+val); flag = false; int temp = 0; for(int j = i;j < unique.size();j++) { int temp_val = unique.get(j); temp += map.get(temp_val); // System.out.println("\t\ttemp = "+temp+" temp_val = "+temp_val); if(curr + temp > temp_val) { // System.out.println("\t\tfound it"); flag = true; i = j; curr+=temp; break; } } if(!flag){ // System.out.println("\tflag is false breaking..."); break; } } } System.out.println(curr); } out.close(); } }
Java
["4\n5\n1 1 2 2 1\n6\n2 3 4 5 6 7\n6\n1 5 4 5 1 9\n5\n1 2 3 5 6"]
2 seconds
["6\n1\n6\n4"]
NoteIn the first test case in the example, on the first step Maria can call all the grannies. Then each of them will see five grannies when they come out. Therefore, Maria and five other grannies will be in the yard.In the second test case in the example, no one can be in the yard, so Maria will remain there alone.The third test case in the example is described in the details above.In the fourth test case in the example, on the first step Maria can call grannies with numbers $$$1$$$, $$$2$$$ and $$$3$$$. If on the second step Maria calls $$$4$$$ or $$$5$$$ (one of them), then when a granny appears in the yard, she will see only four grannies (but it is forbidden). It means that Maria can't call the $$$4$$$-th granny or the $$$5$$$-th granny separately (one of them). If she calls both: $$$4$$$ and $$$5$$$, then when they appear, they will see $$$4+1=5$$$ grannies. Despite the fact that it is enough for the $$$4$$$-th granny, the $$$5$$$-th granny is not satisfied. So, Maria cannot call both the $$$4$$$-th granny and the $$$5$$$-th granny at the same time. That is, Maria and three grannies from the first step will be in the yard in total.
Java 8
standard input
[ "sortings", "greedy" ]
718cea81f609055cece58cae5310f703
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then test cases follow. The first line of a test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of grannies (Maria is not included in this number). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 2\cdot10^5$$$). It is guaranteed that the sum of the values $$$n$$$ over all test cases of the input does not exceed $$$10^5$$$.
1,000
For each test case, print a single integer $$$k$$$ ($$$1 \le k \le n + 1$$$) — the maximum possible number of grannies in the courtyard.
standard output
PASSED
22841c23ad38c6ab6dc2e478cbc12d74
train_001.jsonl
1590503700
Maria is the most active old lady in her house. She was tired of sitting at home. She decided to organize a ceremony against the coronavirus.She has $$$n$$$ friends who are also grannies (Maria is not included in this number). The $$$i$$$-th granny is ready to attend the ceremony, provided that at the time of her appearance in the courtyard there will be at least $$$a_i$$$ other grannies there. Note that grannies can come into the courtyard at the same time. Formally, the granny $$$i$$$ agrees to come if the number of other grannies who came earlier or at the same time with her is greater than or equal to $$$a_i$$$.Grannies gather in the courtyard like that. Initially, only Maria is in the courtyard (that is, the initial number of grannies in the courtyard is $$$1$$$). All the remaining $$$n$$$ grannies are still sitting at home. On each step Maria selects a subset of grannies, none of whom have yet to enter the courtyard. She promises each of them that at the time of her appearance there will be at least $$$a_i$$$ other grannies (including Maria) in the courtyard. Maria can call several grannies at once. In this case, the selected grannies will go out into the courtyard at the same moment of time. She cannot deceive grannies, that is, the situation when the $$$i$$$-th granny in the moment of appearing in the courtyard, finds that now there are strictly less than $$$a_i$$$ other grannies (except herself, but including Maria), is prohibited. Please note that if several grannies appeared in the yard at the same time, then each of them sees others at the time of appearance. Your task is to find what maximum number of grannies (including herself) Maria can collect in the courtyard for the ceremony. After all, the more people in one place during quarantine, the more effective the ceremony!Consider an example: if $$$n=6$$$ and $$$a=[1,5,4,5,1,9]$$$, then: at the first step Maria can call grannies with numbers $$$1$$$ and $$$5$$$, each of them will see two grannies at the moment of going out into the yard (note that $$$a_1=1 \le 2$$$ and $$$a_5=1 \le 2$$$); at the second step, Maria can call grannies with numbers $$$2$$$, $$$3$$$ and $$$4$$$, each of them will see five grannies at the moment of going out into the yard (note that $$$a_2=5 \le 5$$$, $$$a_3=4 \le 5$$$ and $$$a_4=5 \le 5$$$); the $$$6$$$-th granny cannot be called into the yard  — therefore, the answer is $$$6$$$ (Maria herself and another $$$5$$$ grannies).
256 megabytes
//package asd; import java.util.Arrays; import java.util.Scanner; public class Demo2 { public static void main(String[] args) { Scanner s=new Scanner(System.in); int x = s.nextInt(); while(x-->0) { int m = s.nextInt(); int[] g = new int[m]; for(int i=0;i<m;i++) { g[i]= s.nextInt(); } Arrays.sort(g); int count=1; int temp=0; for(int i=0;i<m;i++) { if(g[i]<=count) { count++; }else { if(g[i]<=temp+count) { count= temp+count+1; temp=0; }else { temp++; } } } System.out.println(count); } // int[] arr = new int[x]; // int[] arr1 = new int[x]; // for(int i=0;i<x;i++) { // arr[i] =s.nextInt(); // } // for(int i=0;i<x;i++) { // arr1[i] =s.nextInt(); //// } // int [] h = {1,2,1,1,1,1}; // int [] p = {3,4,2,1,2,3,4,5,6,7,8,9,2,3,4,5,6,8}; //// System.out.println(subset(h, p)); } }
Java
["4\n5\n1 1 2 2 1\n6\n2 3 4 5 6 7\n6\n1 5 4 5 1 9\n5\n1 2 3 5 6"]
2 seconds
["6\n1\n6\n4"]
NoteIn the first test case in the example, on the first step Maria can call all the grannies. Then each of them will see five grannies when they come out. Therefore, Maria and five other grannies will be in the yard.In the second test case in the example, no one can be in the yard, so Maria will remain there alone.The third test case in the example is described in the details above.In the fourth test case in the example, on the first step Maria can call grannies with numbers $$$1$$$, $$$2$$$ and $$$3$$$. If on the second step Maria calls $$$4$$$ or $$$5$$$ (one of them), then when a granny appears in the yard, she will see only four grannies (but it is forbidden). It means that Maria can't call the $$$4$$$-th granny or the $$$5$$$-th granny separately (one of them). If she calls both: $$$4$$$ and $$$5$$$, then when they appear, they will see $$$4+1=5$$$ grannies. Despite the fact that it is enough for the $$$4$$$-th granny, the $$$5$$$-th granny is not satisfied. So, Maria cannot call both the $$$4$$$-th granny and the $$$5$$$-th granny at the same time. That is, Maria and three grannies from the first step will be in the yard in total.
Java 8
standard input
[ "sortings", "greedy" ]
718cea81f609055cece58cae5310f703
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then test cases follow. The first line of a test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of grannies (Maria is not included in this number). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 2\cdot10^5$$$). It is guaranteed that the sum of the values $$$n$$$ over all test cases of the input does not exceed $$$10^5$$$.
1,000
For each test case, print a single integer $$$k$$$ ($$$1 \le k \le n + 1$$$) — the maximum possible number of grannies in the courtyard.
standard output
PASSED
7fdd0ad2b7cafa2088c1e5fe23778881
train_001.jsonl
1590503700
Maria is the most active old lady in her house. She was tired of sitting at home. She decided to organize a ceremony against the coronavirus.She has $$$n$$$ friends who are also grannies (Maria is not included in this number). The $$$i$$$-th granny is ready to attend the ceremony, provided that at the time of her appearance in the courtyard there will be at least $$$a_i$$$ other grannies there. Note that grannies can come into the courtyard at the same time. Formally, the granny $$$i$$$ agrees to come if the number of other grannies who came earlier or at the same time with her is greater than or equal to $$$a_i$$$.Grannies gather in the courtyard like that. Initially, only Maria is in the courtyard (that is, the initial number of grannies in the courtyard is $$$1$$$). All the remaining $$$n$$$ grannies are still sitting at home. On each step Maria selects a subset of grannies, none of whom have yet to enter the courtyard. She promises each of them that at the time of her appearance there will be at least $$$a_i$$$ other grannies (including Maria) in the courtyard. Maria can call several grannies at once. In this case, the selected grannies will go out into the courtyard at the same moment of time. She cannot deceive grannies, that is, the situation when the $$$i$$$-th granny in the moment of appearing in the courtyard, finds that now there are strictly less than $$$a_i$$$ other grannies (except herself, but including Maria), is prohibited. Please note that if several grannies appeared in the yard at the same time, then each of them sees others at the time of appearance. Your task is to find what maximum number of grannies (including herself) Maria can collect in the courtyard for the ceremony. After all, the more people in one place during quarantine, the more effective the ceremony!Consider an example: if $$$n=6$$$ and $$$a=[1,5,4,5,1,9]$$$, then: at the first step Maria can call grannies with numbers $$$1$$$ and $$$5$$$, each of them will see two grannies at the moment of going out into the yard (note that $$$a_1=1 \le 2$$$ and $$$a_5=1 \le 2$$$); at the second step, Maria can call grannies with numbers $$$2$$$, $$$3$$$ and $$$4$$$, each of them will see five grannies at the moment of going out into the yard (note that $$$a_2=5 \le 5$$$, $$$a_3=4 \le 5$$$ and $$$a_4=5 \le 5$$$); the $$$6$$$-th granny cannot be called into the yard  — therefore, the answer is $$$6$$$ (Maria herself and another $$$5$$$ grannies).
256 megabytes
import java.util.*; import java.util.Arrays; public class f { static Scanner sc=new Scanner(System.in); public static void main(String[] args) { int t=sc.nextInt(); for(int i1=0;i1<t;i1++) { int n=sc.nextInt(); int arr[]=new int[n]; for(int i=0;i<n;i++) { arr[i]=sc.nextInt(); } Arrays.sort(arr); int granny=0,flag=0,k=0; for(int i=0;i<n;i++) { granny++; if(arr[i]>granny) { flag=1; } else { flag=0; k=granny; } } if(flag==0) { System.out.println(granny+1);} else { System.out.println(k+1);} } } }
Java
["4\n5\n1 1 2 2 1\n6\n2 3 4 5 6 7\n6\n1 5 4 5 1 9\n5\n1 2 3 5 6"]
2 seconds
["6\n1\n6\n4"]
NoteIn the first test case in the example, on the first step Maria can call all the grannies. Then each of them will see five grannies when they come out. Therefore, Maria and five other grannies will be in the yard.In the second test case in the example, no one can be in the yard, so Maria will remain there alone.The third test case in the example is described in the details above.In the fourth test case in the example, on the first step Maria can call grannies with numbers $$$1$$$, $$$2$$$ and $$$3$$$. If on the second step Maria calls $$$4$$$ or $$$5$$$ (one of them), then when a granny appears in the yard, she will see only four grannies (but it is forbidden). It means that Maria can't call the $$$4$$$-th granny or the $$$5$$$-th granny separately (one of them). If she calls both: $$$4$$$ and $$$5$$$, then when they appear, they will see $$$4+1=5$$$ grannies. Despite the fact that it is enough for the $$$4$$$-th granny, the $$$5$$$-th granny is not satisfied. So, Maria cannot call both the $$$4$$$-th granny and the $$$5$$$-th granny at the same time. That is, Maria and three grannies from the first step will be in the yard in total.
Java 8
standard input
[ "sortings", "greedy" ]
718cea81f609055cece58cae5310f703
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then test cases follow. The first line of a test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of grannies (Maria is not included in this number). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 2\cdot10^5$$$). It is guaranteed that the sum of the values $$$n$$$ over all test cases of the input does not exceed $$$10^5$$$.
1,000
For each test case, print a single integer $$$k$$$ ($$$1 \le k \le n + 1$$$) — the maximum possible number of grannies in the courtyard.
standard output
PASSED
4605566e1dd9b782411c2cec919459f3
train_001.jsonl
1595342100
This is the easy version of the problem. The difference between the versions is the constraint on $$$n$$$ and the required number of operations. You can make hacks only if all versions of the problem are solved.There are two binary strings $$$a$$$ and $$$b$$$ of length $$$n$$$ (a binary string is a string consisting of symbols $$$0$$$ and $$$1$$$). In an operation, you select a prefix of $$$a$$$, and simultaneously invert the bits in the prefix ($$$0$$$ changes to $$$1$$$ and $$$1$$$ changes to $$$0$$$) and reverse the order of the bits in the prefix.For example, if $$$a=001011$$$ and you select the prefix of length $$$3$$$, it becomes $$$011011$$$. Then if you select the entire string, it becomes $$$001001$$$.Your task is to transform the string $$$a$$$ into $$$b$$$ in at most $$$3n$$$ operations. It can be proved that it is always possible.
256 megabytes
import java.io.*; import java.util.*; public class A { static int n; static int[] arr; static char[] a, b; public static void main(String[] args) throws IOException { Flash f = new Flash(); int T = f.ni(); for(int tc = 1; tc <= T; tc++){ n = f.ni(); a = new char[n+1]; b = new char[n+1]; String s1 = f.ns(), s2 = f.ns(); for(int i = 1; i <= n; i++){ a[i] = s1.charAt(i-1); b[i] = s2.charAt(i-1); } fn(); } } static void fn() { int cnt = 0; List<Integer> ans = new ArrayList<>(); for(int i = n; i >= 1; i--){ if(a[i] == b[i]) continue; cnt++; if(a[1] != b[i]) ans.add(i); else{ ans.add(1); a[1] = a[1] == '0' ? '1' : '0'; if(i == 1) break; ans.add(i); cnt++; } for(int j = 1; j <= i; j++) a[j] = a[j] == '0' ? '1' : '0'; for(int l = 1, r = i; l < r; l++, r--){ char t = a[l]; a[l] = a[r]; a[r] = t; } } StringBuilder sb = new StringBuilder(); sb.append(cnt + " "); for(int v : ans) sb.append(v + " "); sop(sb); } static void sort(int[] a){ List<Integer> A = new ArrayList<>(); for(int i : a) A.add(i); Collections.sort(A); for(int i = 0; i < A.size(); i++) a[i] = A.get(i); } static int swap(int itself, int dummy){ return itself; } static void sop(Object o){ System.out.println(o); } static void print(int[] a){ StringBuilder sb = new StringBuilder(); for(int i = 0; i < a.length; i++) sb.append(a[i] + " "); System.out.println(sb); } static class Flash { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next(){ while(!st.hasMoreTokens()){ try{ st = new StringTokenizer(br.readLine()); }catch(IOException e){ e.printStackTrace(); } } return st.nextToken(); } String ns(){ String s = new String(); try{ s = br.readLine().trim(); }catch(IOException e){ e.printStackTrace(); } return s; } int ni(){ return Integer.parseInt(next()); } int[] arr(int n){ int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = ni(); return a; } long nl(){ return Long.parseLong(next()); } double nd(){ return Double.parseDouble(next()); } } }
Java
["5\n2\n01\n10\n5\n01011\n11100\n2\n01\n01\n10\n0110011011\n1000110100\n1\n0\n1"]
1 second
["3 1 2 1\n6 5 2 5 3 1 2\n0\n9 4 1 2 10 4 1 2 1 5\n1 1"]
NoteIn the first test case, we have $$$01\to 11\to 00\to 10$$$.In the second test case, we have $$$01011\to 00101\to 11101\to 01000\to 10100\to 00100\to 11100$$$.In the third test case, the strings are already the same. Another solution is to flip the prefix of length $$$2$$$, which will leave $$$a$$$ unchanged.
Java 11
standard input
[ "data structures", "constructive algorithms", "strings" ]
10c9b2d70030f7ed680297455d1f1bb0
The first line contains a single integer $$$t$$$ ($$$1\le t\le 1000$$$)  — the number of test cases. Next $$$3t$$$ lines contain descriptions of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 1000$$$)  — the length of the binary strings. The next two lines contain two binary strings $$$a$$$ and $$$b$$$ of length $$$n$$$. It is guaranteed that the sum of $$$n$$$ across all test cases does not exceed $$$1000$$$.
1,300
For each test case, output an integer $$$k$$$ ($$$0\le k\le 3n$$$), followed by $$$k$$$ integers $$$p_1,\ldots,p_k$$$ ($$$1\le p_i\le n$$$). Here $$$k$$$ is the number of operations you use and $$$p_i$$$ is the length of the prefix you flip in the $$$i$$$-th operation.
standard output
PASSED
8ee3deb54623f2b40a249a46935c728c
train_001.jsonl
1595342100
This is the easy version of the problem. The difference between the versions is the constraint on $$$n$$$ and the required number of operations. You can make hacks only if all versions of the problem are solved.There are two binary strings $$$a$$$ and $$$b$$$ of length $$$n$$$ (a binary string is a string consisting of symbols $$$0$$$ and $$$1$$$). In an operation, you select a prefix of $$$a$$$, and simultaneously invert the bits in the prefix ($$$0$$$ changes to $$$1$$$ and $$$1$$$ changes to $$$0$$$) and reverse the order of the bits in the prefix.For example, if $$$a=001011$$$ and you select the prefix of length $$$3$$$, it becomes $$$011011$$$. Then if you select the entire string, it becomes $$$001001$$$.Your task is to transform the string $$$a$$$ into $$$b$$$ in at most $$$3n$$$ operations. It can be proved that it is always possible.
256 megabytes
import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; public class C { public static PrintWriter out = new PrintWriter(System.out); public static Scanner in = new Scanner(System.in); public static void main(String[] args) { int t = ni(); while (t-- > 0) solve(); out.flush(); } static StringBuilder ans; static int count; private static void solve() { int n = ni(); char[] s = in.next().toCharArray(); char[] t = in.next().toCharArray(); ans = new StringBuilder(2 * n); count = 0; recur(s, t, n - 1); out.println(count + " " + ans); // out.println(Arrays.toString(s)); // out.println(Arrays.toString(t)); } private static void recur(char[] s, char[] t, int i) { while (i >= 0) { if (s[i] == t[i]) i--; else if (s[0] != t[i]) { ans.append(i + 1).append(" "); count++; swap(s, i); } else { ans.append(1).append(" "); count++; swap(s, 0); ans.append(i + 1).append(" "); count++; swap(s, i); } } } private static void swap(char[] s, int i) { int j = 0; int loop = i; while (loop >= 0) { if (s[i] == s[j]) { s[i] = s[j] = (s[i] == '0') ? '1' : '0'; } i--; loop -= 2; j++; } } private static int ni() { return in.nextInt(); } private static int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } private static long[] nal(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nl(); return a; } private static long nl() { return in.nextLong(); } private float nf() { return in.nextFloat(); } private static double nd() { return in.nextDouble(); } }
Java
["5\n2\n01\n10\n5\n01011\n11100\n2\n01\n01\n10\n0110011011\n1000110100\n1\n0\n1"]
1 second
["3 1 2 1\n6 5 2 5 3 1 2\n0\n9 4 1 2 10 4 1 2 1 5\n1 1"]
NoteIn the first test case, we have $$$01\to 11\to 00\to 10$$$.In the second test case, we have $$$01011\to 00101\to 11101\to 01000\to 10100\to 00100\to 11100$$$.In the third test case, the strings are already the same. Another solution is to flip the prefix of length $$$2$$$, which will leave $$$a$$$ unchanged.
Java 11
standard input
[ "data structures", "constructive algorithms", "strings" ]
10c9b2d70030f7ed680297455d1f1bb0
The first line contains a single integer $$$t$$$ ($$$1\le t\le 1000$$$)  — the number of test cases. Next $$$3t$$$ lines contain descriptions of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 1000$$$)  — the length of the binary strings. The next two lines contain two binary strings $$$a$$$ and $$$b$$$ of length $$$n$$$. It is guaranteed that the sum of $$$n$$$ across all test cases does not exceed $$$1000$$$.
1,300
For each test case, output an integer $$$k$$$ ($$$0\le k\le 3n$$$), followed by $$$k$$$ integers $$$p_1,\ldots,p_k$$$ ($$$1\le p_i\le n$$$). Here $$$k$$$ is the number of operations you use and $$$p_i$$$ is the length of the prefix you flip in the $$$i$$$-th operation.
standard output
PASSED
856a7aa6f429c571810ca64eebb2d255
train_001.jsonl
1595342100
This is the easy version of the problem. The difference between the versions is the constraint on $$$n$$$ and the required number of operations. You can make hacks only if all versions of the problem are solved.There are two binary strings $$$a$$$ and $$$b$$$ of length $$$n$$$ (a binary string is a string consisting of symbols $$$0$$$ and $$$1$$$). In an operation, you select a prefix of $$$a$$$, and simultaneously invert the bits in the prefix ($$$0$$$ changes to $$$1$$$ and $$$1$$$ changes to $$$0$$$) and reverse the order of the bits in the prefix.For example, if $$$a=001011$$$ and you select the prefix of length $$$3$$$, it becomes $$$011011$$$. Then if you select the entire string, it becomes $$$001001$$$.Your task is to transform the string $$$a$$$ into $$$b$$$ in at most $$$3n$$$ operations. It can be proved that it is always possible.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; public final class C { public static void main(String[] args) { final Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); final int t = Integer.parseInt(in.nextLine()); for (int x = 0; x < t; x++) { final int n = Integer.parseInt(in.nextLine()); final String s1 = in.nextLine(); final String s2 = in.nextLine(); final List<Integer> first = new ArrayList<>(); final List<Integer> second = new ArrayList<>(); flipZero(s1, n, first); flipZero(s2, n, second); Collections.reverse(second); first.addAll(second); System.out.print(first.size() + " "); for (int num : first) { System.out.print(num + " "); } System.out.println(); } } private static void flipZero(String str, int n, List<Integer> first) { for (int i = 0; i < n - 1; i++) { if (str.charAt(i) != str.charAt(i + 1)) { first.add(i + 1); } } if (str.charAt(str.length() - 1) == '1') { first.add(n); } } }
Java
["5\n2\n01\n10\n5\n01011\n11100\n2\n01\n01\n10\n0110011011\n1000110100\n1\n0\n1"]
1 second
["3 1 2 1\n6 5 2 5 3 1 2\n0\n9 4 1 2 10 4 1 2 1 5\n1 1"]
NoteIn the first test case, we have $$$01\to 11\to 00\to 10$$$.In the second test case, we have $$$01011\to 00101\to 11101\to 01000\to 10100\to 00100\to 11100$$$.In the third test case, the strings are already the same. Another solution is to flip the prefix of length $$$2$$$, which will leave $$$a$$$ unchanged.
Java 11
standard input
[ "data structures", "constructive algorithms", "strings" ]
10c9b2d70030f7ed680297455d1f1bb0
The first line contains a single integer $$$t$$$ ($$$1\le t\le 1000$$$)  — the number of test cases. Next $$$3t$$$ lines contain descriptions of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 1000$$$)  — the length of the binary strings. The next two lines contain two binary strings $$$a$$$ and $$$b$$$ of length $$$n$$$. It is guaranteed that the sum of $$$n$$$ across all test cases does not exceed $$$1000$$$.
1,300
For each test case, output an integer $$$k$$$ ($$$0\le k\le 3n$$$), followed by $$$k$$$ integers $$$p_1,\ldots,p_k$$$ ($$$1\le p_i\le n$$$). Here $$$k$$$ is the number of operations you use and $$$p_i$$$ is the length of the prefix you flip in the $$$i$$$-th operation.
standard output
PASSED
aaeda2fccceeadb8b5ee6bf97ea46664
train_001.jsonl
1595342100
This is the easy version of the problem. The difference between the versions is the constraint on $$$n$$$ and the required number of operations. You can make hacks only if all versions of the problem are solved.There are two binary strings $$$a$$$ and $$$b$$$ of length $$$n$$$ (a binary string is a string consisting of symbols $$$0$$$ and $$$1$$$). In an operation, you select a prefix of $$$a$$$, and simultaneously invert the bits in the prefix ($$$0$$$ changes to $$$1$$$ and $$$1$$$ changes to $$$0$$$) and reverse the order of the bits in the prefix.For example, if $$$a=001011$$$ and you select the prefix of length $$$3$$$, it becomes $$$011011$$$. Then if you select the entire string, it becomes $$$001001$$$.Your task is to transform the string $$$a$$$ into $$$b$$$ in at most $$$3n$$$ operations. It can be proved that it is always possible.
256 megabytes
import java.io.*; import java.util.*; public class Main { static Scanner sc = new Scanner(System.in); static PrintWriter out = new PrintWriter(System.out); static void reverse(char[] arr, int len) { Stack<Character> st = new Stack<>(); for(int i = 0; i < len; i++) { char c = arr[i] == '0' ? '1' : '0'; st.push(c); } for(int i = 0; i < len; i++) { arr[i] = st.pop(); } } static void solve() throws Exception{ int n = sc.nextInt(); char a[] = sc.nextLine().toCharArray(); char b[] = sc.nextLine().toCharArray(); ArrayList<Integer> ans = new ArrayList<>(); for(int i = n - 1; i > 0; i--) { if(a[i] == b[i]) continue; if(a[0] != b[i]) { ans.add(i + 1); reverse(a, i + 1); }else { ans.add(1); ans.add(i + 1); a[0] = a[i]; reverse(a, i + 1); } } if(a[0] != b[0]) ans.add(1); out.print(ans.size() + " "); for(int x : ans) out.print(x + " "); out.println(); } public static void main(String[] args) throws Exception { int t = sc.nextInt(); while(t-- > 0) { solve(); } out.close(); } } class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public Long nextLong() throws IOException { return Long.parseLong(next()); } }
Java
["5\n2\n01\n10\n5\n01011\n11100\n2\n01\n01\n10\n0110011011\n1000110100\n1\n0\n1"]
1 second
["3 1 2 1\n6 5 2 5 3 1 2\n0\n9 4 1 2 10 4 1 2 1 5\n1 1"]
NoteIn the first test case, we have $$$01\to 11\to 00\to 10$$$.In the second test case, we have $$$01011\to 00101\to 11101\to 01000\to 10100\to 00100\to 11100$$$.In the third test case, the strings are already the same. Another solution is to flip the prefix of length $$$2$$$, which will leave $$$a$$$ unchanged.
Java 11
standard input
[ "data structures", "constructive algorithms", "strings" ]
10c9b2d70030f7ed680297455d1f1bb0
The first line contains a single integer $$$t$$$ ($$$1\le t\le 1000$$$)  — the number of test cases. Next $$$3t$$$ lines contain descriptions of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 1000$$$)  — the length of the binary strings. The next two lines contain two binary strings $$$a$$$ and $$$b$$$ of length $$$n$$$. It is guaranteed that the sum of $$$n$$$ across all test cases does not exceed $$$1000$$$.
1,300
For each test case, output an integer $$$k$$$ ($$$0\le k\le 3n$$$), followed by $$$k$$$ integers $$$p_1,\ldots,p_k$$$ ($$$1\le p_i\le n$$$). Here $$$k$$$ is the number of operations you use and $$$p_i$$$ is the length of the prefix you flip in the $$$i$$$-th operation.
standard output
PASSED
62932224d747588b97d430798f2cc8ba
train_001.jsonl
1595342100
This is the easy version of the problem. The difference between the versions is the constraint on $$$n$$$ and the required number of operations. You can make hacks only if all versions of the problem are solved.There are two binary strings $$$a$$$ and $$$b$$$ of length $$$n$$$ (a binary string is a string consisting of symbols $$$0$$$ and $$$1$$$). In an operation, you select a prefix of $$$a$$$, and simultaneously invert the bits in the prefix ($$$0$$$ changes to $$$1$$$ and $$$1$$$ changes to $$$0$$$) and reverse the order of the bits in the prefix.For example, if $$$a=001011$$$ and you select the prefix of length $$$3$$$, it becomes $$$011011$$$. Then if you select the entire string, it becomes $$$001001$$$.Your task is to transform the string $$$a$$$ into $$$b$$$ in at most $$$3n$$$ operations. It can be proved that it is always possible.
256 megabytes
import java.io.*; import java.text.*; import java.util.*; import java.math.*; public class template { public static void main(String[] args) throws Exception { new template().run(); } public void run() throws Exception { FastScanner f = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int t = f.nextInt(); while(t-->0) { int n = f.nextInt(); char[] a = f.next().toCharArray(); char[] b = f.next().toCharArray(); int parity = 0; ArrayList<Integer> moves = new ArrayList<>(); for(int i = 0; i < n; i++) { if(i % 2 == 0) { if(b[n-i-1] == (a[i/2]^parity)) moves.add(1); } else { if(b[n-i-1] == (a[n-i/2-1]^parity)) moves.add(1); } moves.add(n-i); parity ^= 1; } out.print(moves.size()); for(int i : moves) out.print(" " + i); out.println(); } out.flush(); } /// static class FastScanner { public BufferedReader reader; public StringTokenizer tokenizer; public FastScanner() { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { try { return reader.readLine(); } catch(IOException e) { throw new RuntimeException(e); } } } }
Java
["5\n2\n01\n10\n5\n01011\n11100\n2\n01\n01\n10\n0110011011\n1000110100\n1\n0\n1"]
1 second
["3 1 2 1\n6 5 2 5 3 1 2\n0\n9 4 1 2 10 4 1 2 1 5\n1 1"]
NoteIn the first test case, we have $$$01\to 11\to 00\to 10$$$.In the second test case, we have $$$01011\to 00101\to 11101\to 01000\to 10100\to 00100\to 11100$$$.In the third test case, the strings are already the same. Another solution is to flip the prefix of length $$$2$$$, which will leave $$$a$$$ unchanged.
Java 11
standard input
[ "data structures", "constructive algorithms", "strings" ]
10c9b2d70030f7ed680297455d1f1bb0
The first line contains a single integer $$$t$$$ ($$$1\le t\le 1000$$$)  — the number of test cases. Next $$$3t$$$ lines contain descriptions of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 1000$$$)  — the length of the binary strings. The next two lines contain two binary strings $$$a$$$ and $$$b$$$ of length $$$n$$$. It is guaranteed that the sum of $$$n$$$ across all test cases does not exceed $$$1000$$$.
1,300
For each test case, output an integer $$$k$$$ ($$$0\le k\le 3n$$$), followed by $$$k$$$ integers $$$p_1,\ldots,p_k$$$ ($$$1\le p_i\le n$$$). Here $$$k$$$ is the number of operations you use and $$$p_i$$$ is the length of the prefix you flip in the $$$i$$$-th operation.
standard output
PASSED
97981cd294abf56f063d84944ca46cf6
train_001.jsonl
1595342100
This is the easy version of the problem. The difference between the versions is the constraint on $$$n$$$ and the required number of operations. You can make hacks only if all versions of the problem are solved.There are two binary strings $$$a$$$ and $$$b$$$ of length $$$n$$$ (a binary string is a string consisting of symbols $$$0$$$ and $$$1$$$). In an operation, you select a prefix of $$$a$$$, and simultaneously invert the bits in the prefix ($$$0$$$ changes to $$$1$$$ and $$$1$$$ changes to $$$0$$$) and reverse the order of the bits in the prefix.For example, if $$$a=001011$$$ and you select the prefix of length $$$3$$$, it becomes $$$011011$$$. Then if you select the entire string, it becomes $$$001001$$$.Your task is to transform the string $$$a$$$ into $$$b$$$ in at most $$$3n$$$ operations. It can be proved that it is always possible.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.*; import java.util.*; /** * Accomplished using the EduTools plugin by JetBrains https://plugins.jetbrains.com/plugin/10081-edutools */ public class Main { public static void main(String[] args) { // Write your solution here FastReader in = new FastReader(); int tt = in.nextInt(); while(tt-- > 0){ int n = in.nextInt(); String s = in.nextLine(); String t = in.nextLine(); List<Integer> l = new ArrayList<>(); for(int i = 0; i < n; i++){ if(s.charAt(i) != t.charAt(i)){ if(i > 0){ l.add(i + 1); // flip the prefix of length i } l.add(1); // flip the prefix of length 1 if(i > 0){ l.add(i + 1); // flip the prefix of length i again } } } System.out.print(l.size() + " "); for(int num : l){ System.out.print(num + " "); } System.out.println(); } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5\n2\n01\n10\n5\n01011\n11100\n2\n01\n01\n10\n0110011011\n1000110100\n1\n0\n1"]
1 second
["3 1 2 1\n6 5 2 5 3 1 2\n0\n9 4 1 2 10 4 1 2 1 5\n1 1"]
NoteIn the first test case, we have $$$01\to 11\to 00\to 10$$$.In the second test case, we have $$$01011\to 00101\to 11101\to 01000\to 10100\to 00100\to 11100$$$.In the third test case, the strings are already the same. Another solution is to flip the prefix of length $$$2$$$, which will leave $$$a$$$ unchanged.
Java 11
standard input
[ "data structures", "constructive algorithms", "strings" ]
10c9b2d70030f7ed680297455d1f1bb0
The first line contains a single integer $$$t$$$ ($$$1\le t\le 1000$$$)  — the number of test cases. Next $$$3t$$$ lines contain descriptions of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 1000$$$)  — the length of the binary strings. The next two lines contain two binary strings $$$a$$$ and $$$b$$$ of length $$$n$$$. It is guaranteed that the sum of $$$n$$$ across all test cases does not exceed $$$1000$$$.
1,300
For each test case, output an integer $$$k$$$ ($$$0\le k\le 3n$$$), followed by $$$k$$$ integers $$$p_1,\ldots,p_k$$$ ($$$1\le p_i\le n$$$). Here $$$k$$$ is the number of operations you use and $$$p_i$$$ is the length of the prefix you flip in the $$$i$$$-th operation.
standard output
PASSED
1c329f1b0dc85e2ac1632d20bf11cb10
train_001.jsonl
1595342100
This is the easy version of the problem. The difference between the versions is the constraint on $$$n$$$ and the required number of operations. You can make hacks only if all versions of the problem are solved.There are two binary strings $$$a$$$ and $$$b$$$ of length $$$n$$$ (a binary string is a string consisting of symbols $$$0$$$ and $$$1$$$). In an operation, you select a prefix of $$$a$$$, and simultaneously invert the bits in the prefix ($$$0$$$ changes to $$$1$$$ and $$$1$$$ changes to $$$0$$$) and reverse the order of the bits in the prefix.For example, if $$$a=001011$$$ and you select the prefix of length $$$3$$$, it becomes $$$011011$$$. Then if you select the entire string, it becomes $$$001001$$$.Your task is to transform the string $$$a$$$ into $$$b$$$ in at most $$$3n$$$ operations. It can be proved that it is always possible.
256 megabytes
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ import java.util.*; import java.io.*; /** * * @author billy */ public class PrefixFlip { static class Pair implements Comparable<Pair>{ int x; int y; Pair (int x0, int y0){ x=x0; y=y0; } public int compareTo(Pair e){ if (y>e.y){ return 1; } else if (y<e.y){ return -1; } else return 0; } } static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); static StringTokenizer st; static String flip(String a, int ind){ String temp = ""; for (int i = ind-1; i>=0; i--){ if (a.charAt(i)=='1'){ temp+="0"; } else{ temp+="1"; } } if (ind!=a.length() && ind>0){ return temp + a.substring(ind); } else{ return temp; } } public static void main(String[] args) throws IOException { //fip isnt workuing for (int t = readInt(); t>0; t--){ int n = readInt(); String a = readLine(); String b = readLine(); ArrayList<Integer> ans = new ArrayList(); for (int i =n-1; i>=0; i--){ if (a.charAt(i)!=b.charAt(i)){ ans.add(i+1); a = flip(a,i+1); if (check(a,b)){ break; } ans.add(1); a = flip(a,1); if (check(a, b)) { break; } ans.add(i+1); a = flip(a,i+1); if (check(a, b)) { break; } } } System.out.print(ans.size() + " "); for (int i =0; i<ans.size(); i++){ System.out.print(ans.get(i) + " "); } System.out.println(); } } static boolean check(String a, String b){ for (int i =0; i<a.length(); i++){ if (a.charAt(i) == b.charAt(i)){ continue; } return false; } return true; } static String read () throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine().trim()); return st.nextToken(); } //© Maillew DMOJ static long readLong () throws IOException { return Long.parseLong(read()); } static int readInt () throws IOException { return Integer.parseInt(read()); } static double readDouble () throws IOException { return Double.parseDouble(read()); } static char readChar () throws IOException { return read().charAt(0); } static String readLine () throws IOException { return br.readLine().trim(); } }
Java
["5\n2\n01\n10\n5\n01011\n11100\n2\n01\n01\n10\n0110011011\n1000110100\n1\n0\n1"]
1 second
["3 1 2 1\n6 5 2 5 3 1 2\n0\n9 4 1 2 10 4 1 2 1 5\n1 1"]
NoteIn the first test case, we have $$$01\to 11\to 00\to 10$$$.In the second test case, we have $$$01011\to 00101\to 11101\to 01000\to 10100\to 00100\to 11100$$$.In the third test case, the strings are already the same. Another solution is to flip the prefix of length $$$2$$$, which will leave $$$a$$$ unchanged.
Java 11
standard input
[ "data structures", "constructive algorithms", "strings" ]
10c9b2d70030f7ed680297455d1f1bb0
The first line contains a single integer $$$t$$$ ($$$1\le t\le 1000$$$)  — the number of test cases. Next $$$3t$$$ lines contain descriptions of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 1000$$$)  — the length of the binary strings. The next two lines contain two binary strings $$$a$$$ and $$$b$$$ of length $$$n$$$. It is guaranteed that the sum of $$$n$$$ across all test cases does not exceed $$$1000$$$.
1,300
For each test case, output an integer $$$k$$$ ($$$0\le k\le 3n$$$), followed by $$$k$$$ integers $$$p_1,\ldots,p_k$$$ ($$$1\le p_i\le n$$$). Here $$$k$$$ is the number of operations you use and $$$p_i$$$ is the length of the prefix you flip in the $$$i$$$-th operation.
standard output
PASSED
2570fb439b95d79e00ce4c4354032509
train_001.jsonl
1595342100
This is the easy version of the problem. The difference between the versions is the constraint on $$$n$$$ and the required number of operations. You can make hacks only if all versions of the problem are solved.There are two binary strings $$$a$$$ and $$$b$$$ of length $$$n$$$ (a binary string is a string consisting of symbols $$$0$$$ and $$$1$$$). In an operation, you select a prefix of $$$a$$$, and simultaneously invert the bits in the prefix ($$$0$$$ changes to $$$1$$$ and $$$1$$$ changes to $$$0$$$) and reverse the order of the bits in the prefix.For example, if $$$a=001011$$$ and you select the prefix of length $$$3$$$, it becomes $$$011011$$$. Then if you select the entire string, it becomes $$$001001$$$.Your task is to transform the string $$$a$$$ into $$$b$$$ in at most $$$3n$$$ operations. It can be proved that it is always possible.
256 megabytes
import java.util.*; import java.io.*; public class Question3 { static FastReader sc = new FastReader(); static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); public static void main(String[] args) throws IOException{ int t = sc.nextInt(); while(t-->0) { solve(); } bw.flush(); bw.close(); } public static void solve() throws IOException{ int n = sc.nextInt(); char[] arr = new char[n]; char[] brr = new char[n]; arr = sc.next().toCharArray(); brr = sc.next().toCharArray(); int i = n - 1; ArrayList<Integer> list = new ArrayList<Integer>(); while(i >= 0) { if(arr[i] != brr[i]) { //different.. if(i > 0 && arr[i] != arr[0]) { arr[0] = arr[i]; list.add(1); } list.add(i + 1); arr = prefixize(arr, i + 1); } i--; } bw.write(String.valueOf(list.size()) + " "); for(int a = 0;a < list.size();a++)bw.write(String.valueOf(list.get(a)) + " "); bw.write("\n"); } public static char[] prefixize(char[] arr, int n) { int val = n/2; if(n % 2 == 1)val++; for(int i = 0;i < val;i++) { int temp =arr[i]; arr[i] = arr[n - i - 1] == '0' ? '1' : '0'; arr[n - i - 1] = temp == '0' ? '1' : '0'; } return arr; } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5\n2\n01\n10\n5\n01011\n11100\n2\n01\n01\n10\n0110011011\n1000110100\n1\n0\n1"]
1 second
["3 1 2 1\n6 5 2 5 3 1 2\n0\n9 4 1 2 10 4 1 2 1 5\n1 1"]
NoteIn the first test case, we have $$$01\to 11\to 00\to 10$$$.In the second test case, we have $$$01011\to 00101\to 11101\to 01000\to 10100\to 00100\to 11100$$$.In the third test case, the strings are already the same. Another solution is to flip the prefix of length $$$2$$$, which will leave $$$a$$$ unchanged.
Java 11
standard input
[ "data structures", "constructive algorithms", "strings" ]
10c9b2d70030f7ed680297455d1f1bb0
The first line contains a single integer $$$t$$$ ($$$1\le t\le 1000$$$)  — the number of test cases. Next $$$3t$$$ lines contain descriptions of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 1000$$$)  — the length of the binary strings. The next two lines contain two binary strings $$$a$$$ and $$$b$$$ of length $$$n$$$. It is guaranteed that the sum of $$$n$$$ across all test cases does not exceed $$$1000$$$.
1,300
For each test case, output an integer $$$k$$$ ($$$0\le k\le 3n$$$), followed by $$$k$$$ integers $$$p_1,\ldots,p_k$$$ ($$$1\le p_i\le n$$$). Here $$$k$$$ is the number of operations you use and $$$p_i$$$ is the length of the prefix you flip in the $$$i$$$-th operation.
standard output
PASSED
30a54289997c7fa98d8ca42c2f46b90c
train_001.jsonl
1595342100
This is the easy version of the problem. The difference between the versions is the constraint on $$$n$$$ and the required number of operations. You can make hacks only if all versions of the problem are solved.There are two binary strings $$$a$$$ and $$$b$$$ of length $$$n$$$ (a binary string is a string consisting of symbols $$$0$$$ and $$$1$$$). In an operation, you select a prefix of $$$a$$$, and simultaneously invert the bits in the prefix ($$$0$$$ changes to $$$1$$$ and $$$1$$$ changes to $$$0$$$) and reverse the order of the bits in the prefix.For example, if $$$a=001011$$$ and you select the prefix of length $$$3$$$, it becomes $$$011011$$$. Then if you select the entire string, it becomes $$$001001$$$.Your task is to transform the string $$$a$$$ into $$$b$$$ in at most $$$3n$$$ operations. It can be proved that it is always possible.
256 megabytes
import java.util.*; public class Question3 { static Scanner sc = new Scanner(System.in); public static void main(String[] args) { int t = sc.nextInt(); while(t-->0) { solve(); } } public static void solve() { int n = sc.nextInt(); char[] arr = new char[n]; char[] brr = new char[n]; arr = sc.next().toCharArray(); brr = sc.next().toCharArray(); int i = n - 1; ArrayList<Integer> list = new ArrayList<Integer>(); while(i >= 0) { if(arr[i] != brr[i]) { //different.. if(i > 0 && arr[i] != arr[0]) { arr[0] = arr[i]; list.add(1); } list.add(i + 1); arr = prefixize(arr, i + 1); } i--; } System.out.print(list.size() + " "); for(int a = 0;a < list.size();a++)System.out.print(list.get(a) + " "); System.out.println(); } public static char[] prefixize(char[] arr, int n) { char[] ret = new char[arr.length]; for(int i = 0;i < n;i++) { ret[i] = arr[n - i - 1] == '1' ? '0' : '1'; } for(int i = n;i < arr.length;i++)ret[i] = arr[i]; return ret; } }
Java
["5\n2\n01\n10\n5\n01011\n11100\n2\n01\n01\n10\n0110011011\n1000110100\n1\n0\n1"]
1 second
["3 1 2 1\n6 5 2 5 3 1 2\n0\n9 4 1 2 10 4 1 2 1 5\n1 1"]
NoteIn the first test case, we have $$$01\to 11\to 00\to 10$$$.In the second test case, we have $$$01011\to 00101\to 11101\to 01000\to 10100\to 00100\to 11100$$$.In the third test case, the strings are already the same. Another solution is to flip the prefix of length $$$2$$$, which will leave $$$a$$$ unchanged.
Java 11
standard input
[ "data structures", "constructive algorithms", "strings" ]
10c9b2d70030f7ed680297455d1f1bb0
The first line contains a single integer $$$t$$$ ($$$1\le t\le 1000$$$)  — the number of test cases. Next $$$3t$$$ lines contain descriptions of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 1000$$$)  — the length of the binary strings. The next two lines contain two binary strings $$$a$$$ and $$$b$$$ of length $$$n$$$. It is guaranteed that the sum of $$$n$$$ across all test cases does not exceed $$$1000$$$.
1,300
For each test case, output an integer $$$k$$$ ($$$0\le k\le 3n$$$), followed by $$$k$$$ integers $$$p_1,\ldots,p_k$$$ ($$$1\le p_i\le n$$$). Here $$$k$$$ is the number of operations you use and $$$p_i$$$ is the length of the prefix you flip in the $$$i$$$-th operation.
standard output
PASSED
c7034e4c4a4f95c00b06367d6e9c8876
train_001.jsonl
1595342100
This is the easy version of the problem. The difference between the versions is the constraint on $$$n$$$ and the required number of operations. You can make hacks only if all versions of the problem are solved.There are two binary strings $$$a$$$ and $$$b$$$ of length $$$n$$$ (a binary string is a string consisting of symbols $$$0$$$ and $$$1$$$). In an operation, you select a prefix of $$$a$$$, and simultaneously invert the bits in the prefix ($$$0$$$ changes to $$$1$$$ and $$$1$$$ changes to $$$0$$$) and reverse the order of the bits in the prefix.For example, if $$$a=001011$$$ and you select the prefix of length $$$3$$$, it becomes $$$011011$$$. Then if you select the entire string, it becomes $$$001001$$$.Your task is to transform the string $$$a$$$ into $$$b$$$ in at most $$$3n$$$ operations. It can be proved that it is always possible.
256 megabytes
// package cp; import java.io.*; import java.math.*; import java.util.*; public class Cf_three { long gcd(long a,long b) {if(b==0)return a;else return gcd(b,a%b);} void swap(long a,long b) {long temp=a;a=b;b=temp;} StringBuilder sb=new StringBuilder(); BigInteger RES=new BigInteger("0"); // StringBuilder temp=new StringBuilder(str[i-1]); // String rev=temp.reverse().toString(); convert sb to string // if(str[i].compareTo(rev)>=0)minn=0;-compare two Strings //(Initialize as string) - (a.add(b)) - (array initialized with null and not 0) Integer[] ARR=new Integer[5]; //Integer sort-TLE-Initialize object elements i.e a[0]. void divisor(long n,int start) { int cnt=0;for(int i=start;i<=Math.sqrt(n);i++) { if(n%i==0) {if(i==n/i)cnt++;else cnt+=2;}}} public static void main(String[] args) throws IOException { PrintWriter out = new PrintWriter(System.out); Readers.init(System.in); Cf_three obj=new Cf_three(); int t=Readers.nextInt(); while(t-->0) { int n=Readers.nextInt(); String s1=Readers.next(); char[] p=new char[n]; p=s1.toCharArray(); String s2=Readers.next(); int cnt=0; char[] q=new char[n]; q=s2.toCharArray(); char[] num= {0,1}; int change=0; ArrayList<Integer> arr=new ArrayList<>(); for (int i = n-1; i >=0; i--) { if(p[i]==q[i])continue; else { // System.out.println(change+"Oh"+i); if(p[0]==p[i]) { cnt=cnt+1; arr.add(i+1); } else { cnt=cnt+2; arr.add(1); arr.add(i+1); p[0]=p[i]; } change++; char[] copy=new char[n]; copy=Arrays.copyOf(p,n); for (int j = 0; j <=i; j++) { if(copy[i-j]=='0')p[j]='1'; else p[j]='0'; } // p[0]=q[i]; } p[i]=q[i]; // p[0]=q[i]; // System.out.println(Arrays.toString(p)); } System.out.print(cnt+" "); for (int i = 0; i < arr.size(); i++) { System.out.print(arr.get(i)+" "); } System.out.println(); } out.flush(); } } class Readers { 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() ); } static long nextLong() throws IOException{ return Long.parseLong(next()); } }
Java
["5\n2\n01\n10\n5\n01011\n11100\n2\n01\n01\n10\n0110011011\n1000110100\n1\n0\n1"]
1 second
["3 1 2 1\n6 5 2 5 3 1 2\n0\n9 4 1 2 10 4 1 2 1 5\n1 1"]
NoteIn the first test case, we have $$$01\to 11\to 00\to 10$$$.In the second test case, we have $$$01011\to 00101\to 11101\to 01000\to 10100\to 00100\to 11100$$$.In the third test case, the strings are already the same. Another solution is to flip the prefix of length $$$2$$$, which will leave $$$a$$$ unchanged.
Java 11
standard input
[ "data structures", "constructive algorithms", "strings" ]
10c9b2d70030f7ed680297455d1f1bb0
The first line contains a single integer $$$t$$$ ($$$1\le t\le 1000$$$)  — the number of test cases. Next $$$3t$$$ lines contain descriptions of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 1000$$$)  — the length of the binary strings. The next two lines contain two binary strings $$$a$$$ and $$$b$$$ of length $$$n$$$. It is guaranteed that the sum of $$$n$$$ across all test cases does not exceed $$$1000$$$.
1,300
For each test case, output an integer $$$k$$$ ($$$0\le k\le 3n$$$), followed by $$$k$$$ integers $$$p_1,\ldots,p_k$$$ ($$$1\le p_i\le n$$$). Here $$$k$$$ is the number of operations you use and $$$p_i$$$ is the length of the prefix you flip in the $$$i$$$-th operation.
standard output
PASSED
0dcd470f7ae8be75c6e6af930ce5b608
train_001.jsonl
1595342100
This is the easy version of the problem. The difference between the versions is the constraint on $$$n$$$ and the required number of operations. You can make hacks only if all versions of the problem are solved.There are two binary strings $$$a$$$ and $$$b$$$ of length $$$n$$$ (a binary string is a string consisting of symbols $$$0$$$ and $$$1$$$). In an operation, you select a prefix of $$$a$$$, and simultaneously invert the bits in the prefix ($$$0$$$ changes to $$$1$$$ and $$$1$$$ changes to $$$0$$$) and reverse the order of the bits in the prefix.For example, if $$$a=001011$$$ and you select the prefix of length $$$3$$$, it becomes $$$011011$$$. Then if you select the entire string, it becomes $$$001001$$$.Your task is to transform the string $$$a$$$ into $$$b$$$ in at most $$$3n$$$ operations. It can be proved that it is always possible.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; public class Task3 { public static void main(String[] args) throws IOException { new Task3().solve(); } private void solve() throws IOException { BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int t = Integer.parseInt(f.readLine()); for (int t1 = 0; t1 < t; t1++) { int n = Integer.parseInt(f.readLine()); char[] seq1 = f.readLine().toCharArray(); char[] seq2 = f.readLine().toCharArray(); int k = 0; ArrayList<Integer> moves = new ArrayList<Integer>(); int currentFirst = 0; int currentLast = n - 1; int turns = 0; int current = 0; boolean isFirst = true; for (int i = n - 1; i >= 1; i--) { //System.out.println("oj "+ currentFirst + " " + currentLast); if (isFirst) { current = currentFirst; currentFirst++; } else { current = currentLast; currentLast--; } //System.out.println("ha " + current); if (turns % 2 == 0) { if (seq1[current] == seq2[i]) { k++; moves.add(1); } } else { if (seq1[current] != seq2[i]) { k++; moves.add(1); } } //perform(seq1, i); k++; moves.add(i + 1); turns++; isFirst = !isFirst; } //System.out.println(currentFirst + " " + currentLast); if (n % 2 == 1) { current = currentFirst; } else { current = currentLast; } //System.out.println("oj " + turns + " " + current); if (turns % 2 == 0) { if (seq1[current] != seq2[0]) { moves.add(1); k++; } } else { if (seq1[current] == seq2[0]) { moves.add(1); k++; } } out.print(k); for (int i : moves) { out.print(" "); out.print(i); } out.println(); } out.close(); } private void perform(char[] ar, int upTo) { for (int i = 0; i <= upTo; i++) { change(i, ar); } for (int i = 0; i < (upTo + 1) / 2; i++) { char temp = ar[i]; ar[i] = ar[upTo - i]; ar[upTo - i] =temp; } } private void change(int i, char[] ar) { if (ar[i] == '0') { ar[i] = '1'; } else { ar[i] = '0'; } } }
Java
["5\n2\n01\n10\n5\n01011\n11100\n2\n01\n01\n10\n0110011011\n1000110100\n1\n0\n1"]
1 second
["3 1 2 1\n6 5 2 5 3 1 2\n0\n9 4 1 2 10 4 1 2 1 5\n1 1"]
NoteIn the first test case, we have $$$01\to 11\to 00\to 10$$$.In the second test case, we have $$$01011\to 00101\to 11101\to 01000\to 10100\to 00100\to 11100$$$.In the third test case, the strings are already the same. Another solution is to flip the prefix of length $$$2$$$, which will leave $$$a$$$ unchanged.
Java 11
standard input
[ "data structures", "constructive algorithms", "strings" ]
10c9b2d70030f7ed680297455d1f1bb0
The first line contains a single integer $$$t$$$ ($$$1\le t\le 1000$$$)  — the number of test cases. Next $$$3t$$$ lines contain descriptions of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 1000$$$)  — the length of the binary strings. The next two lines contain two binary strings $$$a$$$ and $$$b$$$ of length $$$n$$$. It is guaranteed that the sum of $$$n$$$ across all test cases does not exceed $$$1000$$$.
1,300
For each test case, output an integer $$$k$$$ ($$$0\le k\le 3n$$$), followed by $$$k$$$ integers $$$p_1,\ldots,p_k$$$ ($$$1\le p_i\le n$$$). Here $$$k$$$ is the number of operations you use and $$$p_i$$$ is the length of the prefix you flip in the $$$i$$$-th operation.
standard output
PASSED
6c033de19eec24ca59b780983a91d8cb
train_001.jsonl
1595342100
This is the easy version of the problem. The difference between the versions is the constraint on $$$n$$$ and the required number of operations. You can make hacks only if all versions of the problem are solved.There are two binary strings $$$a$$$ and $$$b$$$ of length $$$n$$$ (a binary string is a string consisting of symbols $$$0$$$ and $$$1$$$). In an operation, you select a prefix of $$$a$$$, and simultaneously invert the bits in the prefix ($$$0$$$ changes to $$$1$$$ and $$$1$$$ changes to $$$0$$$) and reverse the order of the bits in the prefix.For example, if $$$a=001011$$$ and you select the prefix of length $$$3$$$, it becomes $$$011011$$$. Then if you select the entire string, it becomes $$$001001$$$.Your task is to transform the string $$$a$$$ into $$$b$$$ in at most $$$3n$$$ operations. It can be proved that it is always possible.
256 megabytes
/* ------------------------------------------------------------------- * @Name: 1382C1 Prefix Flip (Easy Version) * @Author: Yanan * @Create Time: 2020/7/22 23:40:20 (UTC+08:00) * @Url: https://codeforces.com/contest/1382/problem/C1 * @Description: ------------------------------------------------------------------- */ import java.io.*; import java.util.*; public class CF_1382C1_PrefixFlipEasyVersion { public static void main(String[] args) throws IOException { // if (System.getProperty("ONLinE_JUDGE") == null) // { // // redirect stdin/stdout to local file // System.setIn(new FileInputStream(new // File("CF_1382C1_PrefixFlipEasyVersion.in"))); // System.setOut(new PrintStream(new // File("CF_1382C1_PrefixFlipEasyVersion.out"))); // } Scanner in = new Scanner(System.in); PrintStream out = System.out; new CF_1382C1_PrefixFlipEasyVersion_Solution().Solve(in, out); in.close(); out.close(); } } class CF_1382C1_PrefixFlipEasyVersion_Solution { public void Solve(Scanner in, PrintStream out) { /* * int n = in.nextint(); // read input as integer long k = in.nextLong(); // * read input as long double d = in.nextDouble(); // read input as double String * str = in.next(); // read input as String String s = in.nextLine(); // read * whole line as String */ // out.println("OK"); int t = in.nextInt(); for (int i = 0; i < t; ++i) { int n = in.nextInt(); String a = in.next(), b = in.next(); var fans = new ArrayList<Integer>(); if (n == 1) { if (a.equals(b) == false) { out.println("1 1"); // cout<<1<<' '<<1<<'\n'; } else { out.println(0); } continue; } for (int j = 1, ss = a.length(); j < ss; ++j) { if (a.charAt(j) != a.charAt(j - 1)) { fans.add(j); } if (j == ss - 1) { if (a.charAt(j) == '1') { fans.add(j + 1); } } } var sans = new ArrayList<Integer>(); for (int j = 1, ss = b.length(); j < ss; ++j) { if (b.charAt(j) != b.charAt(j - 1)) { sans.add(j); } if (j == ss - 1) { if (b.charAt(j) == '1') { sans.add(j + 1); } } } Collections.reverse(sans); out.print(fans.size() + sans.size()); for (int j = 0; j < fans.size(); ++j) { out.print(' '); out.print(fans.get(j)); } for (int j = 0; j < sans.size(); ++j) { out.print(' '); out.print(sans.get(j)); } out.println(); } } }
Java
["5\n2\n01\n10\n5\n01011\n11100\n2\n01\n01\n10\n0110011011\n1000110100\n1\n0\n1"]
1 second
["3 1 2 1\n6 5 2 5 3 1 2\n0\n9 4 1 2 10 4 1 2 1 5\n1 1"]
NoteIn the first test case, we have $$$01\to 11\to 00\to 10$$$.In the second test case, we have $$$01011\to 00101\to 11101\to 01000\to 10100\to 00100\to 11100$$$.In the third test case, the strings are already the same. Another solution is to flip the prefix of length $$$2$$$, which will leave $$$a$$$ unchanged.
Java 11
standard input
[ "data structures", "constructive algorithms", "strings" ]
10c9b2d70030f7ed680297455d1f1bb0
The first line contains a single integer $$$t$$$ ($$$1\le t\le 1000$$$)  — the number of test cases. Next $$$3t$$$ lines contain descriptions of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 1000$$$)  — the length of the binary strings. The next two lines contain two binary strings $$$a$$$ and $$$b$$$ of length $$$n$$$. It is guaranteed that the sum of $$$n$$$ across all test cases does not exceed $$$1000$$$.
1,300
For each test case, output an integer $$$k$$$ ($$$0\le k\le 3n$$$), followed by $$$k$$$ integers $$$p_1,\ldots,p_k$$$ ($$$1\le p_i\le n$$$). Here $$$k$$$ is the number of operations you use and $$$p_i$$$ is the length of the prefix you flip in the $$$i$$$-th operation.
standard output
PASSED
b68e766f7f424fc5d110f24e8b710419
train_001.jsonl
1595342100
This is the easy version of the problem. The difference between the versions is the constraint on $$$n$$$ and the required number of operations. You can make hacks only if all versions of the problem are solved.There are two binary strings $$$a$$$ and $$$b$$$ of length $$$n$$$ (a binary string is a string consisting of symbols $$$0$$$ and $$$1$$$). In an operation, you select a prefix of $$$a$$$, and simultaneously invert the bits in the prefix ($$$0$$$ changes to $$$1$$$ and $$$1$$$ changes to $$$0$$$) and reverse the order of the bits in the prefix.For example, if $$$a=001011$$$ and you select the prefix of length $$$3$$$, it becomes $$$011011$$$. Then if you select the entire string, it becomes $$$001001$$$.Your task is to transform the string $$$a$$$ into $$$b$$$ in at most $$$3n$$$ operations. It can be proved that it is always possible.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); PrintWriter out = new PrintWriter(outputStream); C1PrefixFlipEasyVersion solver = new C1PrefixFlipEasyVersion(); solver.solve(1, in, out); out.close(); } static class C1PrefixFlipEasyVersion { public void solve(int testNumber, FastReader s, PrintWriter out) { int t = s.nextInt(); while (t-- > 0) { int n = s.nextInt(); String str1 = s.nextString(); char[] arr1 = str1.toCharArray(); String str2 = s.nextString(); char[] arr2 = str2.toCharArray(); int count = 0; ArrayList<Integer> list = new ArrayList<>(); for (int i = n - 1; i >= 0; i--) { if (arr1[i] == arr2[i]) { continue; } else { if (arr2[i] == arr1[0]) { list.add(1); count++; } list.add(i + 1); count++; for (int j = 0; j <= i; j++) { if (arr1[j] == '0') { arr1[j] = '1'; } else { arr1[j] = '0'; } } int start = 0; int end = i; while (start < end) { char temp = arr1[start]; arr1[start] = arr1[end]; arr1[end] = temp; start++; end--; } } } out.println(count + " " + C1PrefixFlipEasyVersion.arrayLists.print(list)); } } private static class arrayLists { static StringBuilder print(ArrayList<?> list) { StringBuilder ans = new StringBuilder(); for (Object curr : list) { ans.append(curr.toString() + " "); } return ans; } } } static class FastReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private FastReader.SpaceCharFilter filter; public FastReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String nextString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { res.appendCodePoint(c); } c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["5\n2\n01\n10\n5\n01011\n11100\n2\n01\n01\n10\n0110011011\n1000110100\n1\n0\n1"]
1 second
["3 1 2 1\n6 5 2 5 3 1 2\n0\n9 4 1 2 10 4 1 2 1 5\n1 1"]
NoteIn the first test case, we have $$$01\to 11\to 00\to 10$$$.In the second test case, we have $$$01011\to 00101\to 11101\to 01000\to 10100\to 00100\to 11100$$$.In the third test case, the strings are already the same. Another solution is to flip the prefix of length $$$2$$$, which will leave $$$a$$$ unchanged.
Java 11
standard input
[ "data structures", "constructive algorithms", "strings" ]
10c9b2d70030f7ed680297455d1f1bb0
The first line contains a single integer $$$t$$$ ($$$1\le t\le 1000$$$)  — the number of test cases. Next $$$3t$$$ lines contain descriptions of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 1000$$$)  — the length of the binary strings. The next two lines contain two binary strings $$$a$$$ and $$$b$$$ of length $$$n$$$. It is guaranteed that the sum of $$$n$$$ across all test cases does not exceed $$$1000$$$.
1,300
For each test case, output an integer $$$k$$$ ($$$0\le k\le 3n$$$), followed by $$$k$$$ integers $$$p_1,\ldots,p_k$$$ ($$$1\le p_i\le n$$$). Here $$$k$$$ is the number of operations you use and $$$p_i$$$ is the length of the prefix you flip in the $$$i$$$-th operation.
standard output
PASSED
ef1cb5d017fa17ad00c2f380da44a0af
train_001.jsonl
1385739000
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map.Entry; import java.util.Scanner; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.Vector; public class Solve { static int ans=0; public static void main(String[] args) throws IOException{ FastScanner sc = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int n=sc.nextInt(); int k =sc.nextInt(); int l=sc.nextInt(); int r=sc.nextInt(); int sall=sc.nextInt(); int sk=sc.nextInt(); int arr[]=new int[n+10]; Arrays.fill(arr, l); sall=sall-sk - (n-k)*l; sk-=k*l; int i=1; while(sk>0){ arr[i]++; sk--; i++; if(i==k+1) i=1; } i=k+1; while(sall>0){ arr[i]++; sall--; i++; if(i==n+1) i=k+1; } for(int i1=1;i1<=n;i1++) System.out.print(arr[i1]+" "); } } 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()); } }
Java
["5 3 1 3 13 9", "5 3 1 3 15 9"]
1 second
["2 3 2 3 3", "3 3 3 3 3"]
null
Java 8
standard input
[ "constructive algorithms", "implementation", "math" ]
59154ca15716f0c1c91a37d34c5bbf1d
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.
1,400
Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
standard output
PASSED
e1cf3eab5b16c90dd28ee558c39ad64a
train_001.jsonl
1385739000
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Solution { private final static FastReader in = new FastReader(); private static final PrintWriter out = new PrintWriter(System.out); public static void valeraAndContest(int n, int k, int l, int r, int sa, int sk) { StringBuilder sb = new StringBuilder(""); sa -= sk; for (int x = k; x > 0; x--) { sb.append(sk / x).append(" "); sk -= sk / x; } for (int x = n - k; x > 0; x--) { sb.append(sa / x).append(" "); sa -= sa / x; } out.println(sb); } public static void main(String[] args) { valeraAndContest(in.nextInt(), in.nextInt(), in.nextInt(), in.nextInt() , in.nextInt(), in.nextInt()); out.flush(); } private static final class FastReader { private static BufferedReader BF; private static StringTokenizer ST; public FastReader() { BF = new BufferedReader(new InputStreamReader(System.in)); ST = null; } public final String next() { while (ST == null || !ST.hasMoreTokens()) { try { ST = new StringTokenizer(BF.readLine()); } catch (IOException e) { e.printStackTrace(); } } return ST.nextToken(); } final int nextInt() { return Integer.parseInt(next()); } } }
Java
["5 3 1 3 13 9", "5 3 1 3 15 9"]
1 second
["2 3 2 3 3", "3 3 3 3 3"]
null
Java 8
standard input
[ "constructive algorithms", "implementation", "math" ]
59154ca15716f0c1c91a37d34c5bbf1d
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.
1,400
Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
standard output
PASSED
5188ef0c2012faa77f559bb371442e50
train_001.jsonl
1385739000
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Solution { private final static FastReader in = new FastReader(); private static final PrintWriter out = new PrintWriter(System.out); public static void valeraAndContest(int n, int k, int l, int r, int sa, int sk) { StringBuilder sb = new StringBuilder(); sa -= sk; for (int x = k; x > 0; x--) { sb.append(sk / x).append(" "); sk -= sk / x; } for (int x = n - k; x > 0; x--) { sb.append(sa / x).append(" "); sa -= sa / x; } out.println(sb); } public static void main(String[] args) { valeraAndContest(in.nextInt(), in.nextInt(), in.nextInt(), in.nextInt() , in.nextInt(), in.nextInt()); out.flush(); } private static final class FastReader { private static BufferedReader BF; private static StringTokenizer ST; public FastReader() { BF = new BufferedReader(new InputStreamReader(System.in)); ST = null; } public final String next() { while (ST == null || !ST.hasMoreTokens()) { try { ST = new StringTokenizer(BF.readLine()); } catch (IOException e) { e.printStackTrace(); } } return ST.nextToken(); } final int nextInt() { return Integer.parseInt(next()); } } }
Java
["5 3 1 3 13 9", "5 3 1 3 15 9"]
1 second
["2 3 2 3 3", "3 3 3 3 3"]
null
Java 8
standard input
[ "constructive algorithms", "implementation", "math" ]
59154ca15716f0c1c91a37d34c5bbf1d
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.
1,400
Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
standard output
PASSED
00704760332e097b6b895cacf4acd647
train_001.jsonl
1385739000
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
256 megabytes
import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; import java.util.stream.Collectors; import static java.lang.Integer.min; public class C369B { private static int n, k, l, r, sAll, sK; public static void main(String[] args) throws IOException { input(); output(); } private static int[] solve() { int[] a = new int[n]; if (n * r == sAll) { Arrays.fill(a, r); } else if (n * l == sAll) { Arrays.fill(a, l); } else { fillUp(a, 0, k, sK, r); if (n > k) fillUp(a, k, n, sAll - sK, a[k - 1]); } return a; } private static void fillUp(int[] a, int fromIndex, int toIndex, int targetSum, int cap) { int num = toIndex - fromIndex; Arrays.fill(a, fromIndex, toIndex, targetSum / num); int remaining = targetSum % num; if (remaining != 0) { int i = fromIndex; while (remaining > 0) { int increment = min(remaining, cap - a[i]); a[i] += increment; remaining -= increment; i++; } } } private static void output() { PrintWriter out = new PrintWriter(System.out); out.println(Arrays.stream(solve()).boxed().map(String::valueOf).collect(Collectors.joining(" "))); out.close(); } private static void input() { Scanner sc = new Scanner(System.in); n = sc.nextInt(); k = sc.nextInt(); l = sc.nextInt(); r = sc.nextInt(); sAll = sc.nextInt(); sK = sc.nextInt(); sc.close(); } }
Java
["5 3 1 3 13 9", "5 3 1 3 15 9"]
1 second
["2 3 2 3 3", "3 3 3 3 3"]
null
Java 8
standard input
[ "constructive algorithms", "implementation", "math" ]
59154ca15716f0c1c91a37d34c5bbf1d
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.
1,400
Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
standard output
PASSED
777e8d3e968a1172c7e9f85f87b235de
train_001.jsonl
1385739000
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
256 megabytes
import java.awt.Point; import java.io.*; import java.math.BigInteger; import java.util.*; import static java.lang.Math.*; public class Solution implements Runnable { BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); public static void main(String[] args) { new Thread(null, new Solution(), "", 256 * (1L << 20)).start(); } public void run() { try { long t1 = System.currentTimeMillis(); if (System.getProperty("ONLINE_JUDGE") != null) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } Locale.setDefault(Locale.US); solve(); in.close(); out.close(); long t2 = System.currentTimeMillis(); System.err.println("Time = " + (t2 - t1)); } catch (Throwable t) { t.printStackTrace(System.err); System.exit(-1); } } String readString() throws IOException { while (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } int sumArray (int[] arr) { int sum = 0; for(int i = 0; i < arr.length; i++) sum+=arr[i]; return sum; } int getMinOfArray(int[] arr) { int[] temp = Arrays.copyOf(arr, arr.length); Arrays.sort(temp); return temp[arr.length-1]; } // solution void solve() throws IOException { int n = readInt(); int k = readInt(); int min = readInt(); int max = readInt(); int scoreAll = readInt(); int scoreK = readInt(); int scoreRest = scoreAll - scoreK; int[] scores = new int[n]; int[] ks = new int[k]; for(int i = 0; i < k; i++) { ks[i] = max; } int x = k-1; while(sumArray(ks) > scoreK) { ks[x] --; x--; if(x < 0) x = k-1; } int minInArr = getMinOfArray(ks); int[] rs = new int[n-k]; for(int i = 0; i < rs.length; i++) rs[i] = minInArr; x = rs.length - 1; while(sumArray(rs) > scoreRest) { rs[x] --; x--; if(x < 0) x = rs.length-1; } for(int i = 0; i < k; i++) { scores[i] = ks[i]; } for(int i = 0; i < rs.length; i++) { scores[i+k] = rs[i]; } for(int i = 0; i < scores.length; i++) { out.write("" + scores[i] + " "); } } }
Java
["5 3 1 3 13 9", "5 3 1 3 15 9"]
1 second
["2 3 2 3 3", "3 3 3 3 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "math" ]
59154ca15716f0c1c91a37d34c5bbf1d
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.
1,400
Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
standard output
PASSED
bceed52bfd4a2bb61c8a25bca81c7b5c
train_001.jsonl
1385739000
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
256 megabytes
import java.util.Scanner; public class CFR2162 { public static void main (String[] args) { Scanner sc = new Scanner (System.in); int N = sc.nextInt(); int K = sc.nextInt(); int l = sc.nextInt(); int r = sc.nextInt(); int tsum = sc.nextInt(); int msum = sc.nextInt(); int[] answer = new int [N]; int emsum = msum /K; int remsum = msum % K; for (int i = 0; i < K; i++) answer[i] = emsum; for (int i = 0; i < K && remsum > 0; i++, remsum--) answer[i]++; if (N > K) { tsum -= msum; emsum = tsum / (N - K); remsum = tsum % (N - K); for (int i = K; i < N; i++) answer[i] = emsum; for (int i = K; i < N && remsum > 0; i++, remsum--) answer[i]++; } for (int i = 0; i < N; i++) System.out.print(answer[i] + " "); System.out.println(); sc.close(); } }
Java
["5 3 1 3 13 9", "5 3 1 3 15 9"]
1 second
["2 3 2 3 3", "3 3 3 3 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "math" ]
59154ca15716f0c1c91a37d34c5bbf1d
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.
1,400
Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
standard output
PASSED
989092a0a362dd344addc88620c2e181
train_001.jsonl
1385739000
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Vector; public class ValeraAndContest { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] line = br.readLine().split(" "); int n = Integer.parseInt(line[0]); int k = Integer.parseInt(line[1]); int l = Integer.parseInt(line[2]); int r = Integer.parseInt(line[3]); long sumAll = Long.parseLong(line[4]); long sumK = Long.parseLong(line[5]); perform(k, l, r, sumK); if (n > k) perform(n - k, l, r, sumAll - sumK); } private static void perform(int k, int l, int r, long sum) { // if (k <= 0 && sum <= 0) // return r; // long numbers = sum / r; // while (--numbers >= 0) // System.out.print(r + " "); // // if (sum % r != 0) { // sum -= ((sum / r) * r); // k -= (sum / r); // r--; // perform(k, l, r, sum); // } // return r; long remainder = sum % k; long result = 0; for (int i = 0; i < k; i++) { result = remainder > 0 ? (sum / k) + 1 : (sum / k); remainder--; System.out.print(result + " "); } } }
Java
["5 3 1 3 13 9", "5 3 1 3 15 9"]
1 second
["2 3 2 3 3", "3 3 3 3 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "math" ]
59154ca15716f0c1c91a37d34c5bbf1d
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.
1,400
Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
standard output
PASSED
7ebc1fa2ecf42d0e04f82a1af4e5537d
train_001.jsonl
1385739000
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; public class T369B { public void solve(int n, int k, int l, int r, int sall, int sk) { int m = n - k; int sno = sall - sk; ArrayList<Integer> ans = new ArrayList<Integer>(); if (k > 0) { if (sk % k == 0) { for (int i = 0; i < k; i ++) { ans.add(sk / k); } } else { int x = sk / k; int y = x * k; int z = sk - y; for (int i = 0; i < k; i ++) { if (z > 0) { ans.add(x + 1); z --; } else { ans.add(x); } } } } if (m > 0) { if (sno % m == 0) { for (int i = 0; i < m; i ++) { ans.add(sno / m); } } else { int x = sno / m; int y = x * m; int z = sno - y; for (int i = 0; i < m; i ++) { if (z > 0) { ans.add(x + 1); z --; } else { ans.add(x); } } } } StringBuffer s = new StringBuffer(); for (int i : ans) s.append(i + " "); System.out.println(s.toString().trim()); } public static void main(String[] args) { FastScanner in = new FastScanner(); new T369B().solve(in.nextInt(), in.nextInt(), in.nextInt(), in.nextInt(), in.nextInt(), in.nextInt()); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["5 3 1 3 13 9", "5 3 1 3 15 9"]
1 second
["2 3 2 3 3", "3 3 3 3 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "math" ]
59154ca15716f0c1c91a37d34c5bbf1d
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.
1,400
Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
standard output
PASSED
8c36701901bdfdb7056a1c91ff81e65b
train_001.jsonl
1385739000
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
256 megabytes
import java.io.*; import java.util.*; public class program { public static ArrayList<Integer> getPeople(int n, int min, int max, int sum) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = min; } int s = min * n; int i = 0; while (s != sum) { arr[i]++; s += 1; i = (i + 1) % n; } ArrayList<Integer> res = new ArrayList<Integer>(); for (i = 0; i < n; i++) { res.add(arr[i]); } return res; } public static void main(String args[]) { BufferedReader reader = new BufferedReader(new InputStreamReader( System.in)); Scanner scanner = new Scanner(reader); int n = scanner.nextInt(); int k = scanner.nextInt(); int l = scanner.nextInt(); int r = scanner.nextInt(); int sall = scanner.nextInt(); int sk = scanner.nextInt(); int lsum = sk; int rsum = sall - sk; ArrayList<Integer> p1 = getPeople(k, l, r, lsum); ArrayList<Integer> p2 = getPeople(n - k, l, r, rsum); p1.addAll(p2); for (int x : p1) { System.out.print(x + " "); } System.out.println(); } }
Java
["5 3 1 3 13 9", "5 3 1 3 15 9"]
1 second
["2 3 2 3 3", "3 3 3 3 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "math" ]
59154ca15716f0c1c91a37d34c5bbf1d
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.
1,400
Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
standard output
PASSED
09f3b022bdc8399ade70c96048f3d1ff
train_001.jsonl
1385739000
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.StringTokenizer; public class C216P2 { private static BufferedReader in; private static PrintWriter out; private static StringTokenizer input; public static void main(String[] args) throws IOException { //------------------------------------------------------------------------- //Initializing... new C216P2(); //------------------------------------------------------------------------- //put your code here... :) int n = nextInt(); int k = nextInt(); int l = nextInt(); int r = nextInt(); int sall = nextInt(); int sk = nextInt(); int [] scors = new int[n]; if(k!=n){ int diff = sall - sk; int less = scors.length - k; int leftover = diff%less; for (int i = k; i < scors.length; i++) { scors[i] = diff/less; if(leftover!=0){ scors[i]++; leftover--; } } } int leftover = sk%k; for (int i = 0; i < k; i++) { scors[i] = sk/k; if(leftover!=0){ scors[i]++; leftover--; } } write(""+scors[0]); for (int i = 1; i < scors.length; i++) { write(" "+scors[i]); } writeln(""); //------------------------------------------------------------------------- //closing up end(); //-------------------------------------------------------------------------- } public C216P2() throws IOException { //Input Output for Console to be used for trying the test samples of the problem in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); //------------------------------------------------------------------------- //Initalize Stringtokenizer input input = new StringTokenizer(in.readLine()); } private static int nextInt() throws IOException { if (!input.hasMoreTokens())input=new StringTokenizer(in.readLine()); return Integer.parseInt(input.nextToken()); } private static long nextLong() throws IOException { if (!input.hasMoreTokens())input=new StringTokenizer(in.readLine()); return Long.parseLong(input.nextToken()); } private static double nextDouble() throws IOException { if (!input.hasMoreTokens())input=new StringTokenizer(in.readLine()); return Double.parseDouble(input.nextToken()); } private static String nextString() throws IOException { if (!input.hasMoreTokens())input=new StringTokenizer(in.readLine()); return input.nextToken(); } private static void write(String output){ out.write(output); // out.flush(); } private static void writeln(String output){ out.write(output+"\n"); // out.flush(); } private static void end() throws IOException{ in.close(); out.flush(); out.close(); System.exit(0); } }
Java
["5 3 1 3 13 9", "5 3 1 3 15 9"]
1 second
["2 3 2 3 3", "3 3 3 3 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "math" ]
59154ca15716f0c1c91a37d34c5bbf1d
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.
1,400
Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
standard output
PASSED
3c38984fa9d2c238b5130f642ba07710
train_001.jsonl
1385739000
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner leer = new Scanner(System.in); int n, k, l, r, sall, sk; n = leer.nextInt(); k = leer.nextInt(); l = leer.nextInt(); r = leer.nextInt(); sall = leer.nextInt(); sk = leer.nextInt(); int a[] = new int[n]; int i = 0; for (i = 0; i < k; i++) { int num = sk / k; if (i < sk % k) num++; a[i] = num; } n -= k; sall -= sk; int j = 0; for (i = i; i < n + k; i++) { int num = sall / n; if (j < sall % n) num++; a[i] = num; j++; } for (int j2 = 0; j2 < a.length; j2++) { System.out.print(a[j2]+" "); } } }
Java
["5 3 1 3 13 9", "5 3 1 3 15 9"]
1 second
["2 3 2 3 3", "3 3 3 3 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "math" ]
59154ca15716f0c1c91a37d34c5bbf1d
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.
1,400
Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
standard output
PASSED
f117bccc1803b18207064ee429a44196
train_001.jsonl
1385739000
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
256 megabytes
import java.util.*; public class ValeraB { public static void main(String a[]) { Scanner in = new Scanner(System.in); int n = in.nextInt(), k = in.nextInt(), l = in.nextInt(), r = in.nextInt(), sAll = in.nextInt(), sK = in.nextInt(); int[] s = new int[n]; int avgK = sK / k; Arrays.fill(s, 0, k, avgK); int multK = avgK * k; for(int i = 0; i < k; ++i) { if(multK == sK) break; s[i]++; multK++; } if(n != k) { sAll -= sK; int avgAll = sAll / (n - k); Arrays.fill(s, k, n, avgAll); int multAll = avgAll * (n - k); for(int i = k; i < n; ++i) { if(multAll == sAll) break; s[i]++; multAll++; } } for(int i = 0; i < n; ++i) System.out.print(s[i]+" "); } }
Java
["5 3 1 3 13 9", "5 3 1 3 15 9"]
1 second
["2 3 2 3 3", "3 3 3 3 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "math" ]
59154ca15716f0c1c91a37d34c5bbf1d
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.
1,400
Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
standard output
PASSED
e4851bf1ea8e51af67657178a130ba98
train_001.jsonl
1385739000
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
256 megabytes
import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import java.io.*; import java.math.*; import java.text.*; import java.util.*; /* br = new BufferedReader(new FileReader("input.txt")); pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt"))); br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); */ public class Main { private static BufferedReader br; private static StringTokenizer st; private static PrintWriter pw; static int[] dp; static int[] list; static int[] prefix; static String str; public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); //int qq = 1; int qq = Integer.MAX_VALUE; //int qq = readInt(); for(int casenum = 1; casenum <= qq; casenum++) { int n = readInt(); int k = readInt(); int l = readInt(); int r = readInt(); int total = readInt(); int most = readInt(); int[] ret = new int[n]; Arrays.fill(ret, total/n); int temp = (total/n)*n; for(int i = 0; i < n && temp < total; i++) { ret[i]++; temp++; } for(int i = 0; i < k; i++) { most -= ret[i]; } int left = 0; int right = n-1; while(most-- > 0) { while(ret[left] == r) left++; while(ret[right] == l) right--; ret[left]++; ret[right]--; } StringBuilder sb = new StringBuilder(); for(int out: ret) { sb.append(out + " "); } pw.println(sb.toString().trim()); } pw.close(); } public static int solve(int n) { if(n < 0) return 0; if(str.charAt(n) == '0') { dp[n] = solve(n-1); return dp[n]; } dp[n] = Math.max(prefix[n], list[n] + solve(n-1)); return dp[n]; } private static void exitImmediately() { pw.close(); System.exit(0); } private static long readLong() throws IOException { return Long.parseLong(nextToken()); } private static double readDouble() throws IOException { return Double.parseDouble(nextToken()); } private static int readInt() throws IOException { return Integer.parseInt(nextToken()); } private static String nextToken() throws IOException { while(st == null || !st.hasMoreTokens()) { if(!br.ready()) { exitImmediately(); } st = new StringTokenizer(br.readLine().trim()); } return st.nextToken(); } }
Java
["5 3 1 3 13 9", "5 3 1 3 15 9"]
1 second
["2 3 2 3 3", "3 3 3 3 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "math" ]
59154ca15716f0c1c91a37d34c5bbf1d
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.
1,400
Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
standard output
PASSED
cc0d882b504039dc1a40655eebcb8893
train_001.jsonl
1385739000
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
256 megabytes
import java.util.Scanner; public class Competitions { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int k = scan.nextInt(); int low = scan.nextInt(); int high = scan.nextInt(); int sn = scan.nextInt(); int sk = scan.nextInt(); int[] score = new int[n]; for(int i=0; i<n; i++) { score[i] = low; } int howmany = sk - (sk/k) * k; for(int i=0; i<howmany; i++) { score[i] = sk/k + 1; } for(int i=howmany; i<k; i++) { score[i] = sk/k; } int x = (sk/k) - low; int y = n-k; int nowsum = low*y; int tochangex = sn - sk - nowsum; int tochange; if(x != 0) tochange = tochangex / x; else tochange = 0; if(x != 0) { for(int i=k; i< k + tochange; i++) { score[i] = sk/k; } for(int i= k + tochange + 1; i<n; i++) { score[i] = low; } if(k+tochange < n){ score[k + tochange] = low + tochangex - x*(tochangex/x);} } else { for(int i=k; i<n; i++) { score[i] = low; } } for(int asd = 0; asd<n; asd++) System.out.print(score[asd] + " "); } }
Java
["5 3 1 3 13 9", "5 3 1 3 15 9"]
1 second
["2 3 2 3 3", "3 3 3 3 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "math" ]
59154ca15716f0c1c91a37d34c5bbf1d
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.
1,400
Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
standard output
PASSED
c81699c570fae6212a6c32e69a411e13
train_001.jsonl
1385739000
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
256 megabytes
import java.util.*; import java.io.*; public class Main{ BufferedReader in; StringTokenizer str = null; PrintWriter out; private String next() throws Exception{ if (str == null || !str.hasMoreElements()) str = new StringTokenizer(in.readLine()); return str.nextToken(); } private int nextInt() throws Exception{ return Integer.parseInt(next()); } public void run() throws Exception{ in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); int n = nextInt(), k = nextInt(), l = nextInt(), r = nextInt(); int sn = nextInt(), sk = nextInt(); int a[] = new int[n]; for(int i=0;i<k;i++){ a[i] = sk/k; } for(int i=0;i<sk%k;i++){ a[i]++; } if (n != k){ for(int i=k;i<n;i++){ a[i] = (sn-sk)/(n-k); } for(int i=k,j=0;j<(sn-sk)%(n-k);i++,j++){ a[i]++; } } for(int i=0;i<n;i++){ out.print(a[i] + " "); } out.println(); out.close(); } public static void main(String args[]) throws Exception{ new Main().run(); } }
Java
["5 3 1 3 13 9", "5 3 1 3 15 9"]
1 second
["2 3 2 3 3", "3 3 3 3 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "math" ]
59154ca15716f0c1c91a37d34c5bbf1d
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.
1,400
Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
standard output
PASSED
eec05116bdff65055b0333af7c857fb4
train_001.jsonl
1385739000
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
256 megabytes
import java.util.Scanner; public class p2_216 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int k = in.nextInt(); int l = in.nextInt(); int r = in.nextInt(); int Sall = in.nextInt(); int sk = in.nextInt(); int num = sk / k; int[] array = new int[n]; for (int i = 0; i <k; i++) array[i] = r; for (int i = k; i <n; i++) array[i] = l; int sum = r * k; while (sum > sk) { for (int i = k - 1; i >= 0; i--) { array[i]--; sum--; if (sum == sk) break; } } sum=l*(n-k); while (sum < Sall-sk) { for (int i = k; i <n; i++) { array[i]++; sum++; if (sum == Sall-sk) break; } } for (int i = 0; i < array.length-1; i++) { System.out.print(array[i]+" "); } System.out.println(array[array.length-1]); } }
Java
["5 3 1 3 13 9", "5 3 1 3 15 9"]
1 second
["2 3 2 3 3", "3 3 3 3 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "math" ]
59154ca15716f0c1c91a37d34c5bbf1d
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.
1,400
Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
standard output
PASSED
45b6e62f2bb4dc623b6af1a368600029
train_001.jsonl
1385739000
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class B { BufferedReader reader; StringTokenizer tokenizer; PrintWriter out; public void solve() throws IOException { int N = nextInt(); int K = nextInt(); int L = nextInt(); int R = nextInt(); int SALL = nextInt(); int SK = nextInt(); int[] ans = new int[N]; for (int i = 0; i < SK % K; i++) { ans[i] = SK/K + 1; } for (int i = SK % K; i < K; i++) { ans[i] = SK/K; } if(N > K) { int remainS = SALL - SK; int remain = N - K; for (int i = K; i < K + remainS % remain; i++) { ans[i] = remainS/remain + 1; } for (int i = K + remainS % remain; i < N; i++) { ans[i] = remainS/remain; } } int sum = 0; for (int i = 0; i < N; i++) { out.print(ans[i] + " "); sum += ans[i]; } if (sum != SALL){ throw new RuntimeException(); } out.println(); } /** * @param args */ public static void main(String[] args) { new B().run(); } public void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; out = new PrintWriter(System.out); solve(); reader.close(); out.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()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }
Java
["5 3 1 3 13 9", "5 3 1 3 15 9"]
1 second
["2 3 2 3 3", "3 3 3 3 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "math" ]
59154ca15716f0c1c91a37d34c5bbf1d
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.
1,400
Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
standard output
PASSED
7c2627a6a22450055eafa962c5e708db
train_001.jsonl
1385739000
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
256 megabytes
/** * Created by yuantian on 12/5/13. */ import java.util.*; public class ValeraAndContest369B { static public void main(String[] args) { Scanner in = new Scanner(System.in); int n, k, l, r, sa, sk; n = in.nextInt(); k = in.nextInt(); l = in.nextInt(); r = in.nextInt(); sa = in.nextInt(); sk = in.nextInt(); int avg = sk / k; int rem = sk % k; for (int i = 0; i < k; i++) { if (i < rem) System.out.println((avg + 1)); else System.out.println(avg); } if (k < n) { avg = (sa - sk) / (n - k); rem = (sa - sk) % (n - k); for (int i = k; i < n; i++) { if (i < k+rem) System.out.println((avg + 1)); else System.out.println(avg); } } } }
Java
["5 3 1 3 13 9", "5 3 1 3 15 9"]
1 second
["2 3 2 3 3", "3 3 3 3 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "math" ]
59154ca15716f0c1c91a37d34c5bbf1d
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.
1,400
Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
standard output
PASSED
257c9bdc34cff549d5281204cb0e7a38
train_001.jsonl
1385739000
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
256 megabytes
/** * Created by yuantian on 12/5/13. */ import java.util.*; public class ValeraAndContest369B { static public void main(String[] args) { Scanner in = new Scanner(System.in); int n, k, l, r, sa, sk, sk1; n = in.nextInt(); k = in.nextInt(); l = in.nextInt(); r = in.nextInt(); sa = in.nextInt(); sk = in.nextInt(); sk1 = sa - sk; int[] out = new int[n]; int avg = sk / k; int rem = sk % k; for (int i = 0; i < n; i++) { if (i < rem) out[i] = avg + 1; else out[i] = avg; } if (k < n) { avg = sk1 / (n - k); rem = sk1 % (n - k); for (int i = k; i < n; i++) { if (i < k+rem) out[i] = avg + 1; else out[i] = avg; } } for (int i : out) System.out.println(i + " "); } }
Java
["5 3 1 3 13 9", "5 3 1 3 15 9"]
1 second
["2 3 2 3 3", "3 3 3 3 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "math" ]
59154ca15716f0c1c91a37d34c5bbf1d
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.
1,400
Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
standard output
PASSED
36d6b226a0540a346f0bd2bd94d44dba
train_001.jsonl
1385739000
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class B216 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int k = in.nextInt(); int l = in.nextInt(); int r = in.nextInt(); int sa = in.nextInt(); int sk = in.nextInt(); r -= l; int[] a = new int[n]; for (int i = 0; i < a.length; i++) a[i] = l; sa -= l * n; sk -= l * k; for (int i = 0; i < k; i++) { int temp = Math.min(r, (int)Math.ceil(sk / (double)(k - i))); a[i] += temp; sk -= temp; sa -= temp; } for (int i = k; i < n; i++) { int temp = Math.min(r, (int)Math.ceil(sa / (double)(n - i))); a[i] += temp; sa -= temp; } for (int i = 0; i < n; i++) System.out.print(a[i] + " "); } }
Java
["5 3 1 3 13 9", "5 3 1 3 15 9"]
1 second
["2 3 2 3 3", "3 3 3 3 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "math" ]
59154ca15716f0c1c91a37d34c5bbf1d
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.
1,400
Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
standard output
PASSED
719dcacd95efe4eab4d09852adb07df1
train_001.jsonl
1385739000
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
256 megabytes
import java.io.*; import java.util.*; public class B implements Runnable { private void solve() throws IOException { int n = nextInt(), k = nextInt(), l = nextInt(), r = nextInt(), sall = nextInt(), sk = nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] += l; sall -= l; } int need = sk - l * k; while (need > 0) { for (int i = 0; i < k; i++) { a[i]++; sall--; need--; if (need == 0) break; } } while (sall > 0) { for (int i = k; i < n; i++) { a[i]++; sall--; if (sall == 0) break; } } for (int i = 0; i < n; i++) { if (i != 0) print(' '); print(a[i]); } } public static void main(String[] args) { new B().run(); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; public void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); writer = new PrintWriter(System.out); solve(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(261); } } void halt() { writer.close(); System.exit(0); } void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } void println(Object... objects) { print(objects); writer.println(); } String nextLine() throws IOException { return reader.readLine(); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(nextLine()); return tokenizer.nextToken(); } 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()); } }
Java
["5 3 1 3 13 9", "5 3 1 3 15 9"]
1 second
["2 3 2 3 3", "3 3 3 3 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "math" ]
59154ca15716f0c1c91a37d34c5bbf1d
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.
1,400
Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
standard output
PASSED
340b8d4d550084c193d35370729db669
train_001.jsonl
1385739000
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
256 megabytes
import java.util.ArrayList; import java.util.Scanner; public class B { public static void main(String args[]) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int k = s.nextInt(); int l = s.nextInt(); int r = s.nextInt(); int sum = s.nextInt(); int sumk = s.nextInt(); int eachInK = sumk / k; int numPlus1InK = sumk - k * eachInK; int eachInRem = 0; int numPlus1Rem = 0; if (n != k) { eachInRem = (sum - sumk) / (n - k); numPlus1Rem = (sum - sumk) - (n - k) * eachInRem; } int r1 = numPlus1InK; int r2 = k - numPlus1InK; int r3 = numPlus1Rem; int r4 = n - k - numPlus1Rem; int a[] = new int[n]; int curr = 0; for (int i = 0; i < r1; i++) a[curr++] = eachInK + 1; for (int i = 0; i < r2; i++) a[curr++] = eachInK; for (int i = 0; i < r3; i++) a[curr++] = eachInRem + 1; for (int i = 0; i < r4; i++) a[curr++] = eachInRem; System.out.print(a[0]); for (int i = 1; i < n; i++) System.out.print(" " + a[i]); System.out.println(""); } }
Java
["5 3 1 3 13 9", "5 3 1 3 15 9"]
1 second
["2 3 2 3 3", "3 3 3 3 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "math" ]
59154ca15716f0c1c91a37d34c5bbf1d
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.
1,400
Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
standard output
PASSED
8012b216303f194aff99a5018f993b08
train_001.jsonl
1385739000
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
256 megabytes
import java.util.Scanner; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author smith */ public class B { public static void main(String Args[]) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); int l = sc.nextInt(); int r = sc.nextInt(); int sa = sc.nextInt(); int sk = sc.nextInt(); sa -= sk; sa-=((n-k)*l); sk -= (k * l); int ns[] = new int[n]; if (sk / k <= (r - l)) { int ds = sk / k; sk -= (k * ds); for (int i = 0; i < k; i++) { ns[i] = ds; } } for (int i = 0; i < k; i++) { if (l + ns[i] < r && sk > 0) { int d = Math.min(r - (l + ns[i]), sk); sk -= d; ns[i] += d; } } k--; for (int i = k+1; i < n; i++) { if (ns[i] < ns[k] && sa > 0) { int d = Math.min(ns[k] -ns[i], sa); sa -= d; ns[i] += d; } } System.out.print(ns[0]+l); for(int i=1;i<n;i++){ System.out.print(" "+(ns[i]+l)); } System.out.println(""); } }
Java
["5 3 1 3 13 9", "5 3 1 3 15 9"]
1 second
["2 3 2 3 3", "3 3 3 3 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "math" ]
59154ca15716f0c1c91a37d34c5bbf1d
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.
1,400
Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
standard output
PASSED
6fbcef9b551b472c4a42c0cf4da0795d
train_001.jsonl
1385739000
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
256 megabytes
import java.util.*; public class Contest { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n, k, l, r, sall, sk; n = in.nextInt(); k = in.nextInt(); l = in.nextInt(); r = in.nextInt(); sall = in.nextInt(); sk = in.nextInt(); int[] arr = new int[n]; for(int i = 0; i < k; i++) { arr[i] = r; } int sum = r * k; while(sum > sk) { arr[sum % k]--; sum--; } for(int i = k; i < n; i++) { arr[i] = l; } sum += l * (n - k); while(sum < sall) { arr[sum % (n-k) + k]++; sum++; } for(int i: arr) System.out.print(i + " "); } }
Java
["5 3 1 3 13 9", "5 3 1 3 15 9"]
1 second
["2 3 2 3 3", "3 3 3 3 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "math" ]
59154ca15716f0c1c91a37d34c5bbf1d
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.
1,400
Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
standard output
PASSED
b64fe64d1f7280aa3cc98c50fd78875a
train_001.jsonl
1385739000
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
256 megabytes
import java.io.FileNotFoundException; import java.util.Scanner; public class Main { public static void main(String[] args) throws FileNotFoundException { Scanner sc = new Scanner(System.in); //Scanner sc = new Scanner(new File("input.txt")); // n, k, l, r, sall, sk int n = sc.nextInt(); int k = sc.nextInt(); int l = sc.nextInt(); int r = sc.nextInt(); int sall = sc.nextInt(); int sk = sc.nextInt(); // minimo su tuttu int[] res = new int[n]; for (int i = 0; i < n; i++) { res[i] = l; sall -= l; if (i >= n - k) { sk -= l; } } // il resto ovvero i primi int srest = sall - sk; int rest = n - k; if (rest != 0) { int toAddRest = srest / rest; int toAddLastRest = srest % rest; for (int i = 0; i < rest; i++) { res[i] += toAddRest; if (i >= rest - toAddLastRest) { res[i]++; } } for (int i = n - k; i < n; i++) { int diff = res[rest - 1] - res[i]; res[i] += diff; sk -= diff; } } for (int i = n - 1; i >= n - k && sk > 0; i--) { int max = Math.min(res[i] + sk, r); int diff = max - res[i]; res[i] += diff; sk -= diff; } for (int i : res) { System.out.print(i + " "); } } }
Java
["5 3 1 3 13 9", "5 3 1 3 15 9"]
1 second
["2 3 2 3 3", "3 3 3 3 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "math" ]
59154ca15716f0c1c91a37d34c5bbf1d
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.
1,400
Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
standard output
PASSED
46a36d0c245c396010743202b70f1451
train_001.jsonl
1385739000
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; /** * Created by 875k on 12/23/13. */ public class CF216B { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer tok = new StringTokenizer(br.readLine()); int n = Integer.parseInt(tok.nextToken()); int k = Integer.parseInt(tok.nextToken()); int l = Integer.parseInt(tok.nextToken()); int r = Integer.parseInt(tok.nextToken()); int sall = Integer.parseInt(tok.nextToken()); int sk = Integer.parseInt(tok.nextToken()); int s = sk / k; int m = sk % k; for(int i = 0; i < k; i++) { System.out.print(s + (m-- > 0 ? 1 : 0) + " "); } if(k < n) { s = (sall - sk) / (n - k); m = (sall - sk) % (n - k); for(int i = 0; i < (n - k); i++) { System.out.print(s + (m-- > 0 ? 1 : 0) + " "); } } System.out.println(); } }
Java
["5 3 1 3 13 9", "5 3 1 3 15 9"]
1 second
["2 3 2 3 3", "3 3 3 3 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "math" ]
59154ca15716f0c1c91a37d34c5bbf1d
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.
1,400
Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
standard output
PASSED
177cdafe6d53dbb6e5e4c6135df7f6da
train_001.jsonl
1385739000
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
256 megabytes
import java.util.*; import java.awt.geom.*; import java.io.*; public class Main{ private void doit(){ Scanner sc = new Scanner(System.in); while(sc.hasNext()){ int n = sc.nextInt(); int k = sc.nextInt(); int l = sc.nextInt(); int r = sc.nextInt(); int sa = sc.nextInt(); int sk = sc.nextInt(); int snk = sa - sk; int [] ans = new int[n]; for(int i = 0; i < k; i++){ ans[i] = sk / k; if(sk % k > i){ ans[i]++; } } int nk = n - k; for(int i = k; i < n; i++){ ans[i] = snk / nk; if(snk % nk > i - k){ ans[i]++; } } for(int i = 0; i< n - 1; i++){ System.out.print(ans[i] + " "); } System.out.println(ans[n-1]); } } private void debug(Object... o) { System.out.println("debug = " + Arrays.deepToString(o)); } public static void main(String[] args) { new Main().doit(); } }
Java
["5 3 1 3 13 9", "5 3 1 3 15 9"]
1 second
["2 3 2 3 3", "3 3 3 3 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "math" ]
59154ca15716f0c1c91a37d34c5bbf1d
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.
1,400
Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
standard output
PASSED
9a2c62588b0ac107acde4a7cf1916d89
train_001.jsonl
1385739000
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
256 megabytes
import java.util.*; import java.io.*; public class prog{ public static int tot=0,k=0,l = 0,r=0,sa=0,sk=0; public static boolean llegue = false; public static void hagale(int a,Vector<Integer> b,int sum){ if(llegue)return; if(a==tot && sum==sa){ llegue=true; StringBuilder sb = new StringBuilder(""); for(int n = 0;n<b.size();n++) sb.append(b.get(n)+((n==b.size()-1)?"":" ")); System.out.println(sb); return; } if(a==k-1){ if(sk>sum+r || sum+l>sk)return; Vector<Integer> bb = new Vector<Integer>(); bb.addAll(b); bb.add(sk-sum); hagale(a+1,bb,sk); } int p = r; if(a<=k)p = (int)Math.ceil(sk/(double)k); for(int n = r;n>l-1;n--){ if(sum+n>sa)continue; if(a<k-1 && (sk-(sum+n)>r*(k-a-1) || sk-(sum+n)<l*(k-a-1)))continue; if(sa-(sum+n)>r*(tot-a-1) || sa-(sum+n)<l*(tot-a-1))continue; Vector<Integer> bb = new Vector<Integer>(); bb.addAll(b); bb.add(n); hagale(a+1,bb,sum+n); } } public static void main(String args[]) throws IOException{ BufferedReader lector = new BufferedReader(new InputStreamReader(System.in)); String tmp[] =lector.readLine().split(" "); tot=Integer.parseInt(tmp[0]); k=Integer.parseInt(tmp[1]); l=Integer.parseInt(tmp[2]); r=Integer.parseInt(tmp[3]); sa=Integer.parseInt(tmp[4]); sk=Integer.parseInt(tmp[5]); //hagale(0,new Vector<Integer>(),0); int p = sk/k; int pp = sk-k*p; int tal[] = new int[k]; int tal2[] = new int[tot-k]; Arrays.fill(tal,p); for(int n =0;n<tal.length;n++){ if(tal[n]<l && pp>l-tal[n]){ tal[n]=l; pp-=(l-tal[n]); } } int i = 0; while(pp>0){ if(tal[i]<r){ tal[i]++; pp--; } i = (i+1)%tal.length; } if(tot>k){ p = (sa-sk)/(tot-k); pp = (sa-sk)-p*(tot-k); Arrays.fill(tal2,p); for(int n =0;n<tal2.length;n++){ if(tal2[n]<l && pp>l-tal2[n]){ tal2[n]=l; pp-=(l-tal2[n]); } } i=0; while(pp>0){ if(tal2[i]<r){ tal2[i]++; pp--; } i=(i+1)%tal2.length; } } for(int n = 0;n<tot;n++) if(n<tal.length) System.out.print(tal[n]+(n==tot-1?"":" ")); else System.out.print(tal2[n-tal.length]+(n==tot-1?"":" ")); System.out.println(); } }
Java
["5 3 1 3 13 9", "5 3 1 3 15 9"]
1 second
["2 3 2 3 3", "3 3 3 3 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "math" ]
59154ca15716f0c1c91a37d34c5bbf1d
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.
1,400
Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
standard output
PASSED
00b4223b027c3e81686abc8ae26d92d0
train_001.jsonl
1385739000
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
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.Scanner; public class B216 { public void solve() throws IOException { Scanner sc = new Scanner(System.in); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); int ans = 0, sum = 0, count = 0; int n = sc.nextInt(); int k = sc.nextInt(); int l = sc.nextInt(); int r = sc.nextInt(); int Sall = sc.nextInt(); int Sk = sc.nextInt(); int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = l; } sum = l * k; // printAr(a); // System.out.println(sum); if (sum < Sk) { int temp1 = (Sk - sum) / k; int temp2 = (Sk - sum) % k; // System.out.println(temp1 + " " + temp2); for (int i = 0; i < k; i++) { a[i] += temp1; } for (int i = 0; i < temp2; i++) { a[i]++; } } // printAr(a); int rest = Sall - Sk; int agasum = l * (n - k); rest -= agasum; //System.out.println("aga " + agasum); if (rest > 0) { int temp3 = rest / (n - k); int temp4 = rest % (n - k); //System.out.println(temp3 + " " + temp4); for (int i = k; i < n; i++) { a[i] += temp3; } // printAr(a); for (int i = k; i < k + temp4; i++) { a[i]++; } } printAr(a); } public static void printAr(int a[]) { for (int i = 0; i < a.length; i++) { System.out.print(a[i] + " "); } // System.out.println(""); } public static void main(String[] args) throws IOException { new B216().solve(); } }
Java
["5 3 1 3 13 9", "5 3 1 3 15 9"]
1 second
["2 3 2 3 3", "3 3 3 3 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "math" ]
59154ca15716f0c1c91a37d34c5bbf1d
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.
1,400
Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
standard output
PASSED
2ee697f968977abeb9fae10865cf1ca6
train_001.jsonl
1385739000
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
256 megabytes
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class R216B { static InputStream is; static PrintWriter out; static String INPUT = ""; public static int func(int[] a) { return 0; } static void solve() { int n=ni(); int k=ni(); int l=ni(); int r=ni(); int sall=ni(); int sk=ni(); int[] a=new int[n]; int d=sk-((sk/k)*k); int i; for(i=n-k;d>0; d--,i++){ a[i]=(sk/k)+1; } for(;i<n; i++){ a[i]=(sk/k); } if(n>k){ d=(sall-sk)-(((sall-sk)/(n-k))*(n-k)); for(i=0; d>0; d--, i++){ a[i]=(sall-sk)/(n-k)+1; } for(;i<n-k; i++){ a[i]=(sall-sk)/(n-k); } } for(i=0; i<n; i++){ out.print(a[i]+" "); } } public static void main(String[] args) throws Exception { long S = System.currentTimeMillis(); is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream( INPUT.getBytes()); out = new PrintWriter(System.out); solve(); out.flush(); long G = System.currentTimeMillis(); tr(G - S + "ms"); } private static boolean eof() { if (lenbuf == -1) return true; int lptr = ptrbuf; while (lptr < lenbuf) if (!isSpaceChar(inbuf[lptr++])) return false; try { is.mark(1000); while (true) { int b = is.read(); if (b == -1) { is.reset(); return true; } else if (!isSpaceChar(b)) { is.reset(); return false; } } } catch (IOException e) { return true; } } private static byte[] inbuf = new byte[1024]; static int lenbuf = 0, ptrbuf = 0; private static int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private static int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } private static double nd() { return Double.parseDouble(ns()); } private static char nc() { return (char) skip(); } private static String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != // ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private static char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private static char[][] nm(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = ns(m); return map; } private static int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } private static int ni() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private static long nl() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private static void tr(Object... o) { if (INPUT.length() != 0) System.out.println(Arrays.deepToString(o)); } }
Java
["5 3 1 3 13 9", "5 3 1 3 15 9"]
1 second
["2 3 2 3 3", "3 3 3 3 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "math" ]
59154ca15716f0c1c91a37d34c5bbf1d
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.
1,400
Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
standard output
PASSED
4867249954777cd4063cbe591d13c498
train_001.jsonl
1385739000
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
256 megabytes
import java.io.*; import java.util.*; public class B216 { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String[] inputStr = in.readLine().split(" "); int[] a = new int[6]; for (int i = 0; i < 6; i++) a[i] = pi(inputStr[i]); int n = a[0]; int k = a[1]; int l = a[2]; int r = a[3]; int sa = a[4]; int sk = a[5]; int mid = sk/k; int x, y; y = sk - mid*k; x = k - y; int b = n - k; int pre = sa - sk; int z, w; StringBuilder ans = new StringBuilder(); if (b != 0) { int midk = pre/b; z = pre - midk*b; w = b - z; for (int i = 0; i < w; i++) { if (i != 0) ans.append(" "); ans.append(midk); } for (int i = w; i < b; i++) { if (i != 0) ans.append(" "); ans.append(midk+1); } for (int i = b; i < b + x; i++) { if (i != 0) ans.append(" "); ans.append(mid); } for (int i = b + x; i < n; i++) { if (i != 0) ans.append(" "); ans.append(mid+1); } } else { for (int i = b; i < b + x; i++) { if (i != 0) ans.append(" "); ans.append(mid); } for (int i = b + x; i < n; i++) { if (i != 0) ans.append(" "); ans.append(mid+1); } } System.out.println(ans); } private static int pi(String s) { return Integer.parseInt(s); } }
Java
["5 3 1 3 13 9", "5 3 1 3 15 9"]
1 second
["2 3 2 3 3", "3 3 3 3 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "math" ]
59154ca15716f0c1c91a37d34c5bbf1d
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.
1,400
Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
standard output
PASSED
82d8e4536a2623cbf588f8a11eb84883
train_001.jsonl
1385739000
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
256 megabytes
import java.io.*; import java.util.*; public class a { public static void main(String[] args) throws IOException { input.init(System.in); PrintWriter out = new PrintWriter(System.out); int n = input.nextInt(), k = input.nextInt(), l = input.nextInt(), r = input.nextInt(); int sall = input.nextInt(), sk = input.nextInt(); int[] res = new int[n]; Arrays.fill(res, l); int tot = n*l, subtot = k*l; while(subtot < sk) { for(int i =0; i<k; i++) { res[i]++; tot++; subtot++; if(subtot == sk) break; } } while(tot < sall) { for(int i = k; i<n; i++) { res[i]++; tot++; if(tot == sall) break; } } for(int i =0; i<n; i++) out.print(res[i]+" "); out.close(); } static class Edge { int to, d; public Edge(int tt, int dd) { to = tt; d = dd; } } public static class input { 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() ); } static long nextLong() throws IOException { return Long.parseLong( next() ); } } }
Java
["5 3 1 3 13 9", "5 3 1 3 15 9"]
1 second
["2 3 2 3 3", "3 3 3 3 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "math" ]
59154ca15716f0c1c91a37d34c5bbf1d
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.
1,400
Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
standard output
PASSED
1e5f580e20451aa851850bd106fea722
train_001.jsonl
1385739000
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author To Huu Quan */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int k = in.nextInt(); int l = in.nextInt(); int r = in.nextInt(); int all = in.nextInt(); int sk = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < k; ++i) a[i] = sk / k; for (int i = 0; i < (sk % k); ++i) ++a[i]; if (k < n) { all -= sk; for (int i = k; i < n; ++i) a[i] = all / (n - k); for (int i = 0; i < (all % (n - k)); ++i) ++a[k + i]; } for (int i = 0; i < n; ++i) out.printf("%d ", a[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()); } }
Java
["5 3 1 3 13 9", "5 3 1 3 15 9"]
1 second
["2 3 2 3 3", "3 3 3 3 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "math" ]
59154ca15716f0c1c91a37d34c5bbf1d
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.
1,400
Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
standard output
PASSED
9838805ae2f37799431d83782f430b6a
train_001.jsonl
1385739000
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
256 megabytes
import java.util.Scanner; import java.io.PrintStream; public class TaskB{ public static void main(String[] argc){ Scanner in = new Scanner(System.in); PrintStream out = System.out; int n, k, l, r, sall, sk; n = in.nextInt(); k = in.nextInt(); l = in.nextInt(); r = in.nextInt(); sall = in.nextInt(); sk = in.nextInt(); int score[] = new int[n]; for (int s = l; s <= r; s++){ if (s * (n - k) + sk < sall) continue; for (int i = 0; i < k; i++) score[i] = s; for (int i = k; i < n; i++) score[i] = l; int remain = sk - k * s; for (int i = 0; i < k; i++){ int max_delta = Math.min(remain, r - score[i]); score[i] += max_delta; remain -= max_delta; } remain = sall - sk - (n - k) * l; for (int i = k; i < n; i++){ int max_delta = Math.min(remain, s - score[i]); remain -= max_delta; score[i] += max_delta; } for (int i = 0; i < n; i++) out.print(score[i] + " "); return; } } }
Java
["5 3 1 3 13 9", "5 3 1 3 15 9"]
1 second
["2 3 2 3 3", "3 3 3 3 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "math" ]
59154ca15716f0c1c91a37d34c5bbf1d
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.
1,400
Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
standard output
PASSED
a5b8f4ed6b549ac3e296bc54504ff18d
train_001.jsonl
1385739000
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.StringTokenizer; public class ProblemB { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out)); StringTokenizer st = new StringTokenizer(br.readLine()); int noOfStudents = Integer.parseInt(st.nextToken()); int mostPointStudents = Integer.parseInt(st.nextToken()); int atLeast = Integer.parseInt(st.nextToken()); int atMost = Integer.parseInt(st.nextToken()); int totalScore = Integer.parseInt(st.nextToken()); int scoredByMostPointsStudents = Integer.parseInt(st.nextToken()); int maxScore = scoredByMostPointsStudents/mostPointStudents; pw.print(maxScore); int remMax = scoredByMostPointsStudents % mostPointStudents; int remStuds = mostPointStudents - remMax; for(int i=1;i<remStuds;++i) { pw.print(" "+maxScore); } for(int i=0;i<remMax;++i) { pw.print(" "+(maxScore+1)); } totalScore-=scoredByMostPointsStudents; int remainingStudents = noOfStudents - mostPointStudents; if(remainingStudents > 0) { int scoreDistribution = totalScore/remainingStudents; int remainingPoints = totalScore % remainingStudents; remainingStudents-=remainingPoints; for(int i=0;i<remainingStudents;++i) { pw.print(" "+scoreDistribution); } scoreDistribution++; for(int i=0;i<remainingPoints;++i) { pw.print(" "+scoreDistribution); } } pw.println(); pw.flush(); pw.close(); } }
Java
["5 3 1 3 13 9", "5 3 1 3 15 9"]
1 second
["2 3 2 3 3", "3 3 3 3 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "math" ]
59154ca15716f0c1c91a37d34c5bbf1d
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.
1,400
Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
standard output
PASSED
6a6ef5227dba4c58d0058a78b6570ae0
train_001.jsonl
1385739000
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
256 megabytes
import java.util.Scanner; import java.io.OutputStream; import java.io.IOException; import java.io.PrintWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(); int k = in.nextInt(); int l = in.nextInt(); int r = in.nextInt(); int sall = in.nextInt(); int sk = in.nextInt(); print(sk,k,out); print(sall-sk,n-k,out); out.println(); } private void print(int sum, int k, PrintWriter out) { for (int i = 0; i < k; i++) { if (i < sum%k) out.print(sum/k+1+" "); else out.print(sum/k + " "); } } }
Java
["5 3 1 3 13 9", "5 3 1 3 15 9"]
1 second
["2 3 2 3 3", "3 3 3 3 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "math" ]
59154ca15716f0c1c91a37d34c5bbf1d
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.
1,400
Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
standard output
PASSED
27d9f77453084acda30be339ed93c6f3
train_001.jsonl
1385739000
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; /** * Built using CHelper plug-in * Actual solution is at the top * @author coderbd */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); int k = in.readInt(); int l = in.readInt(); int r = in.readInt(); int sall = in.readInt(); int sk = in.readInt(); int avgk = sk / k; int avgkm = sk % k; for (int i = 0; i < avgkm; i++) out.print(avgk + 1 + " "); for (int i = avgkm; i < k; i++) out.print(avgk + " "); n -= k; sall -= sk; if (n > 0) { int avgn = sall / n; int avgnm = sall % n; for (int i = 0; i < avgnm; i++) out.print(avgn + 1 + " "); for (int i = avgnm; i < n; i++) out.print(avgn + " "); } } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new 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 static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void close() { writer.close(); } }
Java
["5 3 1 3 13 9", "5 3 1 3 15 9"]
1 second
["2 3 2 3 3", "3 3 3 3 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "math" ]
59154ca15716f0c1c91a37d34c5bbf1d
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.
1,400
Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
standard output
PASSED
83864ddb432391592f60ea153bd39bdd
train_001.jsonl
1385739000
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.*; import javax.print.attribute.standard.MediaSize.ISO; public class Codeforces2 implements Runnable { private BufferedReader br = null; private PrintWriter pw = null; private StringTokenizer stk = new StringTokenizer(""); public static void main(String[] args) { new Thread(new Codeforces2()).run(); } public void run() { /* * try { br = new BufferedReader(new FileReader("/home/user/freshdb.sql")); pw = new PrintWriter("/home/user/freshdb_fix.sql"); } catch * (FileNotFoundException e) { e.printStackTrace(); } */ br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new OutputStreamWriter(System.out)); solver(); pw.close(); } private void nline() { try { if (!stk.hasMoreTokens()) stk = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException("KaVaBUnGO!!!", e); } } private String nstr() { while (!stk.hasMoreTokens()) nline(); return stk.nextToken(); } private int ni() { return Integer.valueOf(nstr()); } private long nl() { return Long.valueOf(nstr()); } private double nd() { return Double.valueOf(nstr()); } String nextLine() { try { return br.readLine(); } catch (IOException e) { } return null; } class Point { int x; int y; Point(int x, int y) { this.x = x; this.y = y; } } private void bfs(int t, boolean[] using, int[][] g) { Stack<Integer> st = new Stack<Integer>(); int n = using.length; st.add(t); while (!st.empty()) { int p = st.pop(); for (int i = 0; i < n; i++) { if (g[p][i] == 1 && !using[i]) { st.add(i); using[i] = true; } } } } public int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } private void solver() { int n = ni(), k = ni(), l = ni(), r = ni(), sa = ni(), sk = ni(); int a[] = new int[n]; for (int i=0; i<sk; i++){ ++a[i%k]; } for(int i=0; i<sa-sk; i++){ ++a[k+(i%(n-k))]; } for(int i=0; i<n; i++){ System.out.print(a[i]+" "); } } private BigInteger nbi() { return new BigInteger(nstr()); } void exit() { pw.close(); System.exit(0); } }
Java
["5 3 1 3 13 9", "5 3 1 3 15 9"]
1 second
["2 3 2 3 3", "3 3 3 3 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "math" ]
59154ca15716f0c1c91a37d34c5bbf1d
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.
1,400
Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
standard output
PASSED
7039ac4336e7aaa9baea232660887533
train_001.jsonl
1385739000
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
256 megabytes
import java.util.*; public class B { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); int min = sc.nextInt(); int max = sc.nextInt(); int total = sc.nextInt(); int kTotal = sc.nextInt(); int lTotal = total - kTotal; int l = n - k; int average_k = kTotal / k; int rem_k = kTotal % k; int[] score = new int[n]; for (int i = 0; i < k; i++) { score[i] = average_k; } int i = 0; while (rem_k != 0) { score[i] += 1; i++; rem_k --; } if (l != 0) { int average_l = lTotal / l; int rem_l = lTotal % l; for (int j = k; j < n; j++) { score[j] = average_l; } int j = k; while (rem_l != 0) { score[j] += 1; j++; rem_l --; } } for (int h = 0; h < n; h++) { System.out.print(score[h] + " "); } } }
Java
["5 3 1 3 13 9", "5 3 1 3 15 9"]
1 second
["2 3 2 3 3", "3 3 3 3 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "math" ]
59154ca15716f0c1c91a37d34c5bbf1d
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.
1,400
Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
standard output
PASSED
de52c0828ed6159848145f192df9d0af
train_001.jsonl
1385739000
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
256 megabytes
import java.util.*; import java.io.*; public class TeamContest { public static void main(String[] args) throws IOException { BufferedReader rd = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); StringTokenizer st = new StringTokenizer(rd.readLine()); int n = Integer.parseInt(st.nextToken()), k = Integer.parseInt(st.nextToken()), l = Integer.parseInt(st.nextToken()), r = Integer.parseInt(st.nextToken()), all = Integer.parseInt(st.nextToken()), sk = Integer.parseInt(st.nextToken()); int minimal = 0; // (n-k) calis jami aris (all-sk). titoeuli aris [l, min(r, minimal)]-shi. ArrayList<Integer> ans = new ArrayList<Integer>(); int leftSum = sk; for(int x=0; x<k; x++){ for(int i=r; i>=l; i--){ int leftPeople = k-1-x; if(leftPeople*i<=(leftSum-i) && (leftSum-i)<=leftPeople*r){ ans.add(i); if(ans.size()==1){ minimal = i; } leftSum -= i; break; } } } r = Math.min(r, minimal); int sumLeft = all - sk; for(int i=0; i<n-k; i++){ for(int x=l; x<=r; x++){ sumLeft -= x; int leftPeople = n-k-i-1; if(leftPeople*l <= sumLeft && sumLeft <= leftPeople*r){ ans.add(x); break; } sumLeft += x; } } for(int i=0; i<n; i++) pw.print(ans.get(i)+" "); pw.println(); pw.flush(); } }
Java
["5 3 1 3 13 9", "5 3 1 3 15 9"]
1 second
["2 3 2 3 3", "3 3 3 3 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "math" ]
59154ca15716f0c1c91a37d34c5bbf1d
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.
1,400
Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
standard output
PASSED
383f395cacae881a330f2490b4ec93e8
train_001.jsonl
1385739000
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
256 megabytes
import java.util.Scanner; public class B { static Scanner sc = new Scanner(System.in); public static void main(String[] args) { int n = sc.nextInt(); int k = sc.nextInt(); int l = sc.nextInt(); int r = sc.nextInt(); int sall = sc.nextInt(); int sk = sc.nextInt(); int ss = sall - sk; int[] a = new int[n]; if (k < n) { int min = ss/(n-k); int cnt = ss%(n-k); for (int i = k; i < n; i++) { a[i] = min; if (cnt > i-k) a[i]++; } } int min = sk/k; int cnt = sk%k; for (int i = 0; i < k; i++) { a[i] = min; if (cnt > i) a[i]++; } for (int i : a) System.out.print(i + " "); System.out.println(); } }
Java
["5 3 1 3 13 9", "5 3 1 3 15 9"]
1 second
["2 3 2 3 3", "3 3 3 3 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "math" ]
59154ca15716f0c1c91a37d34c5bbf1d
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.
1,400
Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
standard output
PASSED
b1765bb35f118fdc602c127af1d5e8c8
train_001.jsonl
1385739000
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
256 megabytes
//369B import java.io.*; import java.util.*; public class contest { public static void main(String args[])throws IOException {Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int k=sc.nextInt(); int l=sc.nextInt(); int r=sc.nextInt(); int sall=sc.nextInt(); int sk=sc.nextInt(); int x=sk/k; int a[]=new int[n]; int y=0; if(n!=k) y=(sall-sk)/(n-k); int x1=sk-k*x; int y1=(sall-sk)-y*(n-k); for(int i=0;i<n;i++) if(i<k) { if(x1>0) { a[i]=x+1; x1--; } else { a[i]=x; } } else { if(y1>0) { a[i]=y+1; y1--; } else { a[i]=y; } } for(int i:a) System.out.print(i+" "); }}
Java
["5 3 1 3 13 9", "5 3 1 3 15 9"]
1 second
["2 3 2 3 3", "3 3 3 3 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "math" ]
59154ca15716f0c1c91a37d34c5bbf1d
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.
1,400
Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
standard output
PASSED
261bcbe9f0abeaad8961e8b775187322
train_001.jsonl
1385739000
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author pttrung */ public class B { public static int r1, r2, c1, c2, d1, d2; public static void main(String[] args) { Scanner in = new Scanner(); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int k = in.nextInt(); int l = in.nextInt(); int r = in.nextInt(); int sa = in.nextInt(); int sk = in.nextInt(); int other = n - k; int left = sa - sk - (other * l); int[] result = new int[other]; for (int i = 0; i < other; i++) { result[i] = l; } int index = 0; int max = l; while (left > 0) { result[index] += 1; max = Math.max(max, result[index]); left--; index = (index + 1) % other; } left = sk - (k * max); int[] right = new int[k]; for (int i = 0; i < k; i++) { right[i] = max; } index = 0; while (left > 0) { right[index] += 1; left--; index = (index + 1) % k; } for(int i = 0; i < other; i++){ out.print(result[i] + " "); } for(int i = 0; i < k ; i++){ out.print(right[i] + " "); } out.close(); } public static double dist(Point a, Point b) { double val = (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y); return Math.sqrt(val); } public static class Point { double x, y; public Point(double x, double y) { this.x = x; this.y = y; } } public static boolean nextPer(int[] data) { int i = data.length - 1; while (i > 0 && data[i] < data[i - 1]) { i--; } if (i == 0) { return false; } int j = data.length - 1; while (data[j] < data[i - 1]) { j--; } int temp = data[i - 1]; data[i - 1] = data[j]; data[j] = temp; Arrays.sort(data, i, data.length); return true; } public double pow(double a, int b) { if (b == 0) { return 1; } if (b == 1) { return a; } double val = pow(a, b / 2); if (b % 2 == 0) { return val * val; } else { return val * val * a; } } public static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } public static long lcm(long a, long b) { return a * b / gcd(a, b); } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() { // System.setOut(new PrintStream(new BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
Java
["5 3 1 3 13 9", "5 3 1 3 15 9"]
1 second
["2 3 2 3 3", "3 3 3 3 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "math" ]
59154ca15716f0c1c91a37d34c5bbf1d
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.
1,400
Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
standard output
PASSED
04bfe1742178b466abd67634e5ed551a
train_001.jsonl
1385739000
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
256 megabytes
import java.util.ArrayList; import java.util.Scanner; public class B { public static void main(String[] args) { (new B()).run(); } void run() { Scanner in = new Scanner(System.in); int n = in.nextInt(); int k = in.nextInt(); int l = in.nextInt(); int r = in.nextInt(); int s_all = in.nextInt(); int s_k = in.nextInt(); ArrayList<Integer> scores = new ArrayList<Integer>(n); // k first int mean = s_k / k; int rem = s_k % k; for(int i=0; i<k; i++) { if(rem > 0) { rem--; scores.add(mean+1); } else { scores.add(mean); } } // the rest if(n != k) { mean = (s_all - s_k) / (n - k); rem = (s_all - s_k) % (n - k); for(int i=0; i<n-k; i++) { if(rem > 0) { rem--; scores.add(mean+1); } else { scores.add(mean); } } } for(int i=0; i<scores.size(); i++) { if(i > 0) { System.out.print(" "); } System.out.print(scores.get(i)); } System.out.print("\n"); } }
Java
["5 3 1 3 13 9", "5 3 1 3 15 9"]
1 second
["2 3 2 3 3", "3 3 3 3 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "math" ]
59154ca15716f0c1c91a37d34c5bbf1d
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.
1,400
Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
standard output
PASSED
182a404bed86816c9de72ac8e9ca87c4
train_001.jsonl
1385739000
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
256 megabytes
import java.util.Scanner; public class ValeraandContest { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n = input.nextInt(); int k = input.nextInt(); int l = input.nextInt(); int r = input.nextInt(); int sAll = input.nextInt(); int sK = input.nextInt(); int temp; int remain; if (n == k) { temp = l; remain = 0; } else { temp = (sAll - sK) / (n - k); remain = (sAll - sK) % (n - k); } StringBuilder sb = new StringBuilder(); for (int i = 0; i < n - k - remain; ++i) { sb.append(temp + " "); } for (int i = 0; i < remain; ++i) { sb.append((temp + 1) + " "); } if (remain != 0) { ++temp; } remain = sK - temp * k; int sum = 0; for (int i = 0; i < k; ++i) { if (remain == 0) { sb.append(temp + " "); continue; } if (remain >= r - temp) { sb.append(r + " "); remain -= (r - temp); } else { sb.append((temp + remain) + " "); remain = 0; } } sb.deleteCharAt(sb.length() - 1); System.out.println(sb); } }
Java
["5 3 1 3 13 9", "5 3 1 3 15 9"]
1 second
["2 3 2 3 3", "3 3 3 3 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "math" ]
59154ca15716f0c1c91a37d34c5bbf1d
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.
1,400
Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
standard output
PASSED
d9dfd96073a0ec56e2a013d1a5c6c012
train_001.jsonl
1598020500
You are given a tree that consists of $$$n$$$ nodes. You should label each of its $$$n-1$$$ edges with an integer in such way that satisfies the following conditions: each integer must be greater than $$$0$$$; the product of all $$$n-1$$$ numbers should be equal to $$$k$$$; the number of $$$1$$$-s among all $$$n-1$$$ integers must be minimum possible. Let's define $$$f(u,v)$$$ as the sum of the numbers on the simple path from node $$$u$$$ to node $$$v$$$. Also, let $$$\sum\limits_{i=1}^{n-1} \sum\limits_{j=i+1}^n f(i,j)$$$ be a distribution index of the tree.Find the maximum possible distribution index you can get. Since answer can be too large, print it modulo $$$10^9 + 7$$$.In this problem, since the number $$$k$$$ can be large, the result of the prime factorization of $$$k$$$ is given instead.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class MaxDistributionTree { public static void main(String[] args) { long timeStart = System.nanoTime(); Utility.FastReader fr = new Utility.FastReader(); Solver solver = new Solver(fr); int t = fr.nextInt(); while (t-- > 0) { solver.solve(); } long timeEnd = System.nanoTime(); // System.out.println("Completed in :" + ((double) (timeEnd - timeStart) / 1000000) + " miliseconds"); } static class Solver { Utility.FastReader fr; static ArrayList<Integer>[] adj; static int[] subtreeSize; static int MOD=(int)1e9 + 7; public Solver(Utility.FastReader fr) { this.fr = fr; } void dfs(int node, int parent){ ArrayList<Integer> neighbors=adj[node]; int size=1; for(int nei: neighbors){ if(nei != parent){ dfs(nei, node); size += subtreeSize[nei]; } } subtreeSize[node]=size; } long mul(long a, long b){ return a * b % MOD; } void solve() { int n=fr.nextInt(); adj=new ArrayList[n]; for(int i=0; i<n; ++i) adj[i]=new ArrayList<>(); subtreeSize=new int[n]; for(int i=0; i<n-1; ++i){ int u, v; u=fr.nextInt()-1; v=fr.nextInt()-1; adj[u].add(v); adj[v].add(u); } int m=fr.nextInt(); int[] primes=new int[m]; for(int i=0; i<m; ++i){ primes[i]=fr.nextInt(); } Utility.sort(primes); // System.out.println(Arrays.toString(primes)); long[] edgeWeights=new long[n-1]; Arrays.fill(edgeWeights, 1); if(m>n-1){ int extra=m-(n-1); int i=0; while(i<m){ if(i<=extra){ edgeWeights[0]=mul(edgeWeights[0], primes[m-i-1]); } else{ edgeWeights[i-extra]=primes[m-i-1]; } i++; } } else{ for(int i=0; i<m; ++i){ edgeWeights[i]=primes[i]; } } // System.out.println("edge w" + Arrays.toString(edgeWeights)); Utility.sort(edgeWeights); dfs(0, -1); long[] contribution=new long[n-1]; for(int i=1; i<n; ++i){ long res=subtreeSize[i]*((long)(n-subtreeSize[i])); contribution[i-1]=res; } Arrays.sort(contribution); long ans=0; for(int i=0; i<n-1; ++i){ ans=(ans + mul(edgeWeights[i], contribution[i])) % MOD; } System.out.println(ans); } } static class Utility { static void sort(int[] a) { ArrayList<Integer> list = new ArrayList<>(); for (int i : a) list.add(i); Collections.sort(list); for (int i = 0; i < a.length; i++) a[i] = list.get(i); } static void sort(long[] a) { ArrayList<Long> list = new ArrayList<>(); for (long i : a) list.add(i); Collections.sort(list); for (int i = 0; i < a.length; i++) a[i] = list.get(i); } static void shuffleArray(long[] arr) { int n = arr.length; Random rnd = new Random(); for (int i = 0; i < n; ++i) { long tmp = arr[i]; int randomPos = i + rnd.nextInt(n - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } static void shuffleArray(int[] arr) { int n = arr.length; Random rnd = new Random(); for (int i = 0; i < n; ++i) { int tmp = arr[i]; int randomPos = i + rnd.nextInt(n - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } } }
Java
["3\n4\n1 2\n2 3\n3 4\n2\n2 2\n4\n3 4\n1 3\n3 2\n2\n3 2\n7\n6 1\n2 3\n4 6\n7 3\n5 1\n3 6\n4\n7 5 13 3"]
2 seconds
["17\n18\n286"]
Note In the first test case, one of the optimal ways is on the following image: In this case, $$$f(1,2)=1$$$, $$$f(1,3)=3$$$, $$$f(1,4)=5$$$, $$$f(2,3)=2$$$, $$$f(2,4)=4$$$, $$$f(3,4)=2$$$, so the sum of these $$$6$$$ numbers is $$$17$$$. In the second test case, one of the optimal ways is on the following image: In this case, $$$f(1,2)=3$$$, $$$f(1,3)=1$$$, $$$f(1,4)=4$$$, $$$f(2,3)=2$$$, $$$f(2,4)=5$$$, $$$f(3,4)=3$$$, so the sum of these $$$6$$$ numbers is $$$18$$$.
Java 11
standard input
[ "dp", "greedy", "number theory", "math", "implementation", "sortings", "dfs and similar", "trees" ]
968b3db21bd16bc04bdb355e98079d5d
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines describes an edge: the $$$i$$$-th line contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \ne v_i$$$) — indices of vertices connected by the $$$i$$$-th edge. Next line contains a single integer $$$m$$$ ($$$1 \le m \le 6 \cdot 10^4$$$) — the number of prime factors of $$$k$$$. Next line contains $$$m$$$ prime numbers $$$p_1, p_2, \ldots, p_m$$$ ($$$2 \le p_i &lt; 6 \cdot 10^4$$$) such that $$$k = p_1 \cdot p_2 \cdot \ldots \cdot p_m$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$, the sum of $$$m$$$ over all test cases doesn't exceed $$$6 \cdot 10^4$$$, and the given edges for each test cases form a tree.
1,800
Print the maximum distribution index you can get. Since answer can be too large, print it modulo $$$10^9+7$$$.
standard output
PASSED
b7417f2643bbd27cb9b68be3c3963885
train_001.jsonl
1598020500
You are given a tree that consists of $$$n$$$ nodes. You should label each of its $$$n-1$$$ edges with an integer in such way that satisfies the following conditions: each integer must be greater than $$$0$$$; the product of all $$$n-1$$$ numbers should be equal to $$$k$$$; the number of $$$1$$$-s among all $$$n-1$$$ integers must be minimum possible. Let's define $$$f(u,v)$$$ as the sum of the numbers on the simple path from node $$$u$$$ to node $$$v$$$. Also, let $$$\sum\limits_{i=1}^{n-1} \sum\limits_{j=i+1}^n f(i,j)$$$ be a distribution index of the tree.Find the maximum possible distribution index you can get. Since answer can be too large, print it modulo $$$10^9 + 7$$$.In this problem, since the number $$$k$$$ can be large, the result of the prime factorization of $$$k$$$ is given instead.
256 megabytes
import java.util.*; import java.math.*; public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); final long MOD = 1000000007L; int t = in.nextInt(); for(int tt = 0; tt < t; tt++) { long ans = 0L; int n = in.nextInt(); Node[] nodes = new Node[n]; List<Long> s = new ArrayList<Long>(); List<Long> c = new ArrayList<Long>(); for(int i = 0; i < n; i++) nodes[i] = new Node(i); for(int i = 0; i < n - 1; i++) { int a = in.nextInt() - 1; int b = in.nextInt() - 1; nodes[a].list.add(b); nodes[b].list.add(a); } int m = in.nextInt(); for(int i = 0; i < m; i++) { c.add(in.nextLong()); } dfs(nodes, 0, 0, s); Collections.sort(s); Collections.sort(c); for(int i = 0; i < m; i++) { if(i >= n - 1) { long cur = ((c.get(n - 2) % MOD) * (c.get(i) % MOD)) % MOD; c.set(n - 2, cur); } } int cnt = Math.min(s.size(), c.size()) - 1; for(int i = s.size() - 1; i >= 0; i--) { long cur = (cnt >= 0) ? c.get(cnt) : 1L; cnt -= 1; long add = ((s.get(i) % MOD) * (cur % MOD)) % MOD; ans = ((ans % MOD) + (add % MOD)) % MOD; } System.out.println(ans); } } public static long dfs(Node[] nodes, int root, int parent, List<Long> s) { long sum = 1L; for(int i = 0; i < nodes[root].list.size(); i++) { int nxt = nodes[root].list.get(i); if(nxt == parent) continue; long temp = dfs(nodes, nxt, root, s); s.add(temp * (nodes.length - temp)); sum += temp; } return sum; } } class Node { int id; List<Integer> list = new ArrayList<Integer>(); public Node(int id) { this.id = id; } }
Java
["3\n4\n1 2\n2 3\n3 4\n2\n2 2\n4\n3 4\n1 3\n3 2\n2\n3 2\n7\n6 1\n2 3\n4 6\n7 3\n5 1\n3 6\n4\n7 5 13 3"]
2 seconds
["17\n18\n286"]
Note In the first test case, one of the optimal ways is on the following image: In this case, $$$f(1,2)=1$$$, $$$f(1,3)=3$$$, $$$f(1,4)=5$$$, $$$f(2,3)=2$$$, $$$f(2,4)=4$$$, $$$f(3,4)=2$$$, so the sum of these $$$6$$$ numbers is $$$17$$$. In the second test case, one of the optimal ways is on the following image: In this case, $$$f(1,2)=3$$$, $$$f(1,3)=1$$$, $$$f(1,4)=4$$$, $$$f(2,3)=2$$$, $$$f(2,4)=5$$$, $$$f(3,4)=3$$$, so the sum of these $$$6$$$ numbers is $$$18$$$.
Java 11
standard input
[ "dp", "greedy", "number theory", "math", "implementation", "sortings", "dfs and similar", "trees" ]
968b3db21bd16bc04bdb355e98079d5d
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines describes an edge: the $$$i$$$-th line contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \ne v_i$$$) — indices of vertices connected by the $$$i$$$-th edge. Next line contains a single integer $$$m$$$ ($$$1 \le m \le 6 \cdot 10^4$$$) — the number of prime factors of $$$k$$$. Next line contains $$$m$$$ prime numbers $$$p_1, p_2, \ldots, p_m$$$ ($$$2 \le p_i &lt; 6 \cdot 10^4$$$) such that $$$k = p_1 \cdot p_2 \cdot \ldots \cdot p_m$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$, the sum of $$$m$$$ over all test cases doesn't exceed $$$6 \cdot 10^4$$$, and the given edges for each test cases form a tree.
1,800
Print the maximum distribution index you can get. Since answer can be too large, print it modulo $$$10^9+7$$$.
standard output
PASSED
3ed5950d0bca0a0bc5d2dcd9f0ec9bf2
train_001.jsonl
1598020500
You are given a tree that consists of $$$n$$$ nodes. You should label each of its $$$n-1$$$ edges with an integer in such way that satisfies the following conditions: each integer must be greater than $$$0$$$; the product of all $$$n-1$$$ numbers should be equal to $$$k$$$; the number of $$$1$$$-s among all $$$n-1$$$ integers must be minimum possible. Let's define $$$f(u,v)$$$ as the sum of the numbers on the simple path from node $$$u$$$ to node $$$v$$$. Also, let $$$\sum\limits_{i=1}^{n-1} \sum\limits_{j=i+1}^n f(i,j)$$$ be a distribution index of the tree.Find the maximum possible distribution index you can get. Since answer can be too large, print it modulo $$$10^9 + 7$$$.In this problem, since the number $$$k$$$ can be large, the result of the prime factorization of $$$k$$$ is given instead.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.*; public class Main { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readArray(int n, int size){ int[] a = new int[size]; for(int i = 0; i < n; i++) { a[i] = this.nextInt(); } return a; } long[] readLongArray(int n, int size){ long[] a = new long[size]; for(int i = 0; i < n; i++) { a[i] = this.nextLong(); } return a; } } private static int MOD = (int)(1e9 + 7); private static long MODL = (long)(1e9 + 7); public static long dfs(LinkedList<Integer>[] graph, int node, List<Long> list, boolean[] visited){ visited[node] = true; long count = 1; for(int child : graph[node]){ if(!visited[child]){ long subtree = dfs(graph, child, list, visited); list.add(subtree*(graph.length - subtree)); count += subtree; } } return count; } public static void main(String[] args) { FastReader fs =new FastReader(); int t = fs.nextInt(); for(int z = 0; z < t; z++) { int n = fs.nextInt(); LinkedList<Integer>[] graph = new LinkedList[n]; for(int i = 0; i < n; i++) graph[i] = new LinkedList<>(); for(int i = 0; i < n - 1; i++) { int u = fs.nextInt() - 1; int v = fs.nextInt() - 1; graph[u].add(v); graph[v].add(u); } //System.out.println("Graph Build"); int m = fs.nextInt(); int[] factors = new int[m]; for(int i = 0; i < m; i++) { factors[i] = fs.nextInt(); } //System.out.println("Factors read"); Arrays.sort(factors); List<Long> weights = new ArrayList<>(); dfs(graph, 0, weights, new boolean[n]); Collections.sort(weights); //System.out.println(Arrays.toString(factors)); //System.out.println(weights); long ans = 0; if(m < n - 1) { int i = 0; for(i=0; i < (n - m - 1); i++) ans = (ans + weights.get(i)%MODL)%MODL; //System.out.println(Arrays.toString(factors)); //System.out.println(weights); //System.out.println(i); for( ; i < n-1; i++) ans = (ans + (factors[i-n+1+m]*weights.get(i))%MOD)%MOD; }else { int i; for(i = 0;i<n-2;i++) ans = (ans + (factors[i]*weights.get(i))%MOD)%MOD; long mul = 1L; for(;i<m;i++) mul = (mul * factors[i])%MOD; ans = (ans + (mul*weights.get(n-2))%MOD)%MOD; } System.out.println(ans); } } }
Java
["3\n4\n1 2\n2 3\n3 4\n2\n2 2\n4\n3 4\n1 3\n3 2\n2\n3 2\n7\n6 1\n2 3\n4 6\n7 3\n5 1\n3 6\n4\n7 5 13 3"]
2 seconds
["17\n18\n286"]
Note In the first test case, one of the optimal ways is on the following image: In this case, $$$f(1,2)=1$$$, $$$f(1,3)=3$$$, $$$f(1,4)=5$$$, $$$f(2,3)=2$$$, $$$f(2,4)=4$$$, $$$f(3,4)=2$$$, so the sum of these $$$6$$$ numbers is $$$17$$$. In the second test case, one of the optimal ways is on the following image: In this case, $$$f(1,2)=3$$$, $$$f(1,3)=1$$$, $$$f(1,4)=4$$$, $$$f(2,3)=2$$$, $$$f(2,4)=5$$$, $$$f(3,4)=3$$$, so the sum of these $$$6$$$ numbers is $$$18$$$.
Java 11
standard input
[ "dp", "greedy", "number theory", "math", "implementation", "sortings", "dfs and similar", "trees" ]
968b3db21bd16bc04bdb355e98079d5d
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines describes an edge: the $$$i$$$-th line contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \ne v_i$$$) — indices of vertices connected by the $$$i$$$-th edge. Next line contains a single integer $$$m$$$ ($$$1 \le m \le 6 \cdot 10^4$$$) — the number of prime factors of $$$k$$$. Next line contains $$$m$$$ prime numbers $$$p_1, p_2, \ldots, p_m$$$ ($$$2 \le p_i &lt; 6 \cdot 10^4$$$) such that $$$k = p_1 \cdot p_2 \cdot \ldots \cdot p_m$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$, the sum of $$$m$$$ over all test cases doesn't exceed $$$6 \cdot 10^4$$$, and the given edges for each test cases form a tree.
1,800
Print the maximum distribution index you can get. Since answer can be too large, print it modulo $$$10^9+7$$$.
standard output
PASSED
854c90464f96c0e6c5bc51b717c94e96
train_001.jsonl
1598020500
You are given a tree that consists of $$$n$$$ nodes. You should label each of its $$$n-1$$$ edges with an integer in such way that satisfies the following conditions: each integer must be greater than $$$0$$$; the product of all $$$n-1$$$ numbers should be equal to $$$k$$$; the number of $$$1$$$-s among all $$$n-1$$$ integers must be minimum possible. Let's define $$$f(u,v)$$$ as the sum of the numbers on the simple path from node $$$u$$$ to node $$$v$$$. Also, let $$$\sum\limits_{i=1}^{n-1} \sum\limits_{j=i+1}^n f(i,j)$$$ be a distribution index of the tree.Find the maximum possible distribution index you can get. Since answer can be too large, print it modulo $$$10^9 + 7$$$.In this problem, since the number $$$k$$$ can be large, the result of the prime factorization of $$$k$$$ is given instead.
256 megabytes
import java.util.*; import java.io.*; public class Question4My { static HashSet<Integer> nodes[]; static boolean vis[]; static int n; static int subtreeSize[]; static ArrayList<Long> list; static int MOD = (int)(1e9 + 7); static Reader sc = new Reader(); public static void main(String[] args) throws IOException{ int t = sc.nextInt(); while(t-->0) { solve(); } } public static void solve() throws IOException { n = sc.nextInt(); nodes = new HashSet[n]; vis = new boolean[n]; subtreeSize = new int[n]; list = new ArrayList<>(); //initiate for(int i = 0;i < n;i++) nodes[i] = new HashSet<Integer>(); for(int i = 0;i < n - 1;i++) { int u = sc.nextInt() - 1; int v = sc.nextInt() - 1; nodes[u].add(v); nodes[v].add(u); } //input prime factors int m = sc.nextInt(); ArrayList<Integer> factors = new ArrayList<>(); for(int i = 0;i < m;i++) { factors.add(sc.nextInt()); } while(m < n - 1) { factors.add(1); m++; } Collections.sort(factors); dfs(0); Collections.sort(list); // System.out.println(list); // System.out.println(factors); // System.out.println("\n"); // // System.out.println("list size : " + list.size()); // System.out.println("factors size : " + factors.size()); int a = list.size() - 1; long ans = 0; long[] values = new long[list.size()]; values[a] = (long)list.get(a); for(int i = a + 1;i < factors.size();i++) { values[a] = (values[a] * factors.get(i)) % MOD; } for(int i = 0;i < a;i++)values[i] = (long)list.get(i); for(int i = 0;i < values.length;i++) { ans = (ans + (values[i] * factors.get(i)) % MOD) % MOD; } System.out.println(ans); } public static void dfs(int curr) { vis[curr] = true; int subtree = 1; for(Integer ix : nodes[curr]) { if(!vis[ix]) { dfs(ix); subtree += subtreeSize[ix]; } } subtreeSize[curr] = subtree; if((long)subtree * (long)(n - subtree) != 0) list.add((long)subtree * (long)(n - subtree)); } static long mul(long a, long b) { return (a * b) % MOD; } 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(); } } }
Java
["3\n4\n1 2\n2 3\n3 4\n2\n2 2\n4\n3 4\n1 3\n3 2\n2\n3 2\n7\n6 1\n2 3\n4 6\n7 3\n5 1\n3 6\n4\n7 5 13 3"]
2 seconds
["17\n18\n286"]
Note In the first test case, one of the optimal ways is on the following image: In this case, $$$f(1,2)=1$$$, $$$f(1,3)=3$$$, $$$f(1,4)=5$$$, $$$f(2,3)=2$$$, $$$f(2,4)=4$$$, $$$f(3,4)=2$$$, so the sum of these $$$6$$$ numbers is $$$17$$$. In the second test case, one of the optimal ways is on the following image: In this case, $$$f(1,2)=3$$$, $$$f(1,3)=1$$$, $$$f(1,4)=4$$$, $$$f(2,3)=2$$$, $$$f(2,4)=5$$$, $$$f(3,4)=3$$$, so the sum of these $$$6$$$ numbers is $$$18$$$.
Java 11
standard input
[ "dp", "greedy", "number theory", "math", "implementation", "sortings", "dfs and similar", "trees" ]
968b3db21bd16bc04bdb355e98079d5d
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines describes an edge: the $$$i$$$-th line contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \ne v_i$$$) — indices of vertices connected by the $$$i$$$-th edge. Next line contains a single integer $$$m$$$ ($$$1 \le m \le 6 \cdot 10^4$$$) — the number of prime factors of $$$k$$$. Next line contains $$$m$$$ prime numbers $$$p_1, p_2, \ldots, p_m$$$ ($$$2 \le p_i &lt; 6 \cdot 10^4$$$) such that $$$k = p_1 \cdot p_2 \cdot \ldots \cdot p_m$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$, the sum of $$$m$$$ over all test cases doesn't exceed $$$6 \cdot 10^4$$$, and the given edges for each test cases form a tree.
1,800
Print the maximum distribution index you can get. Since answer can be too large, print it modulo $$$10^9+7$$$.
standard output
PASSED
86ab3e2fba114bbed1834fa6a7a23026
train_001.jsonl
1598020500
You are given a tree that consists of $$$n$$$ nodes. You should label each of its $$$n-1$$$ edges with an integer in such way that satisfies the following conditions: each integer must be greater than $$$0$$$; the product of all $$$n-1$$$ numbers should be equal to $$$k$$$; the number of $$$1$$$-s among all $$$n-1$$$ integers must be minimum possible. Let's define $$$f(u,v)$$$ as the sum of the numbers on the simple path from node $$$u$$$ to node $$$v$$$. Also, let $$$\sum\limits_{i=1}^{n-1} \sum\limits_{j=i+1}^n f(i,j)$$$ be a distribution index of the tree.Find the maximum possible distribution index you can get. Since answer can be too large, print it modulo $$$10^9 + 7$$$.In this problem, since the number $$$k$$$ can be large, the result of the prime factorization of $$$k$$$ is given instead.
256 megabytes
import java.util.*; import java.io.*; public class Question4My { static HashSet<Integer> nodes[]; static boolean vis[]; static int n; static long subtreeSize[]; static ArrayList<Long> list; static int MOD = (int)(1e9 + 7); static Reader sc = new Reader(); public static void main(String[] args) throws IOException{ int t = sc.nextInt(); while(t-->0) { solve(); } } public static void solve() throws IOException { n = sc.nextInt(); nodes = new HashSet[n]; vis = new boolean[n]; subtreeSize = new long[n]; list = new ArrayList<Long>(); //initiate for(int i = 0;i < n;i++) nodes[i] = new HashSet<Integer>(); for(int i = 0;i < n - 1;i++) { int u = sc.nextInt() - 1; int v = sc.nextInt() - 1; nodes[u].add(v); nodes[v].add(u); } //input prime factors int m = sc.nextInt(); ArrayList<Integer> factors = new ArrayList<>(); for(int i = 0;i < m;i++) { factors.add(sc.nextInt()); } while(m < n - 1) { factors.add(1); m++; } Collections.sort(factors); dfs(0); Collections.sort(list); // System.out.println(list); // System.out.println(factors); // System.out.println("\n"); // // System.out.println("list size : " + list.size()); // System.out.println("factors size : " + factors.size()); int a = list.size() - 1; long ans = 0; long[] values = new long[list.size()]; values[a] = (long)list.get(a); for(int i = a + 1;i < factors.size();i++) { values[a] = (values[a] * factors.get(i)) % MOD; } for(int i = 0;i < a;i++)values[i] = (long)list.get(i); for(int i = 0;i < values.length;i++) { ans = (ans + (values[i] * factors.get(i)) % MOD) % MOD; } System.out.println(ans); } public static void dfs(int curr) { vis[curr] = true; int subtree = 1; for(Integer ix : nodes[curr]) { if(!vis[ix]) { dfs(ix); subtree += subtreeSize[ix]; } } subtreeSize[curr] = subtree; long check = (long)subtree * (long)(n - subtree); if(check != 0) list.add(check); } static long mul(long a, long b) { return (a * b) % MOD; } 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(); } } }
Java
["3\n4\n1 2\n2 3\n3 4\n2\n2 2\n4\n3 4\n1 3\n3 2\n2\n3 2\n7\n6 1\n2 3\n4 6\n7 3\n5 1\n3 6\n4\n7 5 13 3"]
2 seconds
["17\n18\n286"]
Note In the first test case, one of the optimal ways is on the following image: In this case, $$$f(1,2)=1$$$, $$$f(1,3)=3$$$, $$$f(1,4)=5$$$, $$$f(2,3)=2$$$, $$$f(2,4)=4$$$, $$$f(3,4)=2$$$, so the sum of these $$$6$$$ numbers is $$$17$$$. In the second test case, one of the optimal ways is on the following image: In this case, $$$f(1,2)=3$$$, $$$f(1,3)=1$$$, $$$f(1,4)=4$$$, $$$f(2,3)=2$$$, $$$f(2,4)=5$$$, $$$f(3,4)=3$$$, so the sum of these $$$6$$$ numbers is $$$18$$$.
Java 11
standard input
[ "dp", "greedy", "number theory", "math", "implementation", "sortings", "dfs and similar", "trees" ]
968b3db21bd16bc04bdb355e98079d5d
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines describes an edge: the $$$i$$$-th line contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \ne v_i$$$) — indices of vertices connected by the $$$i$$$-th edge. Next line contains a single integer $$$m$$$ ($$$1 \le m \le 6 \cdot 10^4$$$) — the number of prime factors of $$$k$$$. Next line contains $$$m$$$ prime numbers $$$p_1, p_2, \ldots, p_m$$$ ($$$2 \le p_i &lt; 6 \cdot 10^4$$$) such that $$$k = p_1 \cdot p_2 \cdot \ldots \cdot p_m$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$, the sum of $$$m$$$ over all test cases doesn't exceed $$$6 \cdot 10^4$$$, and the given edges for each test cases form a tree.
1,800
Print the maximum distribution index you can get. Since answer can be too large, print it modulo $$$10^9+7$$$.
standard output
PASSED
4d4c8d9f266b3f34dce1b328b47077e4
train_001.jsonl
1598020500
You are given a tree that consists of $$$n$$$ nodes. You should label each of its $$$n-1$$$ edges with an integer in such way that satisfies the following conditions: each integer must be greater than $$$0$$$; the product of all $$$n-1$$$ numbers should be equal to $$$k$$$; the number of $$$1$$$-s among all $$$n-1$$$ integers must be minimum possible. Let's define $$$f(u,v)$$$ as the sum of the numbers on the simple path from node $$$u$$$ to node $$$v$$$. Also, let $$$\sum\limits_{i=1}^{n-1} \sum\limits_{j=i+1}^n f(i,j)$$$ be a distribution index of the tree.Find the maximum possible distribution index you can get. Since answer can be too large, print it modulo $$$10^9 + 7$$$.In this problem, since the number $$$k$$$ can be large, the result of the prime factorization of $$$k$$$ is given instead.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Task4 { ArrayList<Integer>[] adj; long[] subtreeSize; long[] edgeTraversals; int n; int mod; public static void main(String[] args) throws IOException { new Task4().solve(); } private void solve() throws IOException { BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); mod = 1000000007; int t = Integer.parseInt(f.readLine()); for (int t1 = 0; t1 < t; t1++) { n = Integer.parseInt(f.readLine()); adj = new ArrayList[n]; for (int i = 0; i < n; i++) adj[i] = new ArrayList<Integer>(); for (int i = 0; i < n - 1; i++) { StringTokenizer tokenizer = new StringTokenizer(f.readLine()); int a = Integer.parseInt(tokenizer.nextToken()) - 1; int b = Integer.parseInt(tokenizer.nextToken()) - 1; adj[a].add(b); adj[b].add(a); } subtreeSize = new long[n]; edgeTraversals = new long[n]; buildTree(0, -1); //System.out.println(Arrays.toString(edgeTraversals)); int m = Integer.parseInt(f.readLine()); Integer[] factors = new Integer[m]; StringTokenizer tokenizer = new StringTokenizer(f.readLine()); for (int i = 0; i < m; i++) factors[i] = Integer.parseInt(tokenizer.nextToken()); Arrays.sort(factors, Collections.reverseOrder()); long multiply = 1; int toConnect = m - (n - 1); ArrayList<Integer> nums = new ArrayList<Integer>(); for (int i = 0; i <= toConnect; i++) { multiply *= factors[i]; multiply %= mod; } if (multiply != 1) nums.add((int) multiply); for (int i = Math.max(toConnect + 1, 0); i < m; i++) nums.add(factors[i]); while (nums.size() < n - 1) nums.add(1); //System.out.println(nums); long res = 0; PriorityQueue<Long> edges = new PriorityQueue<Long>(Collections.reverseOrder()); for (int i = 1; i < n; i++) edges.add(edgeTraversals[i]); for (int num : nums) { long edge = edges.remove(); res += (long) num * edge; //System.out.println(num + " " +edge); res %= mod; } out.println(res); } out.close(); } private void buildTree(int node, int parent) { subtreeSize[node] = 1; for (int adjacent : adj[node]) { if (adjacent == parent) continue; buildTree(adjacent, node); subtreeSize[node] += subtreeSize[adjacent]; } if (node != 0) { long traversals = 0; long otherNodes = n - 1; for (int adjacent : adj[node]) { if (adjacent == parent) continue; otherNodes -= subtreeSize[adjacent]; //traversals += (long) subtreeSize[adjacent] * (n - subtreeSize[adjacent] - 1); //System.out.println(node + 1 + " " + subtreeSize[adjacent] * (n - subtreeSize[adjacent] - 1)); } traversals += otherNodes * ( n - otherNodes); edgeTraversals[node] = traversals; } } }
Java
["3\n4\n1 2\n2 3\n3 4\n2\n2 2\n4\n3 4\n1 3\n3 2\n2\n3 2\n7\n6 1\n2 3\n4 6\n7 3\n5 1\n3 6\n4\n7 5 13 3"]
2 seconds
["17\n18\n286"]
Note In the first test case, one of the optimal ways is on the following image: In this case, $$$f(1,2)=1$$$, $$$f(1,3)=3$$$, $$$f(1,4)=5$$$, $$$f(2,3)=2$$$, $$$f(2,4)=4$$$, $$$f(3,4)=2$$$, so the sum of these $$$6$$$ numbers is $$$17$$$. In the second test case, one of the optimal ways is on the following image: In this case, $$$f(1,2)=3$$$, $$$f(1,3)=1$$$, $$$f(1,4)=4$$$, $$$f(2,3)=2$$$, $$$f(2,4)=5$$$, $$$f(3,4)=3$$$, so the sum of these $$$6$$$ numbers is $$$18$$$.
Java 11
standard input
[ "dp", "greedy", "number theory", "math", "implementation", "sortings", "dfs and similar", "trees" ]
968b3db21bd16bc04bdb355e98079d5d
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines describes an edge: the $$$i$$$-th line contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \ne v_i$$$) — indices of vertices connected by the $$$i$$$-th edge. Next line contains a single integer $$$m$$$ ($$$1 \le m \le 6 \cdot 10^4$$$) — the number of prime factors of $$$k$$$. Next line contains $$$m$$$ prime numbers $$$p_1, p_2, \ldots, p_m$$$ ($$$2 \le p_i &lt; 6 \cdot 10^4$$$) such that $$$k = p_1 \cdot p_2 \cdot \ldots \cdot p_m$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$, the sum of $$$m$$$ over all test cases doesn't exceed $$$6 \cdot 10^4$$$, and the given edges for each test cases form a tree.
1,800
Print the maximum distribution index you can get. Since answer can be too large, print it modulo $$$10^9+7$$$.
standard output
PASSED
83df445dfe26946a2219ae1616da661c
train_001.jsonl
1591281300
Johnny has a new toy. As you may guess, it is a little bit extraordinary. The toy is a permutation $$$P$$$ of numbers from $$$1$$$ to $$$n$$$, written in one row next to each other. For each $$$i$$$ from $$$1$$$ to $$$n - 1$$$ between $$$P_i$$$ and $$$P_{i + 1}$$$ there is a weight $$$W_i$$$ written, and those weights form a permutation of numbers from $$$1$$$ to $$$n - 1$$$. There are also extra weights $$$W_0 = W_n = 0$$$.The instruction defines subsegment $$$[L, R]$$$ as good if $$$W_{L - 1} &lt; W_i$$$ and $$$W_R &lt; W_i$$$ for any $$$i$$$ in $$$\{L, L + 1, \ldots, R - 1\}$$$. For such subsegment it also defines $$$W_M$$$ as minimum of set $$$\{W_L, W_{L + 1}, \ldots, W_{R - 1}\}$$$. Now the fun begins. In one move, the player can choose one of the good subsegments, cut it into $$$[L, M]$$$ and $$$[M + 1, R]$$$ and swap the two parts. More precisely, before one move the chosen subsegment of our toy looks like: $$$$$$W_{L - 1}, P_L, W_L, \ldots, W_{M - 1}, P_M, W_M, P_{M + 1}, W_{M + 1}, \ldots, W_{R - 1}, P_R, W_R$$$$$$ and afterwards it looks like this: $$$$$$W_{L - 1}, P_{M + 1}, W_{M + 1}, \ldots, W_{R - 1}, P_R, W_M, P_L, W_L, \ldots, W_{M - 1}, P_M, W_R$$$$$$ Such a move can be performed multiple times (possibly zero), and the goal is to achieve the minimum number of inversions in $$$P$$$. Johnny's younger sister Megan thinks that the rules are too complicated, so she wants to test her brother by choosing some pair of indices $$$X$$$ and $$$Y$$$, and swapping $$$P_X$$$ and $$$P_Y$$$ ($$$X$$$ might be equal $$$Y$$$). After each sister's swap, Johnny wonders, what is the minimal number of inversions that he can achieve, starting with current $$$P$$$ and making legal moves?You can assume that the input is generated randomly. $$$P$$$ and $$$W$$$ were chosen independently and equiprobably over all permutations; also, Megan's requests were chosen independently and equiprobably over all pairs of indices.
1024 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.Random; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author lewin */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); IJohnnyAndNewToy solver = new IJohnnyAndNewToy(); solver.solve(1, in, out); out.close(); } static class IJohnnyAndNewToy { int n; int[] p; int[] w; IJohnnyAndNewToy.Tree[] leaf; int lidx; long ans = 0; public IJohnnyAndNewToy.Tree create(int start, int end) { if (start + 1 == end) { leaf[lidx] = new IJohnnyAndNewToy.Tree(); leaf[lidx].vals = new TreapBST.Treap(p[start]); leaf[lidx].count = 0; leaf[lidx].size = 1; return leaf[lidx++]; } int mn = start + 1; for (int i = start + 1; i < end; i++) { if (w[i] < w[mn]) mn = i; } IJohnnyAndNewToy.Tree cur = new IJohnnyAndNewToy.Tree(); cur.left = create(start, mn); cur.right = create(mn, end); cur.left.par = cur; cur.left.side = 0; cur.right.par = cur; cur.right.side = 1; cur.size = cur.left.size + cur.right.size; cur.a1 = 0; cur.a2 = 0; for (int i = start; i < mn; i++) { int c1 = TreapBST.rank(cur.right.vals, p[i]); cur.a1 += c1; cur.a2 += cur.right.size - c1; } cur.count = Math.min(cur.a1, cur.a2); ans += cur.count; cur.vals = null; for (int i = start; i < end; i++) { cur.vals = TreapBST.insert(cur.vals, p[i]); } return cur; } void remove(IJohnnyAndNewToy.Tree cur, int value) { cur.vals = TreapBST.remove(cur.vals, value); cur.size--; int side = cur.side; cur = cur.par; while (cur != null) { if (side == 0) { int c = TreapBST.rank(cur.right.vals, value); cur.a1 -= c; cur.a2 -= cur.right.size - c; } else { int c = TreapBST.rank(cur.left.vals, value); cur.a2 -= c; cur.a1 -= cur.left.size - c; } ans -= cur.count; cur.count = Math.min(cur.a1, cur.a2); ans += cur.count; cur.size--; cur.vals = TreapBST.remove(cur.vals, value); side = cur.side; cur = cur.par; } } void add(IJohnnyAndNewToy.Tree cur, int value) { cur.vals = TreapBST.insert(cur.vals, value); cur.size++; int side = cur.side; cur = cur.par; while (cur != null) { if (side == 0) { int c = TreapBST.rank(cur.right.vals, value); cur.a1 += c; cur.a2 += cur.right.size - c; } else { int c = TreapBST.rank(cur.left.vals, value); cur.a2 += c; cur.a1 += cur.left.size - c; } ans -= cur.count; cur.count = Math.min(cur.a1, cur.a2); ans += cur.count; cur.size++; cur.vals = TreapBST.insert(cur.vals, value); side = cur.side; cur = cur.par; } } public void solve(int testNumber, InputReader in, OutputWriter out) { n = in.nextInt(); p = in.readIntArrayAndDecrementOne(n); w = new int[n + 1]; for (int i = 1; i < n; i++) w[i] = in.nextInt() - 1; leaf = new IJohnnyAndNewToy.Tree[n]; lidx = 0; create(0, n); int q = in.nextInt(); while (q-- > 0) { int x = in.nextInt() - 1, y = in.nextInt() - 1; if (x != y) { remove(leaf[x], p[x]); remove(leaf[y], p[y]); add(leaf[x], p[y]); add(leaf[y], p[x]); int t = p[x]; p[x] = p[y]; p[y] = t; } out.println(ans); } } static class Tree { public IJohnnyAndNewToy.Tree left; public IJohnnyAndNewToy.Tree right; public IJohnnyAndNewToy.Tree par; public int side; public TreapBST.Treap vals; public long count; public long a1; public long a2; public int size; } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1 << 16]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int[] readIntArrayAndDecrementOne(int tokens) { int[] ret = new int[tokens]; for (int i = 0; i < tokens; i++) { ret[i] = nextInt() - 1; } return ret; } public int read() { if (this.numChars == -1) { throw new InputMismatchException(); } else { if (this.curChar >= this.numChars) { this.curChar = 0; try { this.numChars = this.stream.read(this.buf); } catch (IOException var2) { throw new InputMismatchException(); } if (this.numChars <= 0) { return -1; } } return this.buf[this.curChar++]; } } public int nextInt() { int c; for (c = this.read(); isSpaceChar(c); c = this.read()) { ; } byte sgn = 1; if (c == 45) { sgn = -1; c = this.read(); } int res = 0; while (c >= 48 && c <= 57) { res *= 10; res += c - 48; c = this.read(); if (isSpaceChar(c)) { return res * sgn; } } throw new InputMismatchException(); } public static boolean isSpaceChar(int c) { return c == 32 || c == 10 || c == 13 || c == 9 || c == -1; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void println(long i) { writer.println(i); } } static class TreapBST { static Random random = new Random(); public static int getSize(TreapBST.Treap root) { return root == null ? 0 : root.size; } public static TreapBST.TreapPair split(TreapBST.Treap root, int minRight) { if (root == null) return new TreapBST.TreapPair(null, null); root.update(); if (root.key >= minRight) { TreapBST.TreapPair leftSplit = split(root.left, minRight); root.left = leftSplit.right; root.update(); leftSplit.right = root; return leftSplit; } else { TreapBST.TreapPair rightSplit = split(root.right, minRight); root.right = rightSplit.left; root.update(); rightSplit.left = root; return rightSplit; } } public static TreapBST.Treap merge(TreapBST.Treap left, TreapBST.Treap right) { if (left != null) left.update(); if (right != null) right.update(); if (left == null) return right; if (right == null) return left; // if (random.nextInt(left.size + right.size) < left.size) { if (left.prio > right.prio) { left.right = merge(left.right, right); left.update(); return left; } else { right.left = merge(left, right.left); right.update(); return right; } } public static TreapBST.Treap insert(TreapBST.Treap root, int key) { TreapBST.TreapPair t = split(root, key); return merge(merge(t.left, new TreapBST.Treap(key)), t.right); } public static TreapBST.Treap remove(TreapBST.Treap root, int key) { TreapBST.TreapPair t = split(root, key); return merge(t.left, split(t.right, key + 1).right); } public static int rank(TreapBST.Treap root, int val) { if (root == null) { return 0; } if (root.key <= val) { return rank(root.right, val) + 1 + getSize(root.left); } else { return rank(root.left, val); } } public static class Treap { public int key; public int size; public long prio; public int lazy; public TreapBST.Treap left; public TreapBST.Treap right; public Treap(int key) { this.key = key; prio = random.nextLong(); size = 1; lazy = 0; } public void update() { size = 1 + getSize(left) + getSize(right); if (lazy != 0) { if (left != null) { left.lazy += lazy; left.key += lazy; } if (right != null) { right.lazy += lazy; right.key += lazy; } lazy = 0; } } } public static class TreapPair { public TreapBST.Treap left; public TreapBST.Treap right; public TreapPair(TreapBST.Treap left, TreapBST.Treap right) { this.left = left; this.right = right; } } } }
Java
["3\n3 2 1\n2 1\n3\n1 3\n3 2\n3 1", "5\n4 3 2 5 1\n3 2 1 4\n7\n5 4\n5 2\n1 5\n2 4\n2 4\n4 3\n3 3"]
15 seconds
["0\n1\n0", "3\n1\n2\n1\n2\n3\n3"]
NoteConsider the first sample. After the first query, $$$P$$$ is sorted, so we already achieved a permutation with no inversions. After the second query, $$$P$$$ is equal to [$$$1$$$, $$$3$$$, $$$2$$$], it has one inversion, it can be proven that it is impossible to achieve $$$0$$$ inversions. In the end, $$$P$$$ is equal to [$$$2$$$, $$$3$$$, $$$1$$$]; we can make a move on the whole permutation, as it is a good subsegment itself, which results in $$$P$$$ equal to [$$$1$$$, $$$2$$$, $$$3$$$], which has $$$0$$$ inversions.
Java 11
standard input
[ "data structures", "implementation", "math" ]
354f3e98fefb325b8503be21c84ac4ef
The first line contains single integer $$$n$$$ $$$(2 \leq n \leq 2 \cdot 10^5)$$$ denoting the length of the toy. The second line contains $$$n$$$ distinct integers $$$P_1, P_2, \ldots, P_n$$$ $$$(1 \leq P_i \leq n)$$$ denoting the initial permutation $$$P$$$. The third line contains $$$n - 1$$$ distinct integers $$$W_1, W_2, \ldots, W_{n - 1}$$$ $$$(1 \leq W_i \leq n - 1)$$$ denoting the weights. The fourth line contains single integer $$$q$$$ $$$(1 \leq q \leq 5 \cdot 10^4)$$$ — the number of Megan's swaps. The following $$$q$$$ lines contain two integers $$$X$$$ and $$$Y$$$ $$$(1 \leq X, Y \leq n)$$$ — the indices of elements of $$$P$$$ to swap. The queries aren't independent; after each of them, the permutation is changed.
3,300
Output $$$q$$$ lines. The $$$i$$$-th line should contain exactly one integer — the minimum number of inversions in permutation, which can be obtained by starting with the $$$P$$$ after first $$$i$$$ queries and making moves described in the game's instruction.
standard output
PASSED
12761ffab5b7357ceec55f46309130b1
train_001.jsonl
1603548300
Bandits appeared in the city! One of them is trying to catch as many citizens as he can.The city consists of $$$n$$$ squares connected by $$$n-1$$$ roads in such a way that it is possible to reach any square from any other square. The square number $$$1$$$ is the main square.After Sunday walk all the roads were changed to one-way roads in such a way that it is possible to reach any square from the main square.At the moment when the bandit appeared on the main square there were $$$a_i$$$ citizens on the $$$i$$$-th square. Now the following process will begin. First, each citizen that is currently on a square with some outgoing one-way roads chooses one of such roads and moves along it to another square. Then the bandit chooses one of the one-way roads outgoing from the square he is located and moves along it. The process is repeated until the bandit is located on a square with no outgoing roads. The bandit catches all the citizens on that square.The bandit wants to catch as many citizens as possible; the citizens want to minimize the number of caught people. The bandit and the citizens know positions of all citizens at any time, the citizens can cooperate. If both sides act optimally, how many citizens will be caught?
256 megabytes
import java.util.*; import java.io.*; public class A { static PrintWriter ww = new PrintWriter(System.out); static class Pair{ long extra , max , leaves; public Pair(long leaves , long max , long extra){ this.leaves = leaves; this.max = max; this.extra = extra; } } static ArrayList<Integer> arr[]; static long cost[]; static Pair res[]; static void dfs(int i){ if(arr[i].size() == 0){ res[i] = new Pair(1L , cost[i] , 0); return; } long leaves = 0 , max = Long.MIN_VALUE , extra = 0; for(int j : arr[i]){ dfs(j); max = Math.max(max , res[j].max); leaves += res[j].leaves; } for(int j : arr[i]){ extra += res[j].extra; extra += (max - res[j].max)*res[j].leaves; } extra -= cost[i]; if(extra < 0){ extra *= -1; long count = (extra + leaves - 1)/leaves; max += count; extra = count * leaves - extra; } res[i] = new Pair(leaves , max , extra); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); arr = new ArrayList[n + 1]; for(int i = 0 ; i <= n ; i ++){ arr[i] = new ArrayList<>(); } res = new Pair[n + 1]; for(int i = 2 ; i <= n ; i ++){ arr[sc.nextInt()].add(i); } cost = new long[n + 1]; for(int i = 1 ; i <= n ; i ++){ cost[i] = sc.nextInt(); } dfs(1); ww.println(res[1].max); ww.close(); } }
Java
["3\n1 1\n3 1 2", "3\n1 1\n3 1 3"]
1 second
["3", "4"]
NoteIn the first example the citizens on the square $$$1$$$ can split into two groups $$$2 + 1$$$, so that the second and on the third squares will have $$$3$$$ citizens each.In the second example no matter how citizens act the bandit can catch at least $$$4$$$ citizens.
Java 8
standard input
[ "greedy", "graphs", "binary search", "dfs and similar", "trees" ]
18cf79b50d0a389e6c3afd5d2f6bd9ed
The first line contains a single integer $$$n$$$ — the number of squares in the city ($$$2 \le n \le 2\cdot10^5$$$). The second line contains $$$n-1$$$ integers $$$p_2, p_3 \dots p_n$$$ meaning that there is a one-way road from the square $$$p_i$$$ to the square $$$i$$$ ($$$1 \le p_i &lt; i$$$). The third line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ — the number of citizens on each square initially ($$$0 \le a_i \le 10^9$$$).
1,900
Print a single integer — the number of citizens the bandit will catch if both sides act optimally.
standard output
PASSED
1c15f6fc6ddf3ef138ddc694e7fe0ca3
train_001.jsonl
1603548300
Bandits appeared in the city! One of them is trying to catch as many citizens as he can.The city consists of $$$n$$$ squares connected by $$$n-1$$$ roads in such a way that it is possible to reach any square from any other square. The square number $$$1$$$ is the main square.After Sunday walk all the roads were changed to one-way roads in such a way that it is possible to reach any square from the main square.At the moment when the bandit appeared on the main square there were $$$a_i$$$ citizens on the $$$i$$$-th square. Now the following process will begin. First, each citizen that is currently on a square with some outgoing one-way roads chooses one of such roads and moves along it to another square. Then the bandit chooses one of the one-way roads outgoing from the square he is located and moves along it. The process is repeated until the bandit is located on a square with no outgoing roads. The bandit catches all the citizens on that square.The bandit wants to catch as many citizens as possible; the citizens want to minimize the number of caught people. The bandit and the citizens know positions of all citizens at any time, the citizens can cooperate. If both sides act optimally, how many citizens will be caught?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.io.UncheckedIOException; import java.io.Closeable; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * @author khokharnikunj8 */ public class Main { public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "khokharnikunj8", 1 << 29); thread.start(); thread.join(); } static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastInput in = new FastInput(inputStream); FastOutput out = new FastOutput(outputStream); DBanditInACity solver = new DBanditInACity(); solver.solve(1, in, out); out.close(); } } static class DBanditInACity { int[][] G; long[] max; long[] accomodate; long[] leaf; int[] values; public int[][] packGraph(int[] from, int[] to, int n, int m) { int[][] g = new int[n + 1][]; int[] p = new int[n + 1]; for (int i = 0; i < m; i++) p[from[i]]++; for (int i = 0; i < m; i++) p[to[i]]++; for (int i = 0; i <= n; i++) g[i] = new int[p[i]]; for (int i = 0; i < m; i++) { g[from[i]][--p[from[i]]] = to[i]; g[to[i]][--p[to[i]]] = from[i]; } return g; } public void dfs(int node, int parent) { long mx = Long.MIN_VALUE; for (int i : G[node]) { if (i == parent) continue; dfs(i, node); mx = Math.max(mx, max[i]); } if (mx == Long.MIN_VALUE) { leaf[node] = 1; max[node] = values[node]; accomodate[node] = 0; return; } for (int i : G[node]) { if (i == parent) continue; if (mx == max[i]) { accomodate[node] += accomodate[i]; accomodate[node] = Math.min(accomodate[node], 300000000000000l); } else { accomodate[node] += accomodate[i]; if ((double) (mx - max[i]) * leaf[i] > 1e18) accomodate[node] = Math.min(accomodate[node], 300000000000000l); else accomodate[node] += ((mx - max[i]) * leaf[i]); accomodate[node] = Math.min(accomodate[node], 300000000000000l); } leaf[node] += leaf[i]; } max[node] = mx; if (accomodate[node] >= values[node]) { accomodate[node] -= values[node]; } else { values[node] -= accomodate[node]; accomodate[node] = 0; long how_much = values[node] / leaf[node]; max[node] += how_much; if (values[node] % leaf[node] != 0) { max[node]++; accomodate[node] = (leaf[node] - (values[node] % leaf[node])); } } } public void solve(int testNumber, FastInput in, FastOutput out) { int n = in.readInt(); int[] from = new int[n - 1]; int[] to = new int[n - 1]; for (int i = 0; i < n - 1; i++) { from[i] = i + 2; to[i] = in.readInt(); } G = packGraph(from, to, n, n - 1); max = new long[n + 1]; accomodate = new long[n + 1]; leaf = new long[n + 1]; values = new int[n + 1]; for (int i = 1; i <= n; i++) values[i] = in.readInt(); dfs(1, -1); out.println(max[1]); } } static class FastOutput implements AutoCloseable, Closeable, Appendable { private final Writer os; private final StringBuilder cache = new StringBuilder(5 << 20); public FastOutput(Writer os) { this.os = os; } public FastOutput(OutputStream os) { this(new OutputStreamWriter(os)); } public FastOutput append(CharSequence csq) { cache.append(csq); return this; } public FastOutput append(CharSequence csq, int start, int end) { cache.append(csq, start, end); return this; } public FastOutput append(char c) { cache.append(c); return this; } public FastOutput append(long c) { cache.append(c); return this; } public FastOutput println(long c) { return append(c).println(); } public FastOutput println() { cache.append(System.lineSeparator()); return this; } public FastOutput flush() { try { os.append(cache); os.flush(); cache.setLength(0); } catch (IOException e) { throw new UncheckedIOException(e); } return this; } public void close() { flush(); try { os.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } public String toString() { return cache.toString(); } } static class FastInput { private final InputStream is; private final byte[] buf = new byte[1 << 13]; private int bufLen; private int bufOffset; private int next; public FastInput(InputStream is) { this.is = is; } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { bufLen = -1; } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public int readInt() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } int val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } } }
Java
["3\n1 1\n3 1 2", "3\n1 1\n3 1 3"]
1 second
["3", "4"]
NoteIn the first example the citizens on the square $$$1$$$ can split into two groups $$$2 + 1$$$, so that the second and on the third squares will have $$$3$$$ citizens each.In the second example no matter how citizens act the bandit can catch at least $$$4$$$ citizens.
Java 8
standard input
[ "greedy", "graphs", "binary search", "dfs and similar", "trees" ]
18cf79b50d0a389e6c3afd5d2f6bd9ed
The first line contains a single integer $$$n$$$ — the number of squares in the city ($$$2 \le n \le 2\cdot10^5$$$). The second line contains $$$n-1$$$ integers $$$p_2, p_3 \dots p_n$$$ meaning that there is a one-way road from the square $$$p_i$$$ to the square $$$i$$$ ($$$1 \le p_i &lt; i$$$). The third line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ — the number of citizens on each square initially ($$$0 \le a_i \le 10^9$$$).
1,900
Print a single integer — the number of citizens the bandit will catch if both sides act optimally.
standard output
PASSED
95f2906b98fd413710ffda92373db93b
train_001.jsonl
1603548300
Bandits appeared in the city! One of them is trying to catch as many citizens as he can.The city consists of $$$n$$$ squares connected by $$$n-1$$$ roads in such a way that it is possible to reach any square from any other square. The square number $$$1$$$ is the main square.After Sunday walk all the roads were changed to one-way roads in such a way that it is possible to reach any square from the main square.At the moment when the bandit appeared on the main square there were $$$a_i$$$ citizens on the $$$i$$$-th square. Now the following process will begin. First, each citizen that is currently on a square with some outgoing one-way roads chooses one of such roads and moves along it to another square. Then the bandit chooses one of the one-way roads outgoing from the square he is located and moves along it. The process is repeated until the bandit is located on a square with no outgoing roads. The bandit catches all the citizens on that square.The bandit wants to catch as many citizens as possible; the citizens want to minimize the number of caught people. The bandit and the citizens know positions of all citizens at any time, the citizens can cooperate. If both sides act optimally, how many citizens will be caught?
256 megabytes
import java.io.*; import java.util.*; /** * Created by Katushka on 11.03.2020. */ public class Main { static int[] readArray(int size, InputReader in) { int[] a = new int[size]; for (int i = 0; i < size; i++) { a[i] = in.nextInt(); } return a; } static long[] readLongArray(int size, InputReader in) { long[] a = new long[size]; for (int i = 0; i < size; i++) { a[i] = in.nextLong(); } return a; } private static void outputArray(List<Integer> ans, PrintWriter out) { StringBuilder str = new StringBuilder(); for (int an : ans) { str.append(an).append(' '); } out.println(str); } static final long MOD = 1000000007; public static void main(String[] args) throws FileNotFoundException { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int n = in.nextInt(); int[] ps = readArray(n - 1, in); long[] a = readLongArray(n, in); List<Integer>[] children = new List[n]; for (int i = 0; i < n; i++) { children[i] = new ArrayList<>(); } for (int i = 0; i < ps.length; i++) { children[ps[i] - 1].add(i + 1); } out.println(solve(0, children, a)[2]); out.close(); } private static long[] solve(int v, List<Integer>[] children, long[] a) { long sum = a[v]; long leaves = children[v].isEmpty() ? 1 : 0; long ans = 0; for (int i = 0; i < children[v].size(); i++) { long[] res = solve(children[v].get(i), children, a); sum += res[0]; leaves += res[1]; ans = Math.max(ans, res[2]); } ans = Math.max((sum + leaves - 1) / leaves, ans); return new long[]{sum, leaves, ans}; } private static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public String nextString() { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public char nextChar() { return next().charAt(0); } } }
Java
["3\n1 1\n3 1 2", "3\n1 1\n3 1 3"]
1 second
["3", "4"]
NoteIn the first example the citizens on the square $$$1$$$ can split into two groups $$$2 + 1$$$, so that the second and on the third squares will have $$$3$$$ citizens each.In the second example no matter how citizens act the bandit can catch at least $$$4$$$ citizens.
Java 8
standard input
[ "greedy", "graphs", "binary search", "dfs and similar", "trees" ]
18cf79b50d0a389e6c3afd5d2f6bd9ed
The first line contains a single integer $$$n$$$ — the number of squares in the city ($$$2 \le n \le 2\cdot10^5$$$). The second line contains $$$n-1$$$ integers $$$p_2, p_3 \dots p_n$$$ meaning that there is a one-way road from the square $$$p_i$$$ to the square $$$i$$$ ($$$1 \le p_i &lt; i$$$). The third line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ — the number of citizens on each square initially ($$$0 \le a_i \le 10^9$$$).
1,900
Print a single integer — the number of citizens the bandit will catch if both sides act optimally.
standard output
PASSED
afcf3d33b4af836540e798a59fe046af
train_001.jsonl
1603548300
Bandits appeared in the city! One of them is trying to catch as many citizens as he can.The city consists of $$$n$$$ squares connected by $$$n-1$$$ roads in such a way that it is possible to reach any square from any other square. The square number $$$1$$$ is the main square.After Sunday walk all the roads were changed to one-way roads in such a way that it is possible to reach any square from the main square.At the moment when the bandit appeared on the main square there were $$$a_i$$$ citizens on the $$$i$$$-th square. Now the following process will begin. First, each citizen that is currently on a square with some outgoing one-way roads chooses one of such roads and moves along it to another square. Then the bandit chooses one of the one-way roads outgoing from the square he is located and moves along it. The process is repeated until the bandit is located on a square with no outgoing roads. The bandit catches all the citizens on that square.The bandit wants to catch as many citizens as possible; the citizens want to minimize the number of caught people. The bandit and the citizens know positions of all citizens at any time, the citizens can cooperate. If both sides act optimally, how many citizens will be caught?
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Main { PrintWriter out = new PrintWriter(System.out); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer tok = new StringTokenizer(""); String next() throws IOException { if (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int ni() throws IOException { return Integer.parseInt(next()); } long nl() throws IOException { return Long.parseLong(next()); } long mod=1000000007; int n; ArrayList<Integer>[]A; long[]nl,currmax,sts,c; void solve() throws IOException { n=ni(); A=new ArrayList[n+1]; for (int i=1;i<=n;i++) A[i]=new ArrayList(); for (int i=2;i<=n;i++) A[ni()].add(i); c=new long[n+1]; nl=new long[n+1]; currmax=new long[n+1]; sts=new long[n+1]; for (int i=1;i<=n;i++) c[i]=ni(); dfs(1); out.println(currmax[1]); out.flush(); } void dfs(int u) { sts[u]=c[u]; if (A[u].size()==0) { nl[u]=1; currmax[u]=sts[u]; return; } for (int j=0;j<A[u].size();j++) { int v=A[u].get(j); dfs(v); currmax[u]=Math.max(currmax[u],currmax[v]); sts[u]+=sts[v]; nl[u]+=nl[v]; } currmax[u]=Math.max(currmax[u],sts[u]/nl[u]+(sts[u]%nl[u]>0?1:0)); } 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)); } long mp(long a,long p) { long r=1; while(p>0) { if ((p&1)==1) r=(r*a)%mod; p>>=1; a=(a*a)%mod; } return r; } public static void main(String[] args) throws IOException { new Main().solve(); } }
Java
["3\n1 1\n3 1 2", "3\n1 1\n3 1 3"]
1 second
["3", "4"]
NoteIn the first example the citizens on the square $$$1$$$ can split into two groups $$$2 + 1$$$, so that the second and on the third squares will have $$$3$$$ citizens each.In the second example no matter how citizens act the bandit can catch at least $$$4$$$ citizens.
Java 8
standard input
[ "greedy", "graphs", "binary search", "dfs and similar", "trees" ]
18cf79b50d0a389e6c3afd5d2f6bd9ed
The first line contains a single integer $$$n$$$ — the number of squares in the city ($$$2 \le n \le 2\cdot10^5$$$). The second line contains $$$n-1$$$ integers $$$p_2, p_3 \dots p_n$$$ meaning that there is a one-way road from the square $$$p_i$$$ to the square $$$i$$$ ($$$1 \le p_i &lt; i$$$). The third line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ — the number of citizens on each square initially ($$$0 \le a_i \le 10^9$$$).
1,900
Print a single integer — the number of citizens the bandit will catch if both sides act optimally.
standard output
PASSED
bd3139803cc9fb58c23c95f0292d324e
train_001.jsonl
1603548300
Bandits appeared in the city! One of them is trying to catch as many citizens as he can.The city consists of $$$n$$$ squares connected by $$$n-1$$$ roads in such a way that it is possible to reach any square from any other square. The square number $$$1$$$ is the main square.After Sunday walk all the roads were changed to one-way roads in such a way that it is possible to reach any square from the main square.At the moment when the bandit appeared on the main square there were $$$a_i$$$ citizens on the $$$i$$$-th square. Now the following process will begin. First, each citizen that is currently on a square with some outgoing one-way roads chooses one of such roads and moves along it to another square. Then the bandit chooses one of the one-way roads outgoing from the square he is located and moves along it. The process is repeated until the bandit is located on a square with no outgoing roads. The bandit catches all the citizens on that square.The bandit wants to catch as many citizens as possible; the citizens want to minimize the number of caught people. The bandit and the citizens know positions of all citizens at any time, the citizens can cooperate. If both sides act optimally, how many citizens will be caught?
256 megabytes
import java.awt.Point; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Locale; import java.util.Random; import java.util.StringTokenizer; import static java.lang.Math.max; import static java.lang.Math.min; public class D implements Runnable{ // SOLUTION AT THE TOP OF CODE!!! // HACK ME PLEASE IF YOU CAN!!! // PLEASE!!! // PLEASE!!! // PLEASE!!! @SuppressWarnings("unused") private final static Random rnd = new Random(); private final static String fileName = ""; private final static long MODULO = 1000 * 1000 * 1000 + 7; // THERE SOLUTION STARTS!!! private void solve() { int n = readInt(); int[] parents = new int[n]; parents[0] = -1; for (int i = 1; i < n; ++i) parents[i] = readInt() - 1; long[] a = readLongArray(n); long answer = getAnswer(n, parents, a); out.println(answer); } long getAnswer(int n, int[] parents, long[] a) { GraphBuilder graphBuilder = GraphBuilder.createInstance(n); for (int i = 1; i < n; ++i) { graphBuilder.addDirectedEdge(parents[i], i); } int[][] graph = graphBuilder.build(); long[] minMaxLeafs = new long[n]; long[] totalSubtreeSum = new long[n]; int[] leafsCounts = new int[n]; for (int v = n - 1; v >= 0; --v) { long vertexCount = a[v]; totalSubtreeSum[v] = vertexCount; if (0 == graph[v].length) { minMaxLeafs[v] = totalSubtreeSum[v]; leafsCounts[v] = 1; } else { long maxChildLeaf = 0; for (int child : graph[v]) { maxChildLeaf = max(maxChildLeaf, minMaxLeafs[child]); totalSubtreeSum[v] += totalSubtreeSum[child]; leafsCounts[v] += leafsCounts[child]; } long minEqualSum = maxChildLeaf * leafsCounts[v]; long resultSum = max(minEqualSum, totalSubtreeSum[v]); minMaxLeafs[v] = (resultSum + leafsCounts[v] - 1) / leafsCounts[v]; } } return minMaxLeafs[0]; } ///////////////////////////////////////////////////////////////////// private final static boolean MULTIPLE_TESTS = true; private final boolean ONLINE_JUDGE = !new File("input.txt").exists(); // private final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; private final static int MAX_STACK_SIZE = 128; private final static boolean OPTIMIZE_READ_NUMBERS = false; ///////////////////////////////////////////////////////////////////// @SuppressWarnings("unused") private static long inverse(long x) { return binpow(x, MODULO - 2); } private static long binpow(long base, long power) { if (power == 0) return 1; if ((power & 1) == 0) { long half = binpow(base, power >> 1); return mult(half, half); } else { long prev = binpow(base, power - 1); return mult(prev, base); } } private static long add(long a, long b) { return (a + b) % MODULO; } @SuppressWarnings("unused") private static long subtract(long a, long b) { return add(a, MODULO - b % MODULO); } private static long mult(long a, long b) { return (a * b) % MODULO; } ///////////////////////////////////////////////////////////////////// @SuppressWarnings("unused") void yesNo(boolean yes) { out.println(yes ? "YES" : "NO"); } ///////////////////////////////////////////////////////////////////// public void run(){ try{ timeInit(); Locale.setDefault(Locale.US); init(); if (ONLINE_JUDGE) { solve(); } else { do { try { timeInit(); solve(); time(); out.println(); out.flush(); } catch (NumberFormatException | EOFException e) { break; } } while (MULTIPLE_TESTS); } out.close(); time(); }catch (Exception e){ e.printStackTrace(System.err); System.exit(-1); } } ///////////////////////////////////////////////////////////////////// private BufferedReader in; private OutputWriter out; private StringTokenizer tok = new StringTokenizer(""); public static void main(String[] args){ new Thread(null, new D(), "", MAX_STACK_SIZE * (1L << 20)).start(); } ///////////////////////////////////////////////////////////////////// private void init() throws FileNotFoundException{ Locale.setDefault(Locale.US); if (ONLINE_JUDGE){ if (fileName.isEmpty()) { in = new BufferedReader(new InputStreamReader(System.in)); out = new OutputWriter(System.out); } else { in = new BufferedReader(new FileReader(fileName + ".in")); out = new OutputWriter(fileName + ".out"); } }else{ in = new BufferedReader(new FileReader("input.txt")); out = new OutputWriter("output.txt"); } } //////////////////////////////////////////////////////////////// private long timeBegin; private void timeInit() { this.timeBegin = System.currentTimeMillis(); } private void time(){ long timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } @SuppressWarnings("unused") private void debug(Object... objects){ if (ONLINE_JUDGE){ for (Object o: objects){ System.err.println(o.toString()); } } } ///////////////////////////////////////////////////////////////////// private String delim = " "; private String readNullableLine() { try { return in.readLine(); } catch (IOException e) { throw new RuntimeIOException(e); } } private String readLine() { String line = readNullableLine(); if (null == line) throw new EOFException(); return line; } private String readString() { while(!tok.hasMoreTokens()){ tok = new StringTokenizer(readLine(), delim); } return tok.nextToken(delim); } ///////////////////////////////////////////////////////////////// private final char NOT_A_SYMBOL = '\0'; @SuppressWarnings("unused") private char readChar() { try { int intValue = in.read(); if (intValue == -1){ return NOT_A_SYMBOL; } return (char) intValue; } catch (IOException e) { throw new RuntimeIOException(e); } } private char[] readCharArray() { return readLine().toCharArray(); } @SuppressWarnings("unused") private char[][] readCharField(int rowsCount) { char[][] field = new char[rowsCount][]; for (int row = 0; row < rowsCount; ++row) { field[row] = readCharArray(); } return field; } ///////////////////////////////////////////////////////////////// private long optimizedReadLong() { int sign = 1; long result = 0; boolean started = false; while (true) { try { int j = in.read(); if (-1 == j) { if (started) return sign * result; throw new NumberFormatException(); } if (j == '-') { if (started) throw new NumberFormatException(); sign = -sign; } if ('0' <= j && j <= '9') { result = result * 10 + j - '0'; started = true; } else if (started) { return sign * result; } } catch (IOException e) { throw new RuntimeIOException(e); } } } private int readInt() { if (!OPTIMIZE_READ_NUMBERS) { return Integer.parseInt(readString()); } else { return (int) optimizedReadLong(); } } private int[] readIntArray(int size) { int[] array = new int[size]; for (int index = 0; index < size; ++index){ array[index] = readInt(); } return array; } @SuppressWarnings("unused") private int[] readSortedIntArray(int size) { Integer[] array = new Integer[size]; for (int index = 0; index < size; ++index) { array[index] = readInt(); } Arrays.sort(array); int[] sortedArray = new int[size]; for (int index = 0; index < size; ++index) { sortedArray[index] = array[index]; } return sortedArray; } private int[] readIntArrayWithDecrease(int size) { int[] array = readIntArray(size); for (int i = 0; i < size; ++i) { array[i]--; } return array; } /////////////////////////////////////////////////////////////////// @SuppressWarnings("unused") private int[][] readIntMatrix(int rowsCount, int columnsCount) { int[][] matrix = new int[rowsCount][]; for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) { matrix[rowIndex] = readIntArray(columnsCount); } return matrix; } @SuppressWarnings("unused") private int[][] readIntMatrixWithDecrease(int rowsCount, int columnsCount) { int[][] matrix = new int[rowsCount][]; for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) { matrix[rowIndex] = readIntArrayWithDecrease(columnsCount); } return matrix; } /////////////////////////////////////////////////////////////////// private long readLong() { if (!OPTIMIZE_READ_NUMBERS) { return Long.parseLong(readString()); } else { return optimizedReadLong(); } } @SuppressWarnings("unused") private long[] readLongArray(int size) { long[] array = new long[size]; for (int index = 0; index < size; ++index){ array[index] = readLong(); } return array; } //////////////////////////////////////////////////////////////////// private double readDouble() { return Double.parseDouble(readString()); } @SuppressWarnings("unused") private double[] readDoubleArray(int size) { double[] array = new double[size]; for (int index = 0; index < size; ++index){ array[index] = readDouble(); } return array; } //////////////////////////////////////////////////////////////////// @SuppressWarnings("unused") private BigInteger readBigInteger() { return new BigInteger(readString()); } @SuppressWarnings("unused") private BigDecimal readBigDecimal() { return new BigDecimal(readString()); } ///////////////////////////////////////////////////////////////////// private Point readPoint() { int x = readInt(); int y = readInt(); return new Point(x, y); } @SuppressWarnings("unused") private Point[] readPointArray(int size) { Point[] array = new Point[size]; for (int index = 0; index < size; ++index){ array[index] = readPoint(); } return array; } ///////////////////////////////////////////////////////////////////// @Deprecated @SuppressWarnings("unused") private List<Integer>[] readGraph(int vertexNumber, int edgeNumber) { @SuppressWarnings("unchecked") List<Integer>[] graph = new List[vertexNumber]; for (int index = 0; index < vertexNumber; ++index){ graph[index] = new ArrayList<>(); } while (edgeNumber-- > 0){ int from = readInt() - 1; int to = readInt() - 1; graph[from].add(to); graph[to].add(from); } return graph; } private static class GraphBuilder { final int size; final List<Integer>[] edges; static GraphBuilder createInstance(int size) { @SuppressWarnings("unchecked") List<Integer>[] edges = new List[size]; for (int v = 0; v < size; ++v) { edges[v] = new ArrayList<>(); } return new GraphBuilder(edges); } private GraphBuilder(List<Integer>[] edges) { this.size = edges.length; this.edges = edges; } public void addEdge(int from, int to) { addDirectedEdge(from, to); addDirectedEdge(to, from); } public void addDirectedEdge(int from, int to) { edges[from].add(to); } public int[][] build() { int[][] graph = new int[size][]; for (int v = 0; v < size; ++v) { List<Integer> vEdges = edges[v]; graph[v] = castInt(vEdges); } return graph; } } @SuppressWarnings("unused") private final static int ZERO_INDEXATION = 0, ONE_INDEXATION = 1; @SuppressWarnings("unused") private int[][] readUnweightedGraph(int vertexNumber, int edgesNumber) { return readUnweightedGraph(vertexNumber, edgesNumber, ONE_INDEXATION, false); } private int[][] readUnweightedGraph(int vertexNumber, int edgesNumber, int indexation, boolean directed ) { GraphBuilder graphBuilder = GraphBuilder.createInstance(vertexNumber); for (int i = 0; i < edgesNumber; ++i) { int from = readInt() - indexation; int to = readInt() - indexation; if (directed) graphBuilder.addDirectedEdge(from, to); else graphBuilder.addEdge(from, to); } return graphBuilder.build(); } private static class Edge { int to; int w; Edge(int to, int w) { this.to = to; this.w = w; } } @SuppressWarnings("unused") private Edge[][] readWeightedGraph(int vertexNumber, int edgesNumber) { return readWeightedGraph(vertexNumber, edgesNumber, ONE_INDEXATION, false); } private Edge[][] readWeightedGraph(int vertexNumber, int edgesNumber, int indexation, boolean directed) { @SuppressWarnings("unchecked") List<Edge>[] graph = new List[vertexNumber]; for (int v = 0; v < vertexNumber; ++v) { graph[v] = new ArrayList<>(); } while (edgesNumber --> 0) { int from = readInt() - indexation; int to = readInt() - indexation; int w = readInt(); graph[from].add(new Edge(to, w)); if (!directed) graph[to].add(new Edge(from, w)); } Edge[][] graphArrays = new Edge[vertexNumber][]; for (int v = 0; v < vertexNumber; ++v) { graphArrays[v] = graph[v].toArray(new Edge[0]); } return graphArrays; } ///////////////////////////////////////////////////////////////////// private static class IntIndexPair { @SuppressWarnings("unused") static Comparator<IntIndexPair> increaseComparator = (indexPair1, indexPair2) -> { int value1 = indexPair1.value; int value2 = indexPair2.value; if (value1 != value2) { return value1 - value2; } int index1 = indexPair1.index; int index2 = indexPair2.index; return index1 - index2; }; @SuppressWarnings("unused") static Comparator<IntIndexPair> decreaseComparator = (indexPair1, indexPair2) -> { int value1 = indexPair1.value; int value2 = indexPair2.value; if (value1 != value2) { return -(value1 - value2); } int index1 = indexPair1.index; int index2 = indexPair2.index; return index1 - index2; }; @SuppressWarnings("unused") static IntIndexPair[] from(int[] array) { IntIndexPair[] iip = new IntIndexPair[array.length]; for (int i = 0; i < array.length; ++i) { iip[i] = new IntIndexPair(array[i], i); } return iip; } int value, index; IntIndexPair(int value, int index) { super(); this.value = value; this.index = index; } @SuppressWarnings("unused") int getRealIndex() { return index + 1; } } @SuppressWarnings("unused") private IntIndexPair[] readIntIndexArray(int size) { IntIndexPair[] array = new IntIndexPair[size]; for (int index = 0; index < size; ++index) { array[index] = new IntIndexPair(readInt(), index); } return array; } ///////////////////////////////////////////////////////////////////// private static class OutputWriter extends PrintWriter { final int DEFAULT_PRECISION = 12; private int precision; private String format, formatWithSpace; { precision = DEFAULT_PRECISION; format = createFormat(precision); formatWithSpace = format + " "; } OutputWriter(OutputStream out) { super(out); } OutputWriter(String fileName) throws FileNotFoundException { super(fileName); } int getPrecision() { return precision; } void setPrecision(int precision) { precision = max(0, precision); this.precision = precision; format = createFormat(precision); formatWithSpace = format + " "; } String createFormat(int precision){ return "%." + precision + "f"; } @Override public void print(double d){ printf(format, d); } @Override public void println(double d){ print(d); println(); } void printWithSpace(double d){ printf(formatWithSpace, d); } void printAll(double...d){ for (int i = 0; i < d.length - 1; ++i){ printWithSpace(d[i]); } print(d[d.length - 1]); } @SuppressWarnings("unused") void printlnAll(double... d){ printAll(d); println(); } void printAll(int... array) { for (int value : array) { print(value + " "); } } @SuppressWarnings("unused") void printlnAll(int... array) { printAll(array); println(); } void printAll(long... array) { for (long value : array) { print(value + " "); } } @SuppressWarnings("unused") void printlnAll(long... array) { printAll(array); println(); } } ///////////////////////////////////////////////////////////////////// private static class EOFException extends RuntimeException { EOFException() { super(); } } private static class RuntimeIOException extends RuntimeException { /** * */ private static final long serialVersionUID = -6463830523020118289L; RuntimeIOException(Throwable cause) { super(cause); } } ///////////////////////////////////////////////////////////////////// //////////////// Some useful constants andTo functions //////////////// ///////////////////////////////////////////////////////////////////// private static void swap(int[] array, int i, int j) { if (i != j) { int tmp = array[i]; array[i] = array[j]; array[j] = tmp; } } private static <T> void swap(T[] array, int i, int j) { if (i != j) { T tmp = array[i]; array[i] = array[j]; array[j] = tmp; } } private static final int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; private static final int[][] steps8 = { {-1, 0}, {1, 0}, {0, -1}, {0, 1}, {-1, -1}, {1, 1}, {1, -1}, {-1, 1} }; @SuppressWarnings("unused") private static boolean checkCell(int row, int rowsCount, int column, int columnsCount) { return checkIndex(row, rowsCount) && checkIndex(column, columnsCount); } private static boolean checkIndex(int index, int lim){ return (0 <= index && index < lim); } ///////////////////////////////////////////////////////////////////// private static int getBit(long mask, int bit) { return (int)((mask >> bit) & 1); } @SuppressWarnings("unused") private static boolean checkBit(long mask, int bit){ return getBit(mask, bit) != 0; } ///////////////////////////////////////////////////////////////////// @SuppressWarnings("unused") private static long getSum(int[] array) { long sum = 0; for (int value: array) { sum += value; } return sum; } @SuppressWarnings("unused") private static Point getMinMax(int[] array) { int min = array[0]; int max = array[0]; for (int index = 0, size = array.length; index < size; ++index, ++index) { int value = array[index]; if (index == size - 1) { min = min(min, value); max = max(max, value); } else { int otherValue = array[index + 1]; if (value <= otherValue) { min = min(min, value); max = max(max, otherValue); } else { min = min(min, otherValue); max = max(max, value); } } } return new Point(min, max); } ///////////////////////////////////////////////////////////////////// @SuppressWarnings("unused") private static boolean isPrime(int x) { if (x < 2) return false; for (int d = 2; d * d <= x; ++d) { if (x % d == 0) return false; } return true; } @SuppressWarnings("unused") private static int[] getPrimes(int n) { boolean[] used = new boolean[n]; used[0] = used[1] = true; int size = 0; for (int i = 2; i < n; ++i) { if (!used[i]) { ++size; for (int j = 2 * i; j < n; j += i) { used[j] = true; } } } int[] primes = new int[size]; for (int i = 0, cur = 0; i < n; ++i) { if (!used[i]) { primes[cur++] = i; } } return primes; } ///////////////////////////////////////////////////////////////////// @SuppressWarnings("unused") int[] getDivisors(int value) { List<Integer> divisors = new ArrayList<>(); for (int divisor = 1; divisor * divisor <= value; ++divisor) { if (value % divisor == 0) { divisors.add(divisor); if (divisor * divisor != value) { divisors.add(value / divisor); } } } return castInt(divisors); } @SuppressWarnings("unused") long[] getDivisors(long value) { List<Long> divisors = new ArrayList<>(); for (long divisor = 1; divisor * divisor <= value; ++divisor) { if (value % divisor == 0) { divisors.add(divisor); if (divisor * divisor != value) { divisors.add(value / divisor); } } } return castLong(divisors); } ///////////////////////////////////////////////////////////////////// @SuppressWarnings("unused") private static long lcm(long a, long b) { return a / gcd(a, b) * b; } private static long gcd(long a, long b) { return (a == 0 ? b : gcd(b % a, a)); } ///////////////////////////////////////////////////////////////////// private static int[] castInt(List<Integer> list) { int[] array = new int[list.size()]; for (int i = 0; i < array.length; ++i) { array[i] = list.get(i); } return array; } @SuppressWarnings("unused") private static long[] castLong(List<Long> list) { long[] array = new long[list.size()]; for (int i = 0; i < array.length; ++i) { array[i] = list.get(i); } return array; } ///////////////////////////////////////////////////////////////////// /** * Generates list with keys 0..<bowlsCount * @param n - exclusive limit of sequence */ @SuppressWarnings("unused") private static List<Integer> order(int n) { List<Integer> sequence = new ArrayList<>(); for (int i = 0; i < n; ++i) { sequence.add(i); } return sequence; } @SuppressWarnings("unused") private static List<Integer> shuffled(List<Integer> list) { Collections.shuffle(list, rnd); return list; } }
Java
["3\n1 1\n3 1 2", "3\n1 1\n3 1 3"]
1 second
["3", "4"]
NoteIn the first example the citizens on the square $$$1$$$ can split into two groups $$$2 + 1$$$, so that the second and on the third squares will have $$$3$$$ citizens each.In the second example no matter how citizens act the bandit can catch at least $$$4$$$ citizens.
Java 8
standard input
[ "greedy", "graphs", "binary search", "dfs and similar", "trees" ]
18cf79b50d0a389e6c3afd5d2f6bd9ed
The first line contains a single integer $$$n$$$ — the number of squares in the city ($$$2 \le n \le 2\cdot10^5$$$). The second line contains $$$n-1$$$ integers $$$p_2, p_3 \dots p_n$$$ meaning that there is a one-way road from the square $$$p_i$$$ to the square $$$i$$$ ($$$1 \le p_i &lt; i$$$). The third line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ — the number of citizens on each square initially ($$$0 \le a_i \le 10^9$$$).
1,900
Print a single integer — the number of citizens the bandit will catch if both sides act optimally.
standard output
PASSED
89e154bf24627ce0bf74ab86ddb552ff
train_001.jsonl
1603548300
Bandits appeared in the city! One of them is trying to catch as many citizens as he can.The city consists of $$$n$$$ squares connected by $$$n-1$$$ roads in such a way that it is possible to reach any square from any other square. The square number $$$1$$$ is the main square.After Sunday walk all the roads were changed to one-way roads in such a way that it is possible to reach any square from the main square.At the moment when the bandit appeared on the main square there were $$$a_i$$$ citizens on the $$$i$$$-th square. Now the following process will begin. First, each citizen that is currently on a square with some outgoing one-way roads chooses one of such roads and moves along it to another square. Then the bandit chooses one of the one-way roads outgoing from the square he is located and moves along it. The process is repeated until the bandit is located on a square with no outgoing roads. The bandit catches all the citizens on that square.The bandit wants to catch as many citizens as possible; the citizens want to minimize the number of caught people. The bandit and the citizens know positions of all citizens at any time, the citizens can cooperate. If both sides act optimally, how many citizens will be caught?
256 megabytes
import java.io.*; import java.util.*; public class Main1 { public static final int mod=1000000007; public static List<Integer>[] g; public static int[] arr; public static void main(String[] args) throws IOException { //File filein = new File("input.txt"); //BufferedReader sc=new BufferedReader(new FileReader(filein)); //PrintWriter out=new PrintWriter(new FileWriter("output.txt")); //Scanner sc=new Scanner(System.in); BufferedReader sc=new BufferedReader(new InputStreamReader(System.in)); PrintWriter out=new PrintWriter(System.out); int n=Integer.parseInt(sc.readLine()); String[] ip=sc.readLine().split(" "); String[] ipp=sc.readLine().split(" "); arr=new int[n+1]; g=new LinkedList[n+1]; for(int i=0;i<=n;i++) g[i]=new LinkedList<>(); for(int i=0;i<n-1;i++){ int v=Integer.parseInt(ip[i]); g[v].add(i+2); } for(int i=0;i<n;i++) arr[i+1]=Integer.parseInt(ipp[i]); long ans[]=dfs(1); out.print(ans[2]); out.flush(); out.close(); sc.close(); } static long[] dfs(int v){ if(g[v].isEmpty()) return new long[]{arr[v],1,arr[v]}; long sum=arr[v]; int nv=0; long mx=0; for(int ver:g[v]){ long[] temp=dfs(ver); sum+=temp[0]; nv+=temp[1]; mx=Math.max(mx, temp[2]); } return new long[]{sum,nv,Math.max(mx,(long)Math.ceil((double)sum/(double)nv))}; } }
Java
["3\n1 1\n3 1 2", "3\n1 1\n3 1 3"]
1 second
["3", "4"]
NoteIn the first example the citizens on the square $$$1$$$ can split into two groups $$$2 + 1$$$, so that the second and on the third squares will have $$$3$$$ citizens each.In the second example no matter how citizens act the bandit can catch at least $$$4$$$ citizens.
Java 8
standard input
[ "greedy", "graphs", "binary search", "dfs and similar", "trees" ]
18cf79b50d0a389e6c3afd5d2f6bd9ed
The first line contains a single integer $$$n$$$ — the number of squares in the city ($$$2 \le n \le 2\cdot10^5$$$). The second line contains $$$n-1$$$ integers $$$p_2, p_3 \dots p_n$$$ meaning that there is a one-way road from the square $$$p_i$$$ to the square $$$i$$$ ($$$1 \le p_i &lt; i$$$). The third line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ — the number of citizens on each square initially ($$$0 \le a_i \le 10^9$$$).
1,900
Print a single integer — the number of citizens the bandit will catch if both sides act optimally.
standard output
PASSED
5eaad3f9e9d8235a55fe1fb49c611573
train_001.jsonl
1603548300
Bandits appeared in the city! One of them is trying to catch as many citizens as he can.The city consists of $$$n$$$ squares connected by $$$n-1$$$ roads in such a way that it is possible to reach any square from any other square. The square number $$$1$$$ is the main square.After Sunday walk all the roads were changed to one-way roads in such a way that it is possible to reach any square from the main square.At the moment when the bandit appeared on the main square there were $$$a_i$$$ citizens on the $$$i$$$-th square. Now the following process will begin. First, each citizen that is currently on a square with some outgoing one-way roads chooses one of such roads and moves along it to another square. Then the bandit chooses one of the one-way roads outgoing from the square he is located and moves along it. The process is repeated until the bandit is located on a square with no outgoing roads. The bandit catches all the citizens on that square.The bandit wants to catch as many citizens as possible; the citizens want to minimize the number of caught people. The bandit and the citizens know positions of all citizens at any time, the citizens can cooperate. If both sides act optimally, how many citizens will be caught?
256 megabytes
import java.io.*; import java.util.*; public class Main { static ArrayList<Integer> adj[]; static int k; static int[] a; static int b[]; static int m; static class Pair implements Comparable<Pair> { long a; long b; public Pair(long c, long l) { a = c; b = l; } @Override public int compareTo(Pair o) { if(o.a-o.b>this.a-this.b) return 1; else if(o.a-o.b==this.a-this.b) return 0; else { return -1; } } } static ArrayList<Pair> adjlist[]; // static char c[]; static long mod = (long) (1e9+7); static int V; static long INF = (long) 1E16; static int n; static char c[]; static Pair p[]; static int grid[][]; static class Triple{ long max; int leaves; long citizens; public Triple(long a,long l,int c) { leaves=c; max=a; citizens=l; } } public static void main(String args[]) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int n=sc.nextInt(); adj=new ArrayList[n]; for (int i = 0; i <n; i++) { adj[i]=new ArrayList<Integer>(); } for (int i = 0; i <n-1; i++) { int u=sc.nextInt()-1; adj[u].add(i+1); } cost=new long[n]; for (int i = 0; i <cost.length; i++) { cost[i]=sc.nextInt(); } vis=new boolean[n]; System.out.println(dfs(0).max); } static long cost[]; static int ans; static Triple dfs(int u) { vis[u]=true; int leaves=0; long citizens=0; long max=0; for(int v:adj[u]) { if(!vis[v]) { Triple t=dfs(v); leaves+=t.leaves; citizens+=t.citizens; max=Math.max(max,t.max); } } if(adj[u].size()!=0) { int rem=(citizens+cost[u])%leaves==0?0:1; //System.out.println(rem+" "+citizens+" "+leaves+" "+u+" "+cost[u]); return new Triple(Math.max(max,rem+((1l*citizens+cost[u])/leaves)),citizens+cost[u],leaves); } else { return new Triple(cost[u],(int) cost[u],1); } } static void update(int idx,int val) { if(idx==0) { total-=a[0]; if(idx+1<a.length) total-=Math.max(0,a[idx+1]-a[idx]); a[0]=val; total+=a[0]; if(idx+1<a.length) total+=Math.max(0,a[idx+1]-a[idx]); return; } if(idx>0) { total-=Math.max(0,a[idx]-a[idx-1]); } if(idx+1<a.length) { total-=Math.max(0,a[idx+1]-a[idx]); } a[idx]=val; if(idx>0) { total+=Math.max(0,a[idx]-a[idx-1]); } if(idx+1<a.length) { total+=Math.max(0,a[idx+1]-a[idx]); } } static int[] compreessarray(int c[]) { Stack<Integer> st=new Stack<>(); for (int i = 0; i < c.length; i++) { if(st.isEmpty()||c[i]!=st.peek()) st.add(c[i]); } b=new int[st.size()]; for (int i = b.length-1; i>=0; i--) { b[i]=st.pop(); } return b; } static int div4[]; static long [] reversearray(long a[]) { for (int i = 0; i <a.length/2; i++) { long temp=a[i]; a[i]=a[a.length-i-1]; a[a.length-i-1]=temp; } return a; } static int [] reversearray(int a[]) { for (int i = 0; i <=a.length/2; i++) { int temp=a[i]; a[i]=a[a.length-i-1]; a[a.length-i-1]=temp; } return a; } static class SegmentTree { // 1-based DS, OOP int N; //the number of elements in the array as a power of 2 (i.e. after padding) int[] array, sTree, lazy; SegmentTree(int[] in) { array = in; N = in.length - 1; sTree = new int[N<<1]; //no. of nodes = 2*N - 1, we add one to cross out index zero lazy = new int[N<<1]; build(1,1,N); } void build(int node, int b, int e) // O(n) { if(b == e) sTree[node] = array[b]; else { int mid = b + e >> 1; build(node<<1,b,mid); build(node<<1|1,mid+1,e); sTree[node] = sTree[node<<1]+sTree[node<<1|1]; } } void update_point(int index, int val) // O(log n) { index += N - 1; sTree[index] += val; while(index>1) { index >>= 1; sTree[index] = sTree[index<<1] + sTree[index<<1|1]; } } void update_range(int i, int j, int val) // O(log n) { update_range(1,1,N,i,j,val); } void update_range(int node, int b, int e, int i, int j, int val) { if(i > e || j < b) return; if(b >= i && e <= j) { sTree[node] += (e-b+1)*val; lazy[node] += val; } else { int mid = b + e >> 1; propagate(node, b, mid, e); update_range(node<<1,b,mid,i,j,val); update_range(node<<1|1,mid+1,e,i,j,val); sTree[node] = sTree[node<<1] + sTree[node<<1|1]; } } void propagate(int node, int b, int mid, int e) { lazy[node<<1] += lazy[node]; lazy[node<<1|1] += lazy[node]; sTree[node<<1] += (mid-b+1)*lazy[node]; sTree[node<<1|1] += (e-mid)*lazy[node]; lazy[node] = 0; } int query(int i, int j) { return query(1,1,N,i,j); } int query(int node, int b, int e, int i, int j) // O(log n) { if(i>e || j <b) return 0; if(b>= i && e <= j) return sTree[node]; int mid = b + e >> 1; propagate(node, b, mid, e); int q1 = query(node<<1,b,mid,i,j); int q2 = query(node<<1|1,mid+1,e,i,j); return q1 + q2; } } static TreeSet<Integer> ts=new TreeSet(); static HashMap<Integer, Integer> compress(int a[]) { ts = new TreeSet<>(); HashMap<Integer, Integer> hm = new HashMap<>(); for (int x : a) ts.add(x); for (int x : ts) { hm.put(x, hm.size() + 1); } return hm; } static class FenwickTree { // one-based DS int n; int[] ft; FenwickTree(int size) { n = size; ft = new int[n+1]; } int rsq(int b) //O(log n) { int sum = 0; while(b > 0) { sum += ft[b]; b -= b & -b;} //min? return sum; } int rsq(int a, int b) { return rsq(b) - rsq(a-1); } void point_update(int k, int val) //O(log n), update = increment { while(k <= n) { ft[k] += val; k += k & -k; } //min? } } static ArrayList<Integer> euler=new ArrayList<>(); static ArrayList<Integer> arr; static long total; static TreeMap<Integer,Integer> map1; static int zz; //static int dp(int idx,int left,int state) { //if(idx>=k-((zz-left)*2)||idx+1==n) { // return 0; //} //if(memo[idx][left][state]!=-1) { // return memo[idx][left][state]; //} //int ans=a[idx+1]+dp(idx+1,left,0); //if(left>0&&state==0&&idx>0) { // ans=Math.max(ans,a[idx-1]+dp(idx-1,left-1,1)); //} //return memo[idx][left][state]=ans; //}21 static HashMap<Integer,Integer> map; static int maxa=0; static int ff=123123; static int[][] memo; static long modmod=998244353; static int dx[]= {1,-1,0,0}; static int dy[]= {0,0,1,-1}; static class BBOOK implements Comparable<BBOOK>{ int t; int alice; int bob; public BBOOK(int x,int y,int z) { t=x; alice=y; bob=z; } @Override public int compareTo(BBOOK o) { return this.t-o.t; } } private static long lcm(long a2, long b2) { return (a2*b2)/gcd(a2,b2); } static class Edge implements Comparable<Edge> { int node;long cost ; long time; Edge(int a, long b,long c) { node = a; cost = b; time=c; } public int compareTo(Edge e){ return Long.compare(time,e.time); } } static void sieve(int N) // O(N log log N) { isComposite = new int[N+1]; isComposite[0] = isComposite[1] = 1; // 0 indicates a prime number primes = new ArrayList<Integer>(); for (int i = 2; i <= N; ++i) //can loop till i*i <= N if primes array is not needed O(N log log sqrt(N)) if (isComposite[i] == 0) //can loop in 2 and odd integers for slightly better performance { primes.add(i); if(1l * i * i <= N) for (int j = i * i; j <= N; j += i) // j = i * 2 will not affect performance too much, may alter in modified sieve isComposite[j] = 1; } } static TreeSet<Integer> factors; static TreeSet<Integer> primeFactors(int N) // O(sqrt(N) / ln sqrt(N)) { factors = new TreeSet<Integer>(); //take abs(N) in case of -ve integers int idx = 0, p = primes.get(idx); while(1l*p * p <= N) { while(N % p == 0) { factors.add(p); N /= p; } p = primes.get(++idx); } if(N != 1) // last prime factor may be > sqrt(N) factors.add(N); // for integers whose largest prime factor has a power of 1 return factors; } static class UnionFind { int[] p, rank, setSize; int numSets; int max[]; public UnionFind(int N) { p = new int[numSets = N]; rank = new int[N]; setSize = new int[N]; for (int i = 0; i < N; i++) { p[i] = i; setSize[i] = 1; } } public int findSet(int i) { return p[i] == i ? i : (p[i] = findSet(p[i])); } public boolean isSameSet(int i, int j) { return findSet(i) == findSet(j); } public int chunion(int i,int j, int x2) { if (isSameSet(i, j)) return 0; numSets--; int x = findSet(i), y = findSet(j); int z=findSet(x2); p[x]=z;; p[y]=z; return x; } public void unionSet(int i, int j) { if (isSameSet(i, j)) return; numSets--; int x = findSet(i), y = findSet(j); if (rank[x] > rank[y]) { p[y] = x; setSize[x] += setSize[y]; } else { p[x] = y; setSize[y] += setSize[x]; if (rank[x] == rank[y]) rank[y]++; } } public int numDisjointSets() { return numSets; } public int sizeOfSet(int i) { return setSize[findSet(i)]; } } static class Quad implements Comparable<Quad> { int u; int v; char state; int turns; public Quad(int i, int j, char c, int k) { u = i; v = j; state = c; turns = k; } public int compareTo(Quad e) { return (int) (turns - e.turns); } } static long manhatandistance(long x, long x2, long y, long y2) { return Math.abs(x - x2) + Math.abs(y - y2); } static long fib[]; static long fib(int n) { if (n == 1 || n == 0) { return 1; } if (fib[n] != -1) { return fib[n]; } else return fib[n] = ((fib(n - 2) % mod + fib(n - 1) % mod) % mod); } static class Point implements Comparable<Point>{ long x, y; Point(long counth, long counts) { x = counth; y = counts; } @Override public int compareTo(Point p ) { return Long.compare(p.y*1l*x, p.x*1l*y); } } static TreeSet<Long> primeFactors(long N) // O(sqrt(N) / ln sqrt(N)) { TreeSet<Long> factors = new TreeSet<Long>(); // take abs(N) in case of -ve integers int idx = 0, p = primes.get(idx); while (p * p <= N) { while (N % p == 0) { factors.add((long) p); N /= p; } if (primes.size() > idx + 1) p = primes.get(++idx); else break; } if (N != 1) // last prime factor may be > sqrt(N) factors.add(N); // for integers whose largest prime factor has a power of 1 return factors; } static boolean visited[]; /** * static int bfs(int s) { Queue<Integer> q = new LinkedList<Integer>(); * q.add(s); int count=0; int maxcost=0; int dist[]=new int[n]; dist[s]=0; * while(!q.isEmpty()) { * * int u = q.remove(); if(dist[u]==k) { break; } for(Pair v: adj[u]) { * maxcost=Math.max(maxcost, v.cost); * * * * if(!visited[v.v]) { * * visited[v.v]=true; q.add(v.v); dist[v.v]=dist[u]+1; maxcost=Math.max(maxcost, * v.cost); } } * * } return maxcost; } **/ static boolean[] vis2; static boolean f2 = false; static long[][] matMul(long[][] a2, long[][] b, int p, int q, int r) // C(p x r) = A(p x q) x (q x r) -- O(p x q x // r) { long[][] C = new long[p][r]; for (int i = 0; i < p; ++i) { for (int j = 0; j < r; ++j) { for (int k = 0; k < q; ++k) { C[i][j] = (C[i][j] + (a2[i][k] % mod * b[k][j] % mod)) % mod; C[i][j] %= mod; } } } return C; } public static int[] schuffle(int[] a2) { for (int i = 0; i < a2.length; i++) { int x = (int) (Math.random() * a2.length); int temp = a2[x]; a2[x] = a2[i]; a2[i] = temp; } return a2; } static boolean vis[]; static HashSet<Integer> set = new HashSet<Integer>(); static long modPow(long ways, long count, long mod) // O(log e) { ways %= mod; long res = 1; while (count > 0) { if ((count & 1) == 1) res = (res * ways) % mod; ways = (ways * ways) % mod; count >>= 1; } return res % mod; } static long gcd(long l, long o) { if (o == 0) { return l; } return gcd(o, l % o); } static int[] isComposite; static int[] valid; static ArrayList<Integer> primes; static ArrayList<Integer> l1; static TreeSet<Integer> primus = new TreeSet<Integer>(); static void sieveLinear(int N) { int[] lp = new int[N + 1]; //lp[i] = least prime divisor of i for(int i = 2; i <= N; ++i) { if(lp[i] == 0) { primus.add(i); lp[i] = i; } int curLP = lp[i]; for(int p: primus) if(p > curLP || p * i > N) break; else lp[p * i] = i; } } public static long[] schuffle(long[] a2) { for (int i = 0; i < a2.length; i++) { int x = (int) (Math.random() * a2.length); long temp = a2[x]; a2[x] = a2[i]; a2[i] = temp; } return a2; } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } public int[] nxtArr(int n) throws IOException { int[] ans = new int[n]; for (int i = 0; i < n; i++) ans[i] = nextInt(); return ans; } } public static int[] sortarray(int a[]) { schuffle(a); Arrays.sort(a); return a; } public static long[] sortarray(long a[]) { schuffle(a); Arrays.sort(a); return a; } }
Java
["3\n1 1\n3 1 2", "3\n1 1\n3 1 3"]
1 second
["3", "4"]
NoteIn the first example the citizens on the square $$$1$$$ can split into two groups $$$2 + 1$$$, so that the second and on the third squares will have $$$3$$$ citizens each.In the second example no matter how citizens act the bandit can catch at least $$$4$$$ citizens.
Java 8
standard input
[ "greedy", "graphs", "binary search", "dfs and similar", "trees" ]
18cf79b50d0a389e6c3afd5d2f6bd9ed
The first line contains a single integer $$$n$$$ — the number of squares in the city ($$$2 \le n \le 2\cdot10^5$$$). The second line contains $$$n-1$$$ integers $$$p_2, p_3 \dots p_n$$$ meaning that there is a one-way road from the square $$$p_i$$$ to the square $$$i$$$ ($$$1 \le p_i &lt; i$$$). The third line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ — the number of citizens on each square initially ($$$0 \le a_i \le 10^9$$$).
1,900
Print a single integer — the number of citizens the bandit will catch if both sides act optimally.
standard output
PASSED
6f0267ba68ec2049ef4def2098cead9a
train_001.jsonl
1603548300
Bandits appeared in the city! One of them is trying to catch as many citizens as he can.The city consists of $$$n$$$ squares connected by $$$n-1$$$ roads in such a way that it is possible to reach any square from any other square. The square number $$$1$$$ is the main square.After Sunday walk all the roads were changed to one-way roads in such a way that it is possible to reach any square from the main square.At the moment when the bandit appeared on the main square there were $$$a_i$$$ citizens on the $$$i$$$-th square. Now the following process will begin. First, each citizen that is currently on a square with some outgoing one-way roads chooses one of such roads and moves along it to another square. Then the bandit chooses one of the one-way roads outgoing from the square he is located and moves along it. The process is repeated until the bandit is located on a square with no outgoing roads. The bandit catches all the citizens on that square.The bandit wants to catch as many citizens as possible; the citizens want to minimize the number of caught people. The bandit and the citizens know positions of all citizens at any time, the citizens can cooperate. If both sides act optimally, how many citizens will be caught?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.PriorityQueue; import java.util.Random; import java.util.StringTokenizer; public class D { private static ArrayList<Integer>[] adj; private static long[] a; public static void main(String[] args) throws IOException { FastScanner sc = new FastScanner(); int n = sc.nextInt(); adj = new ArrayList[n+1]; for(int i=1; i<=n; i++)adj[i] = new ArrayList<Integer>(); for(int i=2; i<=n; i++) { int p = sc.nextInt(); adj[p].add(i); } a = new long[n+1]; for(int i=1; i<=n; i++)a[i] = sc.nextLong(); long ans = dfs(1)[2]; System.out.println(ans); } private static long[] dfs(int z) { long tmp[] = {0,0,0}; long mx = 0; long extra = 0; ArrayList<ArrayList<Long>> vec = new ArrayList<ArrayList<Long>>(); for(int x:adj[z]){ long[] tmp2 = dfs(x); ArrayList<Long> lis = new ArrayList<Long>(); for(Long e : tmp2)lis.add(e); mx = max(mx, tmp2[2]); tmp[0] += tmp2[0]; vec.add(lis); } for(ArrayList<Long> tmp2:vec){ extra += tmp2.get(1) + tmp2.get(0) * (mx - tmp2.get(2)); } if(adj[z].isEmpty()) tmp[0]++; tmp[2] = mx; // a[z] people can travel down long people = min(a[z],extra); extra -= people; long rem = a[z] - people; if(rem == 0){ tmp[1] = extra; } else{ long new_max = tmp[2] + (rem + tmp[0] - 1) / tmp[0]; tmp[1] = tmp[0] - rem % tmp[0]; if(tmp[1] == tmp[0]) tmp[1] = 0; tmp[2] = new_max; } return tmp; } static void shuffleSort(int[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); int temp = a[i]; a[i] = a[r]; a[r] = temp; } } static void shuffleSort(long[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); long temp = a[i]; a[i] = a[r]; a[r] = temp; } } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] readArrayLong(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static int ceil(int x, int y) { return (x % y == 0 ? x / y : (x / y + 1)); } static long ceil(long x, long y) { return (x % y == 0 ? x / y : (x / y + 1)); } static int max(int x, int y) { return Math.max(x, y); } static int min(int x, int y) { return Math.min(x, y); } static long max(long x, long y) { return Math.max(x, y); } static long min(long x, long y) { return Math.min(x, y); } static int min(int a[]) { int x = 1_000_000_00_9; for (int i = 0; i < a.length; i++) x = min(x, a[i]); return x; } static int max(int a[]) { int x = -1_000_000_00_9; for (int i = 0; i < a.length; i++) x = max(x, a[i]); return x; } static long min(long a[]) { long x = (long) 3e18; for (int i = 0; i < a.length; i++) x = min(x, a[i]); return x; } static long max(long a[]) { long x = -(long) 3e18; for (int i = 0; i < a.length; i++) x = max(x, a[i]); return x; } static int power(int x, int y) { int res = 1; while (y > 0) { if (y % 2 == 1) res = (res * x); y >>= 1; x = (x * x); } return res; } static long power(long x, long y) { long res = 1; while (y > 0) { if (y % 2 == 1) res = (res * x); y >>= 1; x = (x * x); } return res; } static long power(long x, long y, long mod) { long res = 1; x %= mod; while (y > 0) { if (y % 2 == 1) res = (res * x) % mod; y >>= 1; x = (x * x) % mod; } return res; } static void intsort(int[] a) { List<Integer> temp = new ArrayList<Integer>(); for (int i = 0; i < a.length; i++) temp.add(a[i]); Collections.sort(temp); for (int i = 0; i < a.length; i++) a[i] = temp.get(i); } static void longsort(long[] a) { List<Long> temp = new ArrayList<Long>(); for (int i = 0; i < a.length; i++) temp.add(a[i]); Collections.sort(temp); for (int i = 0; i < a.length; i++) a[i] = temp.get(i); } static void reverseintsort(int[] a) { List<Integer> temp = new ArrayList<Integer>(); for (int i = 0; i < a.length; i++) temp.add(a[i]); Collections.sort(temp); Collections.reverseOrder(); for (int i = 0; i < a.length; i++) a[i] = temp.get(i); } static void reverselongsort(long[] a) { List<Long> temp = new ArrayList<Long>(); for (int i = 0; i < a.length; i++) temp.add(a[i]); Collections.sort(temp); Collections.reverseOrder(); for (int i = 0; i < a.length; i++) a[i] = temp.get(i); } static class longpair implements Comparable<longpair> { long x, y; longpair(long x, long y) { this.x = x; this.y = y; } public int compareTo(longpair p) { return Long.compare(this.x, p.x); } } static class intpair implements Comparable<intpair> { int x, y; intpair(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(intpair o) { return Integer.compare(this.x, o.x); } // a = new pair [n]; // a[i] = new pair(coo,cost); } public static int gcd(int a, int b) { BigInteger b1 = BigInteger.valueOf(a); BigInteger b2 = BigInteger.valueOf(b); BigInteger gcd = b1.gcd(b2); return gcd.intValue(); } public static long gcd(long a, long b) { BigInteger b1 = BigInteger.valueOf(a); BigInteger b2 = BigInteger.valueOf(b); BigInteger gcd = b1.gcd(b2); return gcd.longValue(); } }
Java
["3\n1 1\n3 1 2", "3\n1 1\n3 1 3"]
1 second
["3", "4"]
NoteIn the first example the citizens on the square $$$1$$$ can split into two groups $$$2 + 1$$$, so that the second and on the third squares will have $$$3$$$ citizens each.In the second example no matter how citizens act the bandit can catch at least $$$4$$$ citizens.
Java 8
standard input
[ "greedy", "graphs", "binary search", "dfs and similar", "trees" ]
18cf79b50d0a389e6c3afd5d2f6bd9ed
The first line contains a single integer $$$n$$$ — the number of squares in the city ($$$2 \le n \le 2\cdot10^5$$$). The second line contains $$$n-1$$$ integers $$$p_2, p_3 \dots p_n$$$ meaning that there is a one-way road from the square $$$p_i$$$ to the square $$$i$$$ ($$$1 \le p_i &lt; i$$$). The third line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ — the number of citizens on each square initially ($$$0 \le a_i \le 10^9$$$).
1,900
Print a single integer — the number of citizens the bandit will catch if both sides act optimally.
standard output
PASSED
631956ff7a5d881be6ad15cdcc8594e2
train_001.jsonl
1603548300
Bandits appeared in the city! One of them is trying to catch as many citizens as he can.The city consists of $$$n$$$ squares connected by $$$n-1$$$ roads in such a way that it is possible to reach any square from any other square. The square number $$$1$$$ is the main square.After Sunday walk all the roads were changed to one-way roads in such a way that it is possible to reach any square from the main square.At the moment when the bandit appeared on the main square there were $$$a_i$$$ citizens on the $$$i$$$-th square. Now the following process will begin. First, each citizen that is currently on a square with some outgoing one-way roads chooses one of such roads and moves along it to another square. Then the bandit chooses one of the one-way roads outgoing from the square he is located and moves along it. The process is repeated until the bandit is located on a square with no outgoing roads. The bandit catches all the citizens on that square.The bandit wants to catch as many citizens as possible; the citizens want to minimize the number of caught people. The bandit and the citizens know positions of all citizens at any time, the citizens can cooperate. If both sides act optimally, how many citizens will be caught?
256 megabytes
// No sorcery shall prevail. // import java.util.*; import java.io.*; public class _InVoker_ { //Variables static long mod = 1000000007; static long mod2 = 998244353; static FastReader inp= new FastReader(); static PrintWriter out= new PrintWriter(System.out); public static void main(String args[]) { _InVoker_ g=new _InVoker_(); g.main(); out.close(); } ArrayList<Integer> list[]; long dp[]; int leaves[]; long a[]; long gg=0; //Main void main() { int n=inp.nextInt(); list=new ArrayList[n]; for(int i=0;i<n;i++) list[i]=new ArrayList<>(); for(int i=1;i<n;i++) { int x=inp.nextInt()-1; list[x].add(i); list[i].add(x); } dp=new long[n]; leaves=new int[n]; a=new long[n]; input(a,n); dfs(0,-1); out.println(gg); } void dfs(int i, int parent) { long sum=a[i]; int leafs=0; //intentional wrong spelling, don't judge on grammar ty for(int x: list[i]) { if(x==parent) continue; dfs(x,i); sum+=dp[x]; leafs+=leaves[x]; } dp[i]=sum; if(list[i].size()==1 && list[i].get(0)==parent) leafs++; leaves[i]=leafs; gg=Math.max(gg, (dp[i]+leaves[i]-1)/leaves[i]); } /********************************************************************************************************************************************************************************************************* * ti;. .:,:i: :,;;itt;. fDDEDDEEEEEEKEEEEEKEEEEEEEEEEEEEEEEE###WKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWWWWWWWW#WWWWWKKKKKEE :,:. f::::. .,ijLGDDDDDDDEEEEEEE* *ti;. .:,:i: .:,;itt;: GLDEEGEEEEEEEEEEEEEEEEEEDEEEEEEEEEEE#W#WEKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWWWWWWWWWWWKKKKKKG. .::. f:,...,ijLGDDDDDDDDEEEEEE * *ti;. .:,:i: :,;;iti, :fDDEEEEEEEEEEEEEEEKEEEEDEEEEEEEEEEEW##WEEEKKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWWWWWWWWWWWWKKKKKKEG .::. .f,::,ijLGDDDDDDDDEEEEEE * *ti;. .:,:i: .,,;iti;. LDDEEEEEEEEEEKEEEEWEEEDDEEEEEEEEEEE#WWWEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWWWWWWWWKKKKKEDj .::. .:L;;ijfGDDDDDDDDDEEEEE * *ti;. .:,:i: .:,;;iii:LLDEEEEEEEEEEEKEEEEEEEEDEEEEEEEEEEEW#WWEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKWWKWWWWWWWWWWWWWWKKKKKKKEL .::. .:;LijLGGDDDDDDDDEEEEE * *ti;. .:,:;: :,;;ittfDEEEEEEEEEEEEEEEEKEEEGEEEEEEEEEEEKWWWEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWWWWKKKKKKKELj .::. :,;jffGGDDDDDDDDDEEEE * *ti;. .:,:i: .,;;tGGDEEEEEEEEEEEKEEEKEEEDEEEEEEEEEEEEWWWEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWWKWWWWWWKKKKKKKEEL .::. .:;itDGGDDDDDDDDDEEEE * *ti;. .:::;: :;ifDEEEEEEEEEEEEKEEEKEEEEEEEEEEEEEEEWWWEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKW#WWWKKKKKKKKEEf .::. :,itfGEDDDDDDDDDDDEE * *ti;. .:::;: :GGEEEEEEEEEEEKEKEEKEEEEEEEEEEEEEEEEWWEEEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKW#WKKKKKKKKKEEDG .::. .,;jfLGKDLDDDDDDEEDD * *ti;. .:::;: fDEEEEEEKKKKKKKKKEKEEEEEEEEEEEEEEE#WEEEEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKW#KKKKKKKKKKEEf .:::. .,;tfLGDEDDDDDDDDEEE * *ti;. :::;: fDEEEEEEKKKKKKKKKKWKEEEEEEEEEEEEEEEWKEEEEEEEEEEEEEEEEEEEEKEKKKKKKKKKKKKKKKKKKKKKKKKKKKKW##KKKKKKKKKEEft :::. .,;tfLGDDDKDDDDDDDDD * *ti;. .::;: fDEEEEEEKKKKKKKWKKKKKEEEEEEEEEEEEE#WEEWEEEEEDEEDEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKW#WKKKKKKKKEEGG :,:. .,;tfLGGDDDKDDDDDDDD * *ti;. .:.;: tGDEEEEKKKKKKKKKKKKKKKKKEEEEEEEEEEEWEEKWEEEEEEEDEEEEEEEEEEEEEEKEKKKKKKKKKKKKKKKKKKKKKKKKKKWWWKKKKKKKEEDf :::. .,;tfLGGDDDDEDDDDDDD * *ti;. .::;: fDEEEEEKKKKKKKKKKKWKKKKKKKKEEEEEEEWWEEWEEEEEEEEEEEEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKW##KKKKKKKEEEft.::. .,;tfLGGDDDDDDEDDDDD * *ti;. .:.;: tGDEEEKKKKKKKKKKKKKKKKKKKKKKEKEEEEE#EEWWEEEEEEEEEEEEEEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKW#WKKKKKKEEEGD:::. .,;tfLGGDDDDDDDEDDDD * *ti;. .:.,. LDEEEEKKKKKKKKKKWKWKKKKKKKKKKKKEEEKWEKW#EEEEEEEEEEEEEEEEKEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKW##KKKKKKEEEEf,,:. .,;tfLGGDDDDDDDDEDDD * *ti;. ..:.,. LGDEEEEKKKKKKKKKKWKKKKKKKKKKKKKKKKKWEEW#WEEEEEEEEEEEEEEEKEEEEEEEEEEEEEEEEEEEKEKKKKKKKKKKKKKKKK##KKKKKEEEEEfi;,. .,;tfLGGDDDDDDDDDKDD * *tt;. .:.,: jDEEEEKKKKKKKKKKWWKKKKKKKKKKKKKKKKKWKE#WWEEEEEEEEEEEEEEWEEEEEEEEEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKWWKKKKEEEEDfG;,: .,;tfLGGDDDDDDDDDDKD * *tii,. .:.,. tGDEEEEKKKKKKKKKKWWWKKKKKKKKKKKKKKKWKKWWWKEEEEEEEEEEEEEKEEEEEEEEEEEEEEEEEEEEEEEEEEEEEKKKKKKKKKKKW#KKKKEEEEDGGi;,. .,;tfLGGDDDDDDDDDDDE * *ti;;,:. .:.,: fDEEEEKKKKKKKKKKKWKKKKKKKKKKKKKKKKKWEK#WWKEEEEEEEEEEEEDEEEEEEEEEEEEEEGEEEEEEEEEEEEEEEEEEEKKKKKKKWWKKEEEEEEDDf;;;,. .,;tfLGGDDDDDDDDDDDD * *tii;,,:.. ...,. ;LEEEEEKKKKKKWKKKKWKKKKKKKKKKKKKKKKKEKKW#WEEEEEEEEEEEEEjEEEEEEEEEKEEEEGEEEEEEEEEKEEEEEEEEEEEEEEEEE#WKEEEEEEDDf;;;;,: .,itfLGGDDDDDDDDDDDD * *ti;,,,,,:. ...,. LDEEEEKKKKKKKKKKKWWWKKKKKKKKKKKKKKKWKK#W#WEEEEEEEEEEEDDLEEEEEEEEEWEEEEDEEEEEEEEEKEEEEEEEEEEEEEEEEEWWEEEEEEEDDfj,,,,,:. .,itfGGGDDDDDDDDDDDD * *tii,,,,::::. ...,: .fDEEEEKKKKKKWKKKKWWWKKKKKKKKKKKKKKKEKKW#WWEEEEEEEEEEEKiKEEKEEEEEEWEEEEDEEEEEEEEEEEEEEEEEEEEEEEEEEEWWEEEEEEEDDLD:::,,,:. .,ijfGGGDDDDDDDDDDDD * *ti;:::::::::.. .:.,: LDEEEEKKKKKKKWKKKKWWKKKKKKKKKKKKKKKKtKKWWWWKEEEEEEEEEDiiDEEEEEEEEWWEEEEEEDEEEEEEEEEEEEEEEEEEEEEEEEEEWKEEEEEDDDGL:. .:,,,: .,ijLGGGDDDDDDDDDDDD * *tt;. .::::::::.. ...,: :fDEEEKKKKKKKKKKKKWW#KKKKKKKKKKKKKKKKfKKWWWWKEEEEEEEEDti,DEKEEEEEEWWEEEDEEEEEEEEEKEEEEEEEEEEEEEDEEEEE#WEEEEEGGDGf:. .:,;,:. .,ijLGGDDDDDDDDDDDDD * *tt;. .:::::::.. ...,: GDEEEKKKKKKKKWKKKKWWWKKKWKKKKKKKWWWKDEKLWWWWKKEEEEEEDEi,LDEEEEEEEEWWEEEEEEEEEEEEEEEEEEEEEEEEEDEDEEEEEW#EEEEDDDDGf,. :,,,:...,ijLGGGDDDDDDDDDDDD * *tt;. .....::::.. ...,: fDEEEKKKKKKKKWKKKKWWWWKKKWKKKKKKKKKKfWKiWWW#KKEEEEEEEi;.EDfEEEDEEiWWEEEEEEEEEEEEDGKEEEEEEEEEEDEEEEEEEWWEEEEDDDGGLi. .,;,:::,ijLGGGDDDDDDDDDDDD * *tt;. ....:::::. ...,. iDEEEEKKKKKKKKWKKWKWWWWWKKWWWKKKKKKKKtWKt#WWWKKEEEEEDji..DDKDDEDEGiWKEEEEEEEEEEDDEjEEEEEEEEEEEDEEEEEEEKWKEEDDDDGGff. .:,;,,;ijLGGGDDDDDDDDDDDD * *tt;. ....::::.. .:.,: .LDEEEKKKKKKKKKKKKWWWWKWWWWWWWWWWKKKKWtKKiDWWWKKKEEEEKi:..DEDDDDDDiiWKEEEEEEEEEEDDEijDEEEEEKEEEEEEEEEEEEWWEEGDDDGGLG. .:,;;iijLGGGDDDDDDDDDDDD * *tt;. .....:::.. ...,. .fEEEEKKKKKKKKWKKKKWWWWWWWWWWWWWWKWKKKiKDiLWWWWKEEEEEi,..fD:DDDDDti;WEEEEEEEEEEKDDi:iDDEEEEWEEEEEEEEEEEE#WEEGDDDDGGG. :,iitjLGGGDDDDDDDDDDDD * *tti. .....:::.. ...,. GDEEEKKKKKKKKKWKKKWWW#WWWWWWWWWWWKWKKjiEjitWWWKKWEEEDi...DDLDDDDji;;WEEEEEEEEEEEDEj.iDDEEEEWEEEEEEEEEEEEWWEEDDDDDDGf. .,;tjfLGGDDDDDDDDDDDD * *tti. ....::::.. ...,. fEEEKKKKKKKKKKKKKKKW#WWWWWWWWWWWWWWWWtiEiiiWWWKKEWKEi....D.EDDDEi;.fWEEEEEEEEEEDDfL.;EDDEEEWEEEEEEEEEEEEWWEEEDDDDDGf. :;ijfLGGDDDDDDDDDDDD * *tti. ....::::.. ...,. LDEEEKKKKKKKKKKKKKKWWWWWWWWWWWWWWWW####WKiiiWWWKKKEEK,...:E:DDDEii..GWEEEEEEEEDWDDiL.,KDDEEEWEEEEEEEEEEEEWWKEEDDDDDGf: .,itfLGGDDDDDDDDDDDD * *tti. .....:::.. ...,. fDEEEKKKKKKKKKWKKKKWWWWWWWWWWWWW########WLiiWWWKKKEEjD...G,DDDDi;...EWEEEEEEEEDKDEii..LDDEEEWEEEEEEEEEEEEWWWEEDDDDDGfi .,;tfLGGGDDDDDDDDDDD * *tti. .....:::.. ...,. iGEEEKKKKKKKKKKWKKKKWWWWWWWWWWWW###########KiWWWKKEEE,.D..D.DDDii:...KKEEEEEEEEEDDj:...tEDEEEWEEEEEEEEEEEEWWWEEEDDDDDLL .,;tjLLGGDDDDDDDDDDD * *tti. ....::::......:. LEEEKKKKKKKKKKWWKKKWWW#KWWWWWWWW#####W####W##KWWKKEEL..:D.jjDDi;,....KKEEEEEEEDfDDi...:iKDEEEWKEEEEEEEEEEEWWWEEEEDDDDLG .,;tjLLGGDDDDDDDDDDD * *tti. ...::::::..,. :GEEEKKKKKKKKKKKKWWWWW##WWWWWWWWW##WKWK#W#W####WWKEEK.....G.DDti,.....KKEEEEEEDWGDf.,...iKDEEEWWEEEEEEEEEEEW#WEEEEEDDDGL .,;tjLLGGDDDDDDDDDDD * *tti. ....::::::,. GDEEKKKKKKKKKKKKKWWWW###WWWWWWWWWW#WWWK###W#####WKEKK.....jDDL;;......KKEEEEEEEEEDi.f...;KDEEEWWEEEEEEEEEEEWWWWEEEEEDDGf .,;tjLLGGDDDDDDDDDDD * *tti. ....:::,,. .LEEEKKKKKWKKKKKWWWWWW###WWWWWWWWWW#WWKW#WW##W#WWWKEKD:....:DD:;......;KEEEEEEEKiDD..f...,KKEEEWWEEEEEEEEEEEWWWWEEEEEDDDf .:;tjLLGGGDDDDDDDDDD * *tti. ...::,,,:. GDEEKKKKKKKKKKKKWWWWWWW#WWWWWWWWWWW#KjKWWWWWWWWWWWWEK.j,..;fD.;.......fKEEEEEDKG:Di..,....DKEEEWWEEEEEEKEKKKWWWWEEEEEEDDf .:;tjLLGGDDDDDDDDDDD * *jti. ...::,,,,:. .fEEEKKKKKWKKKKKKWWWWWWW#WWWWWWWWWWK#KKKWWWWWWWWWWWWWK..f:.:G.,:.......EKEEEEEKK;:E:.......fKEEEWWKEKEKKKKKKKW#WWEEEEEEDDf: .,;tfLLGGDDDDDDDDDDD * *tti. ...:,,,;;,: iDEEKKKKKWKKKKKKKWWWWWWW#WWWWWWWWWWK#WDKWWKKWWWWWWWWWE..;G:G..,........KKEEEEEKi.Gi..:.....tKEEKWWWKKKKKKKKKKW##WKEEEEEEDfi .,;tfLLGGGDDDDDDDDDD * *tti. ....::,,;;;,LEEKKKKKKWKKKKKWWWWWWW###WWWWWWWWWWKWWDKWEEEWKKWWWWWKKj.:LG..;.........EKEEEEKG;.G...;.....;KKEKWWWKKKKKKKKKKW##WWKEEEEEDfL .,;tfLGGGDDDDDDDDDDD * *jti. ...::::,;ijDEEKKKKKWKKKKKKWKWWWWW##WWWWWWWWWWWKK#KKGDGDWEEWKKWKKGE,.i;.:.........:EKEEEKE;.:L...j.....,KWEKWWWKKKKKKKKKK####WKKEEEEDLG .,;tfLGGGGDDDDDDDDDD * *jti. ...:...,,;GEEKKKKKWWKKKKKWWWWWWWW###WWWWWWWWWKKKWWKiLGGEDEDEKGKKiEG..;...........jKEEEKK;:.G....,.....:KKEWWWWKKKKKKKWKK####WKKKKEEEGL .,;tfLGGGGDDDDDDDDDD * *jti. ...:. .:,GEEKKKKKWKKKKKWWWWWWWW####WWWWWWWWWKKKWWKii;fDLGDK: EEi:E:.............EKEEKK;;..L...........KKKWWWWKKKKKKKWKK####WKKKWKEEDf .,;tfGGGGDDDDDDDDDDD * *jti. ...:. ,EEKKKKKWWKKKKKWWWWWWWWW###WWWWWWWWKKKKfWWLt;i,. fi EG..D:.............EKEKK;;..t....:.......KWKWWWWKKKKKKKWKK####WKKKWEEEDf:. .,;tfGGGGDDDDDDDDDDD * *jti. ...:. GEEKKKKKWKKKKKWWWWWWWWW####WWWWWWWKKKKKt;KKEfff .;t.................KKKKi;:..GtGGfG.......KWWWWWWKKKKKKKWKK###WWWKKKKEEEf,,: .,;tfGGGGDDDDDDDDDDD * *jti. ...:. GEKKKKKWWKKKKKWWWWWWWWWW##WWWWWWWKKKKKKt;EiKKKK, ...t................jEKKG;;..,.....,LGi....KWWWWWWKKKKKKWKKKW####WKKKKKEEL,,,:. .,;tfGGGDDDDDDDDDDDD * *jti. ...:. .GEEKKKKKWKKKKKWWWWWWWWWW###WWWWWWWKKKKKKtiE::tGG........................EEEj;;...,.........:D..DKWWWWWWKKKKK#KKW###W#WKKKKKEEfj:,,,:. .,;tfGGGDDDDDDDDDDDD * *jti. ...:. DEKKKKKWWKKKKKWWWWWWWWW####WWWWWWWKKKKKKiiE:::.::.......................EEi;;...j.....f......:iDKWWWWWWKKKKK#WW######WKKKKKEELG :,,,,:. .,;tfGGGDDDDDDDDDDDD * *jti. ...:. fEEKKKKWWKKKKWWWWWWWWWWW###WWWWWWWWKKKKKK;tE::..........................DD;.;,.::......;........EWWWWWWWKKKKW#WW#####WWKKKWKKELG .:,,,:::,;tfGGGDDDDDDDDDDDD * *jti. ...:. .DEKEKKKWWKKKKWWWWWWWWWWW###WWWWWWWWKKKKKE,iD::..........................D..,;.,;tLffi...........DWDWWWW#KKKWWWWW#####W#KKKWKEEGL .:,;,,,;tfGGGDDDDDDDDDDDD * *jti. ...:. ;EEKKKKWWKKKKKWWWWWW#WWWW####WWWWWWKKKKKEL:iD:..........................j ..;..;;:.....i,........DKtWWWWWKKWWWWWW#####WWWKKKEKEDf .:,;;;itfGGGDDDDDDDDDDDD * *jti. ...:. DEKKKKKWWKKKKWWWWWWW#WWWW####WWWWWWKKKKKEj:iG...............................:....................GKiWWWWWKKWW#WWW######WWKKKKKEEf .,;iitfGGGDDDDDDDDDDDD * *jti. ...:.:EKKKKKWWKKKKKWWWWWWW#WWW#####WWWWWKWKKKKEi:if:.................................iEKEKKKKKKDj......DKiWWWWWKWK##WW#######WWKKK:KEEL .:;itfGGGDDDDDDDDDDDD * *jji. ...:,DEEKKKWWWKWKKWWWWWWWWWWWW#####WWWWWWWKKKKEi:it..................................j. KKKKKKKKKKKf..DKiWWWWWKWW##WW#######WWKKK,KEEf .,;tfGGGDDDDDDDDDDDD * *jji. ..L:iDEEKKKWWKKKKKWWWWWWWWWWWW#####WWWWWKWKKKKKi.i;.................................. . KKKWWWWWWWWK..DGiWWWWWKK##WWW#####W#WWKKKjEKEL, .:;tfGGGDDDDDDDDDDDD * *jji. .f:::EEEKKKWWWKKKKKWWWWWWWWWWWW#####WWWWWKWKKKKK;.i,.................................:: KKEKWWWWWWfWK..EiiWWWWWKWW#WW##########KKKD,KELj .:;tfGGDDDDDDDDDDDDD * *jji. .t::::,DEEKKKWWKKKKWWWWWWWWW#WWWW#####WWWWKKWKKKEK;.i:.................................GDDEEEKKKWWWWWtWWD.E;iWWWWWW###WW#########WWKKK.EEDG .:;tfGGGDDDDDDDDDDDD * *jji. . j..::::EKEKKKWWWKKKKWWWWWWWWW#WWW######WWWWKKWKKKEK;.t:.................................ELLEDDEEEWWWWEtWK,.KiiWWWWWW###W##########WWKKK:EEEG .;tjfLLGDDDDDDDDDDDDDDD * *jji. i.::::::,EEEKKWWWKKKKKWWWWWWWWW#WWW#####WWWWWKWKKKKEE,.t..................................DfiEGDDDEEKKKttKWG.KiiWWWWW##WWW##########WWKKK:fEEL ,fGGGDDDDDDDDEEEDDDDDDDDDD * *jji. .;:..:::::DEEEKKWWWKKKKKWWWWWWWWW#WWWW####WWWWWWWKKKKED,.t..................................ifjDDGGEGDKK.ttKKE.DiWWWWW###WW##########WWWKKK:.KELiLGGGGDDDDDDDDDDDDEEEDDDDDDD * *jji. i.:.::::::,KEEKKWWWKKKKKKWWWWWWWWW#WWWW####WWWWWWWKKKKEL:.j..................................GGf,;ifLLED .iiKKi:fWWWWWW##W#W##########WWWKKK:.KKLGGDDDDDDDDDDDDDDDDEDDEEDDDDD * *jji. .j:.::::::::EEEKKKWWWKKKKKKWWWWWWWW##WWW#####WWWWWWWKKKKKf:.f..................................:EEfftf .,. ;iE,..jWWWWWWW###W############WWKKK,:KKGDDDDDDDDDDDDDDDDDDDDDDDEDDDD * *jji. .:.::::::::,,EEEKKWWWKKKKKKKWWWWWWWW##WWW#####WWWWWWWKKKKKt..G....................................EEELL; .j....tKWWWWWWW################WWWKKtfGKGEDDDDDDDDDDDDDDDDDDDDDDDEEDD * *jji. :...:::::::,,jEEKKWWWWKKKKKKWWWWWWWWW##KWW#####KWWWWWWKKKKEi..D....................................:jEEE.........;KKWWWWWWWW#WW##W##########WWKKDLGKEKDDDDDDDDDDDDDDDDDDDDDDDDDED * *jji. i:.::::::::,,,EEEKKWWWWKKKKKWWWWWWWWWW##WWW#####WWWWWWWKKKKKi..D......................................:::::......,KKKWWWWWWWWW#####W########WWWKKKGGKKEGGGGGGGGDDDDDDDDDDDDDDDDDDE * *jji. i..:::::::::,,tEEKKWWWWKKKKKWWWWWWWWWWW##WW######WWWWWWWKKKKKi..D......................................::::......:EKKKWWWWWWWWWWW##WW########W#WKKWGGKKGGGGGGGGGGGGGGGDDDDDDDDDDDDD * *jji. .:::::::::::,,,EEEKKWWWWKKKKKWWWWWWWWWWW##WW#####WWWWWWWWKKKKKi..D....................................:::::::::..tELii;KWWWWWWWWWW##WW######WWWWWWKWGGGKGGGGGGGGGGGGGGGGGGGGGGGGGGDG * *jjt. :.::::::::,,,,fEEKKWWWWKKKKKKWWWWWWWWWW###WW####WWWWWWW#WKKKKKi..D....................................:::::::.:.,;;;;;;,KKWWWWWWWWW#WW########WWWKKWGGGKGGGGGGGGGGGGGGGGGGGGGGGGGGGG * *jji. ;.::::::::,,,,;EEEKWWWWWKKKKKWWWWWWWWWWWW##WW###WKWWWWWK#WKKKKKi..G......................................:::::::,;;;;:...KKKWWWWWWWWWKWW#######WWWWKKGLGKDGGGGGGLLGGGGGGGGGGGGGGGGGGG * *jjt. f.:::::::::,,,,fEEKKWWWWWKKKKKWWWWWWWWWWW###WW##WKKWWWWWW#WKKKKK;.jt........i.............................:::::::;j;;....:E.KKKWWWWWWWKWW#####W#WWWWKKLLGWEEGGGGGLGGGGGGGGGGGGGGGGGGGG * *jjt. ...:::::::,,,,,;DEEKWWWWWKKKKKWWWWWWWWWWWW####WWWKKKWWWWWWWWKKKKK;.E;.........t.............................:::::ii;;.....D...KKWWWWWWWKWW#####WWEWWWKKGGGEKKGGGGGLGGGGGGGGGGGGGLGGGGGG * *fji. ;.:::::::,,,,,;LEEKKWWWWWKKKKKWWWWWWWWWWWW####KWKKKKWWWWWWWWKKKKKi.D;..........j.............................:::tt;,.....:.....KKWWWWWWKWWWW##WWWGWWWKKGGGGKEGGGGGGGGGGGGGGGGGGGLLGGGGL * *fji. t::::::::,,,,,,;EEEKWWWWWKKKKKKKWWWWWWWWWWW##WKWKKKKKWWWWWWWWKKKKKi:D;............j...........................::LL;,.............KKWWWWWKWWWWWWWWWGWWWKKGGGGKGGGGGGGGGGGGGGGGGGGGLLGGGGL * *fjt: .:::::::,,,,,,,DEEKWWWWWWKKKKKKKWWWWWWWWWWWWKKWKKKKKKWWWWK#WWKKKKWitE;........... ............................:G;;:...............KKKWWKKWWWWWWWWWGWWWKKGGGGWGGGGGGGGGGGGGGGGGGGGGGGGGGL * *fjji;:. .f:::::::,,,,,,,;EEEKWWWWWWKKKKKKWWWWWWWWWWWKKKKKKKKKKKWWKWWWWWKKKKWGKD;........................................L;;..................DKKWKKWWWWWWWWWGWWWKKDGGGKDGGGGGGGGGGGGGGGGGGGGGGGGGG * *fjjtii;,:. :::::::,,,,,,,;EEEKWWWWWWKKKKKKWWWWWWWWWWKKKKKKKKKKKKWWWWWW#WWKKKKWiEj;......................................:i,;....,...............;KKEKWWWWWWWWWGKWWKKDDGGDEGGGDGGGGGDGGGGGGGGGGGGGGGG * *fjtiiiii;;:. j::::::,,,,,,,;;EEEKWWWWW#KKKKKWWWWWWWWWKKKKKKWKKKKKKKWWWWWWWWWKKKKWtEL;:....................................;;;:...,;j................:KEEWWWWWWWWWDDWWKKDDDDDKDDDDDDDDDDDDDDDGGGGGGGGGGG * *fjti;;iiii;;,:::::::,,,,,,,,;EEEKWWWWWWWKKKKWWWWWWWWKKKKKKKWKKKKKKKWWWWWWW#W#KKKKWEEii;...................................f;:....,;L...................EEKWWWWWWWWDDWWKKDDDDDKEDDDDDDDDDDDDDDDDDDDDDGGGG * *fjt,,,;;;;ii;f::::::,,,,,,,;;EEKWWWWWWWKKKKKWWWKWWKKKKKKKKKKKKKKKKKWWWWWWW#W#KKKKWKEij;:...............................:G;,.....,;f....................:tKKWWWWWWWDDWWKKDDDDDKKDDDDDDDDDDDDDDDDDDDDDDDDD * *jjt. ..:,;;;;,::::,,,,,,,,;;GEEWWWWWWWWKKKKWKKWKKKKKKKKKKKKKKKKKKKKWWWWWWW#W#KKKKWEDi;j;............................,Li;L;;;..,;;f........................KKKKWWWKDDWWKKDDDGDKKGGGGGGGGDGDDDDDDDDDDDDDDD * *fjt. .:,,,:::::,,,,,,,;;;EEKWWWWWWWKKKKKKWKKKKKKKKKKKKKKKKKKKKKWKKKWKW##W#KKKKWEti;;G;........................tEEEL;;;;;;;;;;L..........................DKKKKKEDDWWKEDGftiLE;;;;itjLGGGGGGDDDDDDDDDDD * *fjt. .j::::,,,,,,,;;;DEEWWWWWWWWKKKKWKKKKKKKKKKKKKKKKKKKKKKKWKKWWWK##W#KKKKKEii;;;L;...................iDEEEEEEKKi;j;;;;jD.....:......................,KKKKDGGEKKE:::::;E::::::::::,tLGGDDDDDDDDDD * *fjt. .;:::,,,,,,,;;;;EEKWWWWWWWWKWKKKKKKKKKKKKKKKWKKKKKKKKKKWKKWWWW#WW#KKKKKKii;;;;f;.............:tDEEEEEKKKKKKKKEti;;;L...............................EEKf;:iKKE::::::E::::::::::::::ifDDDDDDDDD * *fjt: :::,,,,,,,,;;;DEEWWWWWWWWWEKKKKKKKKKKKKKKKKKKKKKKKKKKWWKKWWWW####KKKKKEiii;;;;f,.........iDEEEEKKKKKKKKKKKKKKKf;iG......i..........................fK::::KKE::::::E::::::::::::::::,tGGDDDDD * *fjt: t:::,,,,,,;;;;iDEKWWWWWWKEKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWKKWWWW####WKKKKLiii;;;;;L,....,Li;EDEEEEKKKKKKKKKKKKKKKKiG......;:...........................:i:::KKE:::::,E,::::::::::::::::::iGDDDD * *jjt. f::,,,,,,,;;;;GEEWWWWKEEKEKKKKKKKKKKKKKKKKWKKKKKKKKKKKWWKWWWWW###WWKKKKiii;;;;;;;G,;L;;iiEEEEEEEKKKKKKKKKKKKKWWKE......;t.........:....................j::KEE:,::,,D,,::::,,,,,,:::::::::tDDD * *fjt:. ,::,,,,,,,;;;;EEWWKEEEEEEKKKKKKKKKKKKKKKKWKKKKKKKKKKKWWKKWWWWW#W#KKKKKKiiiiii;;;;;i;;iiiEEKEEKKWKKKKKKKWKKKKKWWWGi;...;t......,;;;;,....................:,EEE,,,,,,D,,,,,,,,,,,,,,,,::,::::tG * *fjt:. ,::,,,,,,,;;;;DEKEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWWW#W#KKKKKKiiiii;;i;;;;;iiiKKKEKKKKWWKWWWWWWKKKKWWWWW;;;:;L.....;;;;;;;;;....................,KEE,,,,,,E,,,,,,,,,,,,,,,,,,,,,,,,; * *fjt:. f:,,,,,,,;;;;jEDEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWW#W##KKKKKKiiiiiiii;i;;iiiEKKKKKKKKWKWWWWWWWWKKKWWWWWKi;;i.....,jEEfGi;;;;;...................EED,,,,,,E,,,,,,,,,,,,,,,,,,,,,,,,, * *fjt:. .f::,,,,,,;;jEEDEEEEEEEEEEKKKKKKKKKKKKKKKWKKKKKKKKKKKKKWWWKWWWWW###KKKKKLiiiiiiiiiiiiiiEEKKKKKKKKWWWWWWWWWWWWKWWWWWWGi;i;,..;jDDDKEGi;;;;;;:................EED,,,,,,D,,,,,,,,,,,,,,,,,,,,,,,,, * *fjt:. .. ;::,,,,,;;EDDEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWKKW#WW####KWKKKiiiiiiiiiiiiijKKKKKKKKKKWWWWWWWWWWWWWWWWWWWWWt;i;;;;i;DDDDDDGi;;;;;;;;:.............EDf;,,,;,G;;;;;;;;;;;;;;;,,,,,,,,,, * *fjt:......:,,,,,,;LDDDEEEEEEEEEEEKKKKKKKKKKKKKKKKWKKKKKKKKKKKKKWWWWKWWWW####KKKKKiiiiiiiiiiijKEKKWKKKKKKKWWWWWWWWWWWWWWWWWWWWWWiLiii;i;DEEEEDDE;i;;;;;;;;;:..........EDi,;;;;;L;;;;;;;;;;;;;;;;;;,,,,,,, * *fjt:......:,,,,,;EDDDEEKEEEEEEEEEKKKKKKKKKKKKKKKWKKKKKKKKKKKKKKWWWWKKWWW##W#KWKKWEiiiiiijGKKKKKWWKKKKKKKKWWWWWWWWWWWWWWWWWWWWWWKi;iiiiDDEEEEEEDEi;;;;;;;;;;;;;,:.....ED;;;;;;;j;;;;;;;;;;;;;;;;;;;;;;;,, * *fjt:.....t,,,,,;DDDDEEEKEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWWKKKWWWW##WKWKKWKiiiKKKKKKKKKWWKKKKKKKKWWWWWWWWWWWWWWW#WWWWWWWWWiiiiifLEEEEEEEEDi;i;;;;;;;;;;;;.....DD;;;;;;;i;;;;;;;;;;;;;;;;;;;;;;;;; * *fjt:.....G,,,,,GDDDEEEEEEEEEEEEKKKKKKKKKKKKKKKKWKKKKKKKKKKKKKKKWWWKKKWWW###WKWKKWKitKKKKKKKKKWKKKKKKKKKKWWWWWWWWWWWWWW###WWWWWWWWEiiiiiiiEEEEEEEEDGiiii;;;;;;;;;.....GD;;;;;;;i;;;;;;;;;;;;;;;;;;;;;;;;; * *fjt:.....L,,,,;GDDDEEEEEEEEEEKEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWDGWWW###KKWWKWKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWW####WWWWWWWWWiiiiiiiiEEEEEEEEEEDi;i;;;;;;;;.....Lj;;;;;;i;iiiiii;;;;;;ii;;;;;;;;;;; * ***********************************************************************************************************************************************************************************************************/ void sort(int a[]) { ArrayList<Integer> list=new ArrayList<>(); for(int x: a) list.add(x); Collections.sort(list); for(int i=0;i<a.length;i++) a[i]=list.get(i); } void sort(long a[]) { ArrayList<Long> list=new ArrayList<>(); for(long x: a) list.add(x); Collections.sort(list); for(int i=0;i<a.length;i++) a[i]=list.get(i); } void ruffleSort(int a[]) { Random rand=new Random(); int n=a.length; for(int i=0;i<n;i++) { int j=rand.nextInt(n); int temp=a[i]; a[i]=a[j]; a[j]=temp; } Arrays.sort(a); } void ruffleSort(long a[]) { Random rand=new Random(); int n=a.length; for(int i=0;i<n;i++) { int j=rand.nextInt(n); long temp=a[i]; a[i]=a[j]; a[j]=temp; } Arrays.sort(a); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st==null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String s=""; try { s=br.readLine(); } catch (IOException e) { e.printStackTrace(); } return s; } } long fact[]; long invFact[]; void init(int n) { fact=new long[n+1]; invFact=new long[n+1]; fact[0]=1; for(int i=1;i<=n;i++) { fact[i]=mul(i,fact[i-1]); } invFact[n]=power(fact[n],mod-2); for(int i=n-1;i>=0;i--) { invFact[i]=mul(invFact[i+1],i+1); } } long nCr(int n, int r) { if(n<r || r<0) return 0; return mul(fact[n],mul(invFact[r],invFact[n-r])); } long mul(long a, long b) { return a*b%mod; } long add(long a, long b) { return (a+b)%mod; } long power(long x, long y) { long gg=1; while(y>0) { if(y%2==1) gg=mul(gg,x); x=mul(x,x); y/=2; } return gg; } // Functions static long gcd(long a, long b) { return b==0?a:gcd(b,a%b); } static int gcd(int a, int b) { return b==0?a:gcd(b,a%b); } void print(int a[]) { int n=a.length; for(int i=0;i<n;i++) out.print(a[i]+" "); } void print(long a[]) { int n=a.length; for(int i=0;i<n;i++) out.print(a[i]+" "); } //Input Arrays static void input(long a[], int n) { for(int i=0;i<n;i++) { a[i]=inp.nextLong(); } } static void input(int a[], int n) { for(int i=0;i<n;i++) { a[i]=inp.nextInt(); } } static void input(String s[],int n) { for(int i=0;i<n;i++) { s[i]=inp.next(); } } static void input(int a[][], int n, int m) { for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { a[i][j]=inp.nextInt(); } } } static void input(long a[][], int n, int m) { for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { a[i][j]=inp.nextLong(); } } } }
Java
["3\n1 1\n3 1 2", "3\n1 1\n3 1 3"]
1 second
["3", "4"]
NoteIn the first example the citizens on the square $$$1$$$ can split into two groups $$$2 + 1$$$, so that the second and on the third squares will have $$$3$$$ citizens each.In the second example no matter how citizens act the bandit can catch at least $$$4$$$ citizens.
Java 8
standard input
[ "greedy", "graphs", "binary search", "dfs and similar", "trees" ]
18cf79b50d0a389e6c3afd5d2f6bd9ed
The first line contains a single integer $$$n$$$ — the number of squares in the city ($$$2 \le n \le 2\cdot10^5$$$). The second line contains $$$n-1$$$ integers $$$p_2, p_3 \dots p_n$$$ meaning that there is a one-way road from the square $$$p_i$$$ to the square $$$i$$$ ($$$1 \le p_i &lt; i$$$). The third line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ — the number of citizens on each square initially ($$$0 \le a_i \le 10^9$$$).
1,900
Print a single integer — the number of citizens the bandit will catch if both sides act optimally.
standard output
PASSED
21ae4420606f95456586428620cc588e
train_001.jsonl
1603548300
Bandits appeared in the city! One of them is trying to catch as many citizens as he can.The city consists of $$$n$$$ squares connected by $$$n-1$$$ roads in such a way that it is possible to reach any square from any other square. The square number $$$1$$$ is the main square.After Sunday walk all the roads were changed to one-way roads in such a way that it is possible to reach any square from the main square.At the moment when the bandit appeared on the main square there were $$$a_i$$$ citizens on the $$$i$$$-th square. Now the following process will begin. First, each citizen that is currently on a square with some outgoing one-way roads chooses one of such roads and moves along it to another square. Then the bandit chooses one of the one-way roads outgoing from the square he is located and moves along it. The process is repeated until the bandit is located on a square with no outgoing roads. The bandit catches all the citizens on that square.The bandit wants to catch as many citizens as possible; the citizens want to minimize the number of caught people. The bandit and the citizens know positions of all citizens at any time, the citizens can cooperate. If both sides act optimally, how many citizens will be caught?
256 megabytes
import java.util.*; import java.io.*; public class D_1436 { static ArrayList<Integer>[] adjList; static int[] a; public static Tuple dfs(int u) { if(adjList[u].size() == 0) return new Tuple(1, a[u], a[u]); Tuple x = new Tuple(0, 0, 0); for(int v : adjList[u]) { Tuple y = dfs(v); if(x.max >= y.max) { x.cnt += y.cnt; x.sum += y.sum; } else { x.max = y.max; x.cnt += y.cnt; x.sum += y.sum; } } long diff = 1l * x.cnt * x.max - x.sum; x.sum += a[u]; if(a[u] > diff) { x.sum += diff - a[u]; diff = a[u] - diff; long nmax = x.max + ((diff + x.cnt - 1) / x.cnt); x.max = nmax; x.sum += diff; } return x; } public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(); adjList = new ArrayList[n]; for(int i = 0; i < n; i++) adjList[i] = new ArrayList<>(); for(int i = 1; i < n; i++) adjList[sc.nextInt() - 1].add(i); a = new int[n]; a = sc.nextIntArray(n); pw.println(dfs(0).max); pw.flush(); } public static class Tuple { int cnt; long max, sum; public Tuple(int cnt, long max, long sum) { this.cnt = cnt; this.max = max; this.sum = sum; } } public static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public long nextLong() throws IOException { return Long.parseLong(next()); } public int[] nextIntArray(int n) throws IOException { int[] array = new int[n]; for (int i = 0; i < n; i++) array[i] = nextInt(); return array; } public Integer[] nextIntegerArray(int n) throws IOException { Integer[] array = new Integer[n]; for (int i = 0; i < n; i++) array[i] = new Integer(nextInt()); return array; } public long[] nextLongArray(int n) throws IOException { long[] array = new long[n]; for (int i = 0; i < n; i++) array[i] = nextLong(); return array; } public double[] nextDoubleArray(int n) throws IOException { double[] array = new double[n]; for (int i = 0; i < n; i++) array[i] = nextDouble(); return array; } public static int[] shuffle(int[] a) { int n = a.length; Random rand = new Random(); for (int i = 0; i < n; i++) { int tmpIdx = rand.nextInt(n); int tmp = a[i]; a[i] = a[tmpIdx]; a[tmpIdx] = tmp; } return a; } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } }
Java
["3\n1 1\n3 1 2", "3\n1 1\n3 1 3"]
1 second
["3", "4"]
NoteIn the first example the citizens on the square $$$1$$$ can split into two groups $$$2 + 1$$$, so that the second and on the third squares will have $$$3$$$ citizens each.In the second example no matter how citizens act the bandit can catch at least $$$4$$$ citizens.
Java 8
standard input
[ "greedy", "graphs", "binary search", "dfs and similar", "trees" ]
18cf79b50d0a389e6c3afd5d2f6bd9ed
The first line contains a single integer $$$n$$$ — the number of squares in the city ($$$2 \le n \le 2\cdot10^5$$$). The second line contains $$$n-1$$$ integers $$$p_2, p_3 \dots p_n$$$ meaning that there is a one-way road from the square $$$p_i$$$ to the square $$$i$$$ ($$$1 \le p_i &lt; i$$$). The third line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ — the number of citizens on each square initially ($$$0 \le a_i \le 10^9$$$).
1,900
Print a single integer — the number of citizens the bandit will catch if both sides act optimally.
standard output
PASSED
f97b74e62ce26b83b2fcac2229c97a62
train_001.jsonl
1603548300
Bandits appeared in the city! One of them is trying to catch as many citizens as he can.The city consists of $$$n$$$ squares connected by $$$n-1$$$ roads in such a way that it is possible to reach any square from any other square. The square number $$$1$$$ is the main square.After Sunday walk all the roads were changed to one-way roads in such a way that it is possible to reach any square from the main square.At the moment when the bandit appeared on the main square there were $$$a_i$$$ citizens on the $$$i$$$-th square. Now the following process will begin. First, each citizen that is currently on a square with some outgoing one-way roads chooses one of such roads and moves along it to another square. Then the bandit chooses one of the one-way roads outgoing from the square he is located and moves along it. The process is repeated until the bandit is located on a square with no outgoing roads. The bandit catches all the citizens on that square.The bandit wants to catch as many citizens as possible; the citizens want to minimize the number of caught people. The bandit and the citizens know positions of all citizens at any time, the citizens can cooperate. If both sides act optimally, how many citizens will be caught?
256 megabytes
import java.util.*; import java.io.*; public class Main { static Scanner sc = new Scanner(System.in); static PrintWriter out = new PrintWriter(System.out); static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); long mod = 998244353; List<Integer>[] tree; long[] sum_count, leaves; public static void main(String[] args){ Main main = new Main(); int t = 1; while(t-->0){ main.solve(); } out.flush(); } void solve(){ int n = sc.nextInt(); tree = new List[n+1]; sum_count = new long[n+1]; leaves = new long[n+1]; for(int i=0; i<=n; i++) tree[i] = new LinkedList<>(); for(int i=2; i<=n ;i++){ int p = sc.nextInt(); tree[p].add(i); } long[] a = new long[n+1]; for(int i=1; i<=n; i++) { a[i] = sc.nextLong(); } count_leaves(1, a); long ans = 0; for(int i=1; i<=n; i++){ long temp = sum_count[i]/leaves[i]; if(sum_count[i]%leaves[i]!=0) temp++; ans = Math.max(ans, temp); } out.println(ans); } long count_leaves(int cur, long[] a){ long ans = a[cur]; if(tree[cur].size()==0) leaves[cur] = 1; for(int to:tree[cur]){ long temp = count_leaves(to, a); ans += temp; leaves[cur] += leaves[to]; } return sum_count[cur] = ans; } }
Java
["3\n1 1\n3 1 2", "3\n1 1\n3 1 3"]
1 second
["3", "4"]
NoteIn the first example the citizens on the square $$$1$$$ can split into two groups $$$2 + 1$$$, so that the second and on the third squares will have $$$3$$$ citizens each.In the second example no matter how citizens act the bandit can catch at least $$$4$$$ citizens.
Java 8
standard input
[ "greedy", "graphs", "binary search", "dfs and similar", "trees" ]
18cf79b50d0a389e6c3afd5d2f6bd9ed
The first line contains a single integer $$$n$$$ — the number of squares in the city ($$$2 \le n \le 2\cdot10^5$$$). The second line contains $$$n-1$$$ integers $$$p_2, p_3 \dots p_n$$$ meaning that there is a one-way road from the square $$$p_i$$$ to the square $$$i$$$ ($$$1 \le p_i &lt; i$$$). The third line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ — the number of citizens on each square initially ($$$0 \le a_i \le 10^9$$$).
1,900
Print a single integer — the number of citizens the bandit will catch if both sides act optimally.
standard output
PASSED
589360094507811395228d9cf9aee1db
train_001.jsonl
1603548300
Bandits appeared in the city! One of them is trying to catch as many citizens as he can.The city consists of $$$n$$$ squares connected by $$$n-1$$$ roads in such a way that it is possible to reach any square from any other square. The square number $$$1$$$ is the main square.After Sunday walk all the roads were changed to one-way roads in such a way that it is possible to reach any square from the main square.At the moment when the bandit appeared on the main square there were $$$a_i$$$ citizens on the $$$i$$$-th square. Now the following process will begin. First, each citizen that is currently on a square with some outgoing one-way roads chooses one of such roads and moves along it to another square. Then the bandit chooses one of the one-way roads outgoing from the square he is located and moves along it. The process is repeated until the bandit is located on a square with no outgoing roads. The bandit catches all the citizens on that square.The bandit wants to catch as many citizens as possible; the citizens want to minimize the number of caught people. The bandit and the citizens know positions of all citizens at any time, the citizens can cooperate. If both sides act optimally, how many citizens will be caught?
256 megabytes
// package NickMikeMurderers; import java.io.*; import java.util.ArrayList; public class BanditCity { static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } static int val[]; static ArrayList<Integer> tree[]; static long max[]; static long sum[]; static long count[]; public static void main(String[] args)throws IOException { Reader s=new Reader(); int n=s.nextInt(); tree=new ArrayList[n+1]; for(int i=1;i<=n;i++){ tree[i]=new ArrayList<>(); } for(int i=2;i<=n;i++){ tree[s.nextInt()].add(i); } val=new int[n+1]; sum=new long[n+1]; count=new long[n+1]; max=new long[n+1]; for(int i=1;i<=n;i++){ val[i]=s.nextInt(); } dfs(1); System.out.println(max[1]); } public static void dfs(int curr){ if(tree[curr].size()==0){ max[curr]=val[curr]; sum[curr]=val[curr]; count[curr]=1; return; } sum[curr]=val[curr]; for(int j:tree[curr]){ dfs(j); count[curr]+=count[j]; sum[curr]+=sum[j]; max[curr]=Math.max(max[curr],max[j]); } max[curr]=Math.max(max[curr],(long)(Math.ceil(1.0*sum[curr]/count[curr]))); } }
Java
["3\n1 1\n3 1 2", "3\n1 1\n3 1 3"]
1 second
["3", "4"]
NoteIn the first example the citizens on the square $$$1$$$ can split into two groups $$$2 + 1$$$, so that the second and on the third squares will have $$$3$$$ citizens each.In the second example no matter how citizens act the bandit can catch at least $$$4$$$ citizens.
Java 8
standard input
[ "greedy", "graphs", "binary search", "dfs and similar", "trees" ]
18cf79b50d0a389e6c3afd5d2f6bd9ed
The first line contains a single integer $$$n$$$ — the number of squares in the city ($$$2 \le n \le 2\cdot10^5$$$). The second line contains $$$n-1$$$ integers $$$p_2, p_3 \dots p_n$$$ meaning that there is a one-way road from the square $$$p_i$$$ to the square $$$i$$$ ($$$1 \le p_i &lt; i$$$). The third line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ — the number of citizens on each square initially ($$$0 \le a_i \le 10^9$$$).
1,900
Print a single integer — the number of citizens the bandit will catch if both sides act optimally.
standard output
PASSED
5ab55c7c2a003ddda770096cea8a0fd3
train_001.jsonl
1603548300
Bandits appeared in the city! One of them is trying to catch as many citizens as he can.The city consists of $$$n$$$ squares connected by $$$n-1$$$ roads in such a way that it is possible to reach any square from any other square. The square number $$$1$$$ is the main square.After Sunday walk all the roads were changed to one-way roads in such a way that it is possible to reach any square from the main square.At the moment when the bandit appeared on the main square there were $$$a_i$$$ citizens on the $$$i$$$-th square. Now the following process will begin. First, each citizen that is currently on a square with some outgoing one-way roads chooses one of such roads and moves along it to another square. Then the bandit chooses one of the one-way roads outgoing from the square he is located and moves along it. The process is repeated until the bandit is located on a square with no outgoing roads. The bandit catches all the citizens on that square.The bandit wants to catch as many citizens as possible; the citizens want to minimize the number of caught people. The bandit and the citizens know positions of all citizens at any time, the citizens can cooperate. If both sides act optimally, how many citizens will be caught?
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String args[]) {new Main().run();} FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); void run(){ work(); out.flush(); } long mod=1000000007; long gcd(long a,long b) { return a==0?b:gcd(b%a,a); } ArrayList<Integer>[] graph; int n; long[] A; void work() { n=ni(); graph=(ArrayList<Integer>[])new ArrayList[n]; for(int i=0;i<n;i++){ graph[i]=new ArrayList<>(); } for(int i=1;i<n;i++){ graph[ni()-1].add(i); } A=na(n); long[] r=dfs(0); out.println(r[2]); } private long[] dfs(int node) { long[] R=new long[]{0,A[node],0}; boolean f=false; for(int nn:graph[node]){ f=true; long[] r=dfs(nn); R[0]+=r[0]; R[1]+=r[1]; R[2]=Math.max(R[2],r[2]); } if(!f)R[0]++; long v=R[1]/R[0]+1; if(R[1]%R[0]==0)v--; R[2]=Math.max(R[2],v); return R; } //input @SuppressWarnings("unused") private ArrayList<Integer>[] ng(int n, int m) { ArrayList<Integer>[] graph=(ArrayList<Integer>[])new ArrayList[n]; for(int i=0;i<n;i++) { graph[i]=new ArrayList<>(); } for(int i=1;i<=m;i++) { int s=in.nextInt()-1,e=in.nextInt()-1; graph[s].add(e); graph[e].add(s); } return graph; } private ArrayList<long[]>[] ngw(int n, int m) { ArrayList<long[]>[] graph=(ArrayList<long[]>[])new ArrayList[n]; for(int i=0;i<n;i++) { graph[i]=new ArrayList<>(); } for(int i=1;i<=m;i++) { long s=in.nextLong()-1,e=in.nextLong()-1,w=in.nextLong(); graph[(int)s].add(new long[] {e,w}); // graph[(int)e].add(new long[] {s,w}); } return graph; } private int ni() { return in.nextInt(); } private long nl() { return in.nextLong(); } private String ns() { return in.next(); } private long[] na(int n) { long[] A=new long[n]; for(int i=0;i<n;i++) { A[i]=in.nextLong(); } return A; } private int[] nia(int n) { int[] A=new int[n]; for(int i=0;i<n;i++) { A[i]=in.nextInt(); } return A; } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } public String next() { while(st==null || !st.hasMoreElements())//回车,空行情况 { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } }
Java
["3\n1 1\n3 1 2", "3\n1 1\n3 1 3"]
1 second
["3", "4"]
NoteIn the first example the citizens on the square $$$1$$$ can split into two groups $$$2 + 1$$$, so that the second and on the third squares will have $$$3$$$ citizens each.In the second example no matter how citizens act the bandit can catch at least $$$4$$$ citizens.
Java 8
standard input
[ "greedy", "graphs", "binary search", "dfs and similar", "trees" ]
18cf79b50d0a389e6c3afd5d2f6bd9ed
The first line contains a single integer $$$n$$$ — the number of squares in the city ($$$2 \le n \le 2\cdot10^5$$$). The second line contains $$$n-1$$$ integers $$$p_2, p_3 \dots p_n$$$ meaning that there is a one-way road from the square $$$p_i$$$ to the square $$$i$$$ ($$$1 \le p_i &lt; i$$$). The third line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ — the number of citizens on each square initially ($$$0 \le a_i \le 10^9$$$).
1,900
Print a single integer — the number of citizens the bandit will catch if both sides act optimally.
standard output
PASSED
ee3e1792dfecd0e976987ac5357b6097
train_001.jsonl
1603548300
Bandits appeared in the city! One of them is trying to catch as many citizens as he can.The city consists of $$$n$$$ squares connected by $$$n-1$$$ roads in such a way that it is possible to reach any square from any other square. The square number $$$1$$$ is the main square.After Sunday walk all the roads were changed to one-way roads in such a way that it is possible to reach any square from the main square.At the moment when the bandit appeared on the main square there were $$$a_i$$$ citizens on the $$$i$$$-th square. Now the following process will begin. First, each citizen that is currently on a square with some outgoing one-way roads chooses one of such roads and moves along it to another square. Then the bandit chooses one of the one-way roads outgoing from the square he is located and moves along it. The process is repeated until the bandit is located on a square with no outgoing roads. The bandit catches all the citizens on that square.The bandit wants to catch as many citizens as possible; the citizens want to minimize the number of caught people. The bandit and the citizens know positions of all citizens at any time, the citizens can cooperate. If both sides act optimally, how many citizens will be caught?
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; public class D { //-------------------------------------------------------- private static final MyScanner in = new MyScanner(System.in); private static final PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); public static void main(String[] args) throws Exception { Solver solver = new Solver(); solver.solve(); out.close(); } private static class Solver { private void visitAndCount(Node node) { node.total = node.self; if (node.childrens.isEmpty()) { node.leaves = 1; return; } node.leaves = 0; for (Node child : node.childrens) { visitAndCount(child); node.total += child.total; node.leaves += child.leaves; } } private long catchCitizens(Node node) { if (node.childrens.isEmpty()) { return node.total; } long ans = (node.total + node.leaves - 1) / node.leaves; for (Node child : node.childrens) { ans = Math.max(ans, catchCitizens(child)); } return ans; } private void solve() throws Exception { int n = in.nextInt(); Node[] nodes = new Node[n + 1]; for (int i = 1; i <= n; i++) { nodes[i] = new Node(); } for (int i = 2; i <= n; i++) { int from = in.nextInt(); nodes[from].childrens.add(nodes[i]); } for (int i = 1; i <= n; i++) { nodes[i].self = in.nextInt(); } visitAndCount(nodes[1]); out.println(catchCitizens(nodes[1])); } } private static class Node { long self; List<Node> childrens = new ArrayList<>(); long leaves; long total; } public static class MyScanner { private final BufferedReader br; private StringTokenizer st; public MyScanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); } String next() throws IOException { while (st == null || !st.hasMoreElements()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException { return br.readLine(); } } }
Java
["3\n1 1\n3 1 2", "3\n1 1\n3 1 3"]
1 second
["3", "4"]
NoteIn the first example the citizens on the square $$$1$$$ can split into two groups $$$2 + 1$$$, so that the second and on the third squares will have $$$3$$$ citizens each.In the second example no matter how citizens act the bandit can catch at least $$$4$$$ citizens.
Java 8
standard input
[ "greedy", "graphs", "binary search", "dfs and similar", "trees" ]
18cf79b50d0a389e6c3afd5d2f6bd9ed
The first line contains a single integer $$$n$$$ — the number of squares in the city ($$$2 \le n \le 2\cdot10^5$$$). The second line contains $$$n-1$$$ integers $$$p_2, p_3 \dots p_n$$$ meaning that there is a one-way road from the square $$$p_i$$$ to the square $$$i$$$ ($$$1 \le p_i &lt; i$$$). The third line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ — the number of citizens on each square initially ($$$0 \le a_i \le 10^9$$$).
1,900
Print a single integer — the number of citizens the bandit will catch if both sides act optimally.
standard output
PASSED
966b893a06827d31c6578f20e64b665a
train_001.jsonl
1603548300
Bandits appeared in the city! One of them is trying to catch as many citizens as he can.The city consists of $$$n$$$ squares connected by $$$n-1$$$ roads in such a way that it is possible to reach any square from any other square. The square number $$$1$$$ is the main square.After Sunday walk all the roads were changed to one-way roads in such a way that it is possible to reach any square from the main square.At the moment when the bandit appeared on the main square there were $$$a_i$$$ citizens on the $$$i$$$-th square. Now the following process will begin. First, each citizen that is currently on a square with some outgoing one-way roads chooses one of such roads and moves along it to another square. Then the bandit chooses one of the one-way roads outgoing from the square he is located and moves along it. The process is repeated until the bandit is located on a square with no outgoing roads. The bandit catches all the citizens on that square.The bandit wants to catch as many citizens as possible; the citizens want to minimize the number of caught people. The bandit and the citizens know positions of all citizens at any time, the citizens can cooperate. If both sides act optimally, how many citizens will be caught?
256 megabytes
import java.util.*; import java.io.*; public class D445 { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////// ///////// //////// ///////// //////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOOOOO SSSSSSS EEEEEEEEEEEEE ///////// //////// HHHH HHHH EEEEEEEEEEEEE MMMMMM MMMMMM OOO OOO SSSS SSS EEEEEEEEEEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMM MMM MMMM OOO OOO SSSS SSS EEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMMMMM MMMM OOO OOO SSSS EEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSSSSSS EEEEE ///////// //////// HHHHHHHHHHHHHHHH EEEEEEEEEEE MMMM MMMM OOO OOO SSSSSS EEEEEEEEEEE ///////// //////// HHHHHHHHHHHHHHHH EEEEEEEEEEE MMMM MMMM OOO OOO SSSSSSS EEEEEEEEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSSS EEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSS SSSS EEEEE ///////// //////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOO OOO SSS SSSS EEEEEEEEEEEEE ///////// //////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOOOOO SSSSSSS EEEEEEEEEEEEE ///////// //////// ///////// //////// ///////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static int[]a,leaf; static int n; static long[]down; static ArrayList<Integer>[]adj; static void dfs(int u){ down[u] = a[u]; if (adj[u].size()==0) { leaf[u] = 1; } for (int v:adj[u]){ dfs(v); leaf[u]+=leaf[v]; down[u]+=down[v]; } } static boolean ch(long a,long b,long c){ if (1e18/a<c) return true; return a*c>=b; } static long ans; static void ans(int u){ ans=Math.max(ans,(down[u]+leaf[u]-1)/leaf[u]); for (int v:adj[u]) ans(v); } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); // Scanner sc = new Scanner(new FileReader("graph.in")); // PrintWriter pw = new PrintWriter("graph.out"); PrintWriter pw = new PrintWriter(System.out); int n =sc.nextInt(); adj= new ArrayList[n]; a= new int[n]; leaf= new int[n]; down= new long[n]; for (int i =0;i<n;i++) { adj[i]=new ArrayList<>(); if (i>0){ adj[sc.nextInt()-1].add(i); } } a= sc.nextIntArr(n); dfs(0); ans=0; ans(0); pw.println(ans); pw.flush(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(FileReader r) { br = new BufferedReader(r); } 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[] nextIntArr(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } 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
["3\n1 1\n3 1 2", "3\n1 1\n3 1 3"]
1 second
["3", "4"]
NoteIn the first example the citizens on the square $$$1$$$ can split into two groups $$$2 + 1$$$, so that the second and on the third squares will have $$$3$$$ citizens each.In the second example no matter how citizens act the bandit can catch at least $$$4$$$ citizens.
Java 8
standard input
[ "greedy", "graphs", "binary search", "dfs and similar", "trees" ]
18cf79b50d0a389e6c3afd5d2f6bd9ed
The first line contains a single integer $$$n$$$ — the number of squares in the city ($$$2 \le n \le 2\cdot10^5$$$). The second line contains $$$n-1$$$ integers $$$p_2, p_3 \dots p_n$$$ meaning that there is a one-way road from the square $$$p_i$$$ to the square $$$i$$$ ($$$1 \le p_i &lt; i$$$). The third line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ — the number of citizens on each square initially ($$$0 \le a_i \le 10^9$$$).
1,900
Print a single integer — the number of citizens the bandit will catch if both sides act optimally.
standard output
PASSED
48e026c14c5223e88b8a80fa0921d4a3
train_001.jsonl
1595342100
You are given two arrays of integers $$$a_1,\ldots,a_n$$$ and $$$b_1,\ldots,b_m$$$.Your task is to find a non-empty array $$$c_1,\ldots,c_k$$$ that is a subsequence of $$$a_1,\ldots,a_n$$$, and also a subsequence of $$$b_1,\ldots,b_m$$$. If there are multiple answers, find one of the smallest possible length. If there are still multiple of the smallest possible length, find any. If there are no such arrays, you should report about it.A sequence $$$a$$$ is a subsequence of a sequence $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero) elements. For example, $$$[3,1]$$$ is a subsequence of $$$[3,2,1]$$$ and $$$[4,3,1]$$$, but not a subsequence of $$$[1,3,3,7]$$$ and $$$[3,10,4]$$$.
256 megabytes
import java.io.*; import java.util.*; public class A { static int n, m; static int[] arr, brr; static char[] s; public static void main(String[] args) throws IOException { Flash f = new Flash(); int T = f.ni(); for(int tc = 1; tc <= T; tc++){ n = f.ni(); m = f.ni(); arr = f.arr(n); brr = f.arr(m); fn(); } } static void fn() { for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ if(arr[i] == brr[j]){ sop("YES"); sop("1 " + arr[i]); return; } } } sop("NO"); } static void sort(int[] a){ List<Integer> A = new ArrayList<>(); for(int i : a) A.add(i); Collections.sort(A); for(int i = 0; i < A.size(); i++) a[i] = A.get(i); } static int swap(int itself, int dummy){ return itself; } static void sop(Object o){ System.out.println(o); } static void print(int[] a){ StringBuilder sb = new StringBuilder(); for(int i = 0; i < a.length; i++) sb.append(a[i] + " "); System.out.println(sb); } static class Flash { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next(){ while(!st.hasMoreTokens()){ try{ st = new StringTokenizer(br.readLine()); }catch(IOException e){ e.printStackTrace(); } } return st.nextToken(); } String ns(){ String s = new String(); try{ s = br.readLine().trim(); }catch(IOException e){ e.printStackTrace(); } return s; } int ni(){ return Integer.parseInt(next()); } int[] arr(int n){ int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = ni(); return a; } long nl(){ return Long.parseLong(next()); } double nd(){ return Double.parseDouble(next()); } } }
Java
["5\n4 5\n10 8 6 4\n1 2 3 4 5\n1 1\n3\n3\n1 1\n3\n2\n5 3\n1000 2 2 2 3\n3 1 5\n5 5\n1 2 3 4 5\n1 2 3 4 5"]
1 second
["YES\n1 4\nYES\n1 3\nNO\nYES\n1 3\nYES\n1 2"]
NoteIn the first test case, $$$[4]$$$ is a subsequence of $$$[10, 8, 6, 4]$$$ and $$$[1, 2, 3, 4, 5]$$$. This array has length $$$1$$$, it is the smallest possible length of a subsequence of both $$$a$$$ and $$$b$$$.In the third test case, no non-empty subsequences of both $$$[3]$$$ and $$$[2]$$$ exist, so the answer is "NO".
Java 11
standard input
[ "brute force" ]
776a06c14c6fa3ef8664eec0b4d50824
The first line contains a single integer $$$t$$$ ($$$1\le t\le 1000$$$)  — the number of test cases. Next $$$3t$$$ lines contain descriptions of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1\le n,m\le 1000$$$)  — the lengths of the two arrays. The second line of each test case contains $$$n$$$ integers $$$a_1,\ldots,a_n$$$ ($$$1\le a_i\le 1000$$$)  — the elements of the first array. The third line of each test case contains $$$m$$$ integers $$$b_1,\ldots,b_m$$$ ($$$1\le b_i\le 1000$$$)  — the elements of the second array. It is guaranteed that the sum of $$$n$$$ and the sum of $$$m$$$ across all test cases does not exceed $$$1000$$$ ($$$\sum\limits_{i=1}^t n_i, \sum\limits_{i=1}^t m_i\le 1000$$$).
800
For each test case, output "YES" if a solution exists, or "NO" otherwise. If the answer is "YES", on the next line output an integer $$$k$$$ ($$$1\le k\le 1000$$$)  — the length of the array, followed by $$$k$$$ integers $$$c_1,\ldots,c_k$$$ ($$$1\le c_i\le 1000$$$)  — the elements of the array. If there are multiple solutions with the smallest possible $$$k$$$, output any.
standard output
PASSED
587b7c8e0dbc7227ab09c9586ee9851f
train_001.jsonl
1595342100
You are given two arrays of integers $$$a_1,\ldots,a_n$$$ and $$$b_1,\ldots,b_m$$$.Your task is to find a non-empty array $$$c_1,\ldots,c_k$$$ that is a subsequence of $$$a_1,\ldots,a_n$$$, and also a subsequence of $$$b_1,\ldots,b_m$$$. If there are multiple answers, find one of the smallest possible length. If there are still multiple of the smallest possible length, find any. If there are no such arrays, you should report about it.A sequence $$$a$$$ is a subsequence of a sequence $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero) elements. For example, $$$[3,1]$$$ is a subsequence of $$$[3,2,1]$$$ and $$$[4,3,1]$$$, but not a subsequence of $$$[1,3,3,7]$$$ and $$$[3,10,4]$$$.
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 m=sc.nextInt(); int flag=0; ArrayList<Integer> list1=new ArrayList<Integer>(); ArrayList<Integer> list2=new ArrayList<Integer>(); for(int j=0;j<n;j++) { list1.add(sc.nextInt()); } for(int k=0;k<m;k++) { list2.add(sc.nextInt()); } for(Integer num : list1){ if(list2.contains(num)) { System.out.println("YES"); System.out.println(1 + " " + num); flag++; break; } } if(flag==0) { System.out.println("NO"); } } } }
Java
["5\n4 5\n10 8 6 4\n1 2 3 4 5\n1 1\n3\n3\n1 1\n3\n2\n5 3\n1000 2 2 2 3\n3 1 5\n5 5\n1 2 3 4 5\n1 2 3 4 5"]
1 second
["YES\n1 4\nYES\n1 3\nNO\nYES\n1 3\nYES\n1 2"]
NoteIn the first test case, $$$[4]$$$ is a subsequence of $$$[10, 8, 6, 4]$$$ and $$$[1, 2, 3, 4, 5]$$$. This array has length $$$1$$$, it is the smallest possible length of a subsequence of both $$$a$$$ and $$$b$$$.In the third test case, no non-empty subsequences of both $$$[3]$$$ and $$$[2]$$$ exist, so the answer is "NO".
Java 11
standard input
[ "brute force" ]
776a06c14c6fa3ef8664eec0b4d50824
The first line contains a single integer $$$t$$$ ($$$1\le t\le 1000$$$)  — the number of test cases. Next $$$3t$$$ lines contain descriptions of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1\le n,m\le 1000$$$)  — the lengths of the two arrays. The second line of each test case contains $$$n$$$ integers $$$a_1,\ldots,a_n$$$ ($$$1\le a_i\le 1000$$$)  — the elements of the first array. The third line of each test case contains $$$m$$$ integers $$$b_1,\ldots,b_m$$$ ($$$1\le b_i\le 1000$$$)  — the elements of the second array. It is guaranteed that the sum of $$$n$$$ and the sum of $$$m$$$ across all test cases does not exceed $$$1000$$$ ($$$\sum\limits_{i=1}^t n_i, \sum\limits_{i=1}^t m_i\le 1000$$$).
800
For each test case, output "YES" if a solution exists, or "NO" otherwise. If the answer is "YES", on the next line output an integer $$$k$$$ ($$$1\le k\le 1000$$$)  — the length of the array, followed by $$$k$$$ integers $$$c_1,\ldots,c_k$$$ ($$$1\le c_i\le 1000$$$)  — the elements of the array. If there are multiple solutions with the smallest possible $$$k$$$, output any.
standard output
PASSED
4d3a1adb80cd7c43b406bbc89470a40b
train_001.jsonl
1595342100
You are given two arrays of integers $$$a_1,\ldots,a_n$$$ and $$$b_1,\ldots,b_m$$$.Your task is to find a non-empty array $$$c_1,\ldots,c_k$$$ that is a subsequence of $$$a_1,\ldots,a_n$$$, and also a subsequence of $$$b_1,\ldots,b_m$$$. If there are multiple answers, find one of the smallest possible length. If there are still multiple of the smallest possible length, find any. If there are no such arrays, you should report about it.A sequence $$$a$$$ is a subsequence of a sequence $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero) elements. For example, $$$[3,1]$$$ is a subsequence of $$$[3,2,1]$$$ and $$$[4,3,1]$$$, but not a subsequence of $$$[1,3,3,7]$$$ and $$$[3,10,4]$$$.
256 megabytes
import java.util.*; import java.util.Arrays; public class Main { public static void main(String args[]) { try { Scanner in=new Scanner(System.in); int t=in.nextInt(); while(t>=0) { int m=in.nextInt(); int n=in.nextInt(); int a[]=new int[m]; int b[]=new int[n]; int i,j; for(i=0;i<m;i++) { a[i]=in.nextInt(); } for(i=0;i<n;i++) { b[i]=in.nextInt(); } Arrays.sort(a); Arrays.sort(b); int c=0,d=0; for(i=0;i<m;i++) { for(j=0;j<n;j++) { if(a[i]==b[j]) { c=1; d=a[i]; break; } } } if(c==0) { System.out.println("NO"); } else { System.out.println("YES"); System.out.println(+c+" "+d); } t--; } }catch(Exception e) { } } }
Java
["5\n4 5\n10 8 6 4\n1 2 3 4 5\n1 1\n3\n3\n1 1\n3\n2\n5 3\n1000 2 2 2 3\n3 1 5\n5 5\n1 2 3 4 5\n1 2 3 4 5"]
1 second
["YES\n1 4\nYES\n1 3\nNO\nYES\n1 3\nYES\n1 2"]
NoteIn the first test case, $$$[4]$$$ is a subsequence of $$$[10, 8, 6, 4]$$$ and $$$[1, 2, 3, 4, 5]$$$. This array has length $$$1$$$, it is the smallest possible length of a subsequence of both $$$a$$$ and $$$b$$$.In the third test case, no non-empty subsequences of both $$$[3]$$$ and $$$[2]$$$ exist, so the answer is "NO".
Java 11
standard input
[ "brute force" ]
776a06c14c6fa3ef8664eec0b4d50824
The first line contains a single integer $$$t$$$ ($$$1\le t\le 1000$$$)  — the number of test cases. Next $$$3t$$$ lines contain descriptions of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1\le n,m\le 1000$$$)  — the lengths of the two arrays. The second line of each test case contains $$$n$$$ integers $$$a_1,\ldots,a_n$$$ ($$$1\le a_i\le 1000$$$)  — the elements of the first array. The third line of each test case contains $$$m$$$ integers $$$b_1,\ldots,b_m$$$ ($$$1\le b_i\le 1000$$$)  — the elements of the second array. It is guaranteed that the sum of $$$n$$$ and the sum of $$$m$$$ across all test cases does not exceed $$$1000$$$ ($$$\sum\limits_{i=1}^t n_i, \sum\limits_{i=1}^t m_i\le 1000$$$).
800
For each test case, output "YES" if a solution exists, or "NO" otherwise. If the answer is "YES", on the next line output an integer $$$k$$$ ($$$1\le k\le 1000$$$)  — the length of the array, followed by $$$k$$$ integers $$$c_1,\ldots,c_k$$$ ($$$1\le c_i\le 1000$$$)  — the elements of the array. If there are multiple solutions with the smallest possible $$$k$$$, output any.
standard output
PASSED
44f35a0beea830f1c50f03e540f4975b
train_001.jsonl
1595342100
You are given two arrays of integers $$$a_1,\ldots,a_n$$$ and $$$b_1,\ldots,b_m$$$.Your task is to find a non-empty array $$$c_1,\ldots,c_k$$$ that is a subsequence of $$$a_1,\ldots,a_n$$$, and also a subsequence of $$$b_1,\ldots,b_m$$$. If there are multiple answers, find one of the smallest possible length. If there are still multiple of the smallest possible length, find any. If there are no such arrays, you should report about it.A sequence $$$a$$$ is a subsequence of a sequence $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero) elements. For example, $$$[3,1]$$$ is a subsequence of $$$[3,2,1]$$$ and $$$[4,3,1]$$$, but not a subsequence of $$$[1,3,3,7]$$$ and $$$[3,10,4]$$$.
256 megabytes
import java.io.*; import java.text.*; import java.util.*; import java.math.*; public class template { public static void main(String[] args) throws Exception { new template().run(); } public void run() throws Exception { FastScanner f = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int asdf = f.nextInt(); while(asdf-->0) { int n = f.nextInt(), m = f.nextInt(); int[] a = new int[1001]; int[] b = new int[1001]; for(int i = 0; i < n; i++) a[f.nextInt()]++; for(int i = 0; i < m; i++) b[f.nextInt()]++; boolean ok = false; int val = -1; for(int i = 0; i < a.length; i++) if(a[i]*b[i] != 0) { val = i; ok = true; break; } if(ok) { System.out.println("YES"); System.out.println("1 " + val); } else System.out.println("NO"); } out.flush(); } /// static class FastScanner { public BufferedReader reader; public StringTokenizer tokenizer; public FastScanner() { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { try { return reader.readLine(); } catch(IOException e) { throw new RuntimeException(e); } } } }
Java
["5\n4 5\n10 8 6 4\n1 2 3 4 5\n1 1\n3\n3\n1 1\n3\n2\n5 3\n1000 2 2 2 3\n3 1 5\n5 5\n1 2 3 4 5\n1 2 3 4 5"]
1 second
["YES\n1 4\nYES\n1 3\nNO\nYES\n1 3\nYES\n1 2"]
NoteIn the first test case, $$$[4]$$$ is a subsequence of $$$[10, 8, 6, 4]$$$ and $$$[1, 2, 3, 4, 5]$$$. This array has length $$$1$$$, it is the smallest possible length of a subsequence of both $$$a$$$ and $$$b$$$.In the third test case, no non-empty subsequences of both $$$[3]$$$ and $$$[2]$$$ exist, so the answer is "NO".
Java 11
standard input
[ "brute force" ]
776a06c14c6fa3ef8664eec0b4d50824
The first line contains a single integer $$$t$$$ ($$$1\le t\le 1000$$$)  — the number of test cases. Next $$$3t$$$ lines contain descriptions of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1\le n,m\le 1000$$$)  — the lengths of the two arrays. The second line of each test case contains $$$n$$$ integers $$$a_1,\ldots,a_n$$$ ($$$1\le a_i\le 1000$$$)  — the elements of the first array. The third line of each test case contains $$$m$$$ integers $$$b_1,\ldots,b_m$$$ ($$$1\le b_i\le 1000$$$)  — the elements of the second array. It is guaranteed that the sum of $$$n$$$ and the sum of $$$m$$$ across all test cases does not exceed $$$1000$$$ ($$$\sum\limits_{i=1}^t n_i, \sum\limits_{i=1}^t m_i\le 1000$$$).
800
For each test case, output "YES" if a solution exists, or "NO" otherwise. If the answer is "YES", on the next line output an integer $$$k$$$ ($$$1\le k\le 1000$$$)  — the length of the array, followed by $$$k$$$ integers $$$c_1,\ldots,c_k$$$ ($$$1\le c_i\le 1000$$$)  — the elements of the array. If there are multiple solutions with the smallest possible $$$k$$$, output any.
standard output