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
sequencelengths
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
fd20253b59dfd7e645b048fad0202013
train_000.jsonl
1596810900
Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags!
256 megabytes
import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int A = Integer.parseInt(in.readLine()); while(A-- > 0){ int n = Integer.parseInt(in.readLine()); StringTokenizer ka = new StringTokenizer(in.readLine()); int[] count = new int[n + 1]; int subk = 0; int subc = 0; for(int i = 0; i < n; i++){ int k = Integer.parseInt(ka.nextToken()); count[k]++; if(count[k] > subc){ subc = count[k]; subk = k; } } int total = 0; for(int i = 1; i <= n; i++){ if(count[i] == subc){ if(i != subk) total += subc - 1; } else{ total += count[i]; } } int result = total / (subc - 1); out.println(result); } out.close(); } }
Java
["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"]
2 seconds
["3\n2\n0\n4"]
NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$).
Java 8
standard input
[ "constructive algorithms", "sortings", "greedy", "math" ]
9d480b3979a7c9789fd8247120f31f03
The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$.
1,700
For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag.
standard output
PASSED
765b93efd87a7369dfba966fef4fa18f
train_000.jsonl
1596810900
Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags!
256 megabytes
//package com.company; import javafx.util.Pair; import java.util.*; public class CF_1393_C { 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(); int l=0; int r=arr.length; while(r-l>1) { int mid=(l+r)/2; if(check(mid,arr)) l=mid; else r=mid; } System.out.println(l-1); } } public static boolean check(int x, int a[]) { int count[]=new int[a.length+1]; for(int i=0;i<a.length;++i) count[a[i]]++; // LinkedList<int[]> ll=new LinkedList<>(); TreeSet<Pair<Integer,Integer>> ts=new TreeSet(new Comparator<Pair<Integer,Integer>>() { public int compare(Pair<Integer,Integer> p1,Pair<Integer,Integer> p2) { if(p1.getKey().equals(p2.getKey())) return p1.getValue()-p2.getValue(); return p2.getKey()-p1.getKey(); } }); for(int i=1;i<=a.length;++i) { if(count[i]>0) ts.add(new Pair<Integer,Integer>(count[i],i)); } // Collections.sort(ll,(aa,bb)->aa[0]-bb[0]); ArrayList<Integer> arr=new ArrayList<>(); for(int i=0;i<a.length;++i) { if(i>=x&&count[arr.get(i-x)]>0) { ts.add(new Pair<Integer,Integer>(count[arr.get(i-x)],arr.get(i-x))); } if(ts.isEmpty()) return false; arr.add(ts.first().getValue()); ts.remove(ts.first()); count[arr.get(arr.size()-1)]--; } return true; } }
Java
["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"]
2 seconds
["3\n2\n0\n4"]
NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$).
Java 8
standard input
[ "constructive algorithms", "sortings", "greedy", "math" ]
9d480b3979a7c9789fd8247120f31f03
The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$.
1,700
For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag.
standard output
PASSED
5b2d7e9742e1f9c595f8d8ef243a1cd1
train_000.jsonl
1596810900
Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags!
256 megabytes
import java.io.BufferedReader; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class C662C { public static void main(String[] args) throws NumberFormatException, IOException { FastReader sc = new FastReader(); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int t = sc.nextInt(); for(int tt=0; tt<t; tt++) { int n = sc.nextInt(); HashMap<Integer,Integer> cnt = new HashMap<>(); long max = 0; int c=0; for(int x=0; x<n; x++) { int v = sc.nextInt(); if(cnt.containsKey(v)) { cnt.put(v,cnt.get(v)+1); } else { cnt.put(v, 1); } if(cnt.get(v) > max) { max = cnt.get(v); c = 1; } else if(cnt.get(v) == max){ c++; } } //out.println(cnt); long dist = n-1; while(dist >= 0) { if(c+dist*(max-1) <= n) { out.println(dist-1); break; } dist--; } } out.flush(); } static class FastReader{BufferedReader br;StringTokenizer st;public FastReader() {br=new BufferedReader(new InputStreamReader(System.in), 32768);} String next(){while(st==null||!st.hasMoreElements()) {try{st=new StringTokenizer(br.readLine());} catch(IOException e){e.printStackTrace();}}return st.nextToken();} int nextInt(){return Integer.parseInt(next());} long nextLong(){return Long.parseLong(next());} double nextDouble(){return Double.parseDouble(next());} String nextLine(){String str="";try{str=br.readLine();} catch(IOException e){e.printStackTrace();}return str;}} }
Java
["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"]
2 seconds
["3\n2\n0\n4"]
NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$).
Java 8
standard input
[ "constructive algorithms", "sortings", "greedy", "math" ]
9d480b3979a7c9789fd8247120f31f03
The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$.
1,700
For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag.
standard output
PASSED
7bb1fc04149e77f796f512fc8795c2b6
train_000.jsonl
1596810900
Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags!
256 megabytes
import java.io.InputStream; import java.util.Scanner; public class C662 { static int countOfDatasets; static int count_of_sweets; static int[] mass; static int[] count; public static void main(String[] args) { readInput(System.in); } private static void readInput(InputStream s) { Scanner in = new Scanner(s); countOfDatasets = in.nextInt(); for (int i = 0; i < countOfDatasets; i++) { count_of_sweets = in.nextInt(); count = new int[100_001]; mass = new int[count_of_sweets]; for (int j = 0; j < count_of_sweets; j++) { mass[j] = in.nextInt(); count[mass[j]]++; } // int max = Integer.MIN_VALUE; int maxfreq=0; for (int j = 1; j <= count_of_sweets; j++) { if(count[j]>max){ max=count[j]; maxfreq=1; }else if(count[j]==max){ maxfreq++; } } int answer=(count_of_sweets-maxfreq)/(max-1)-1; System.out.println(answer); // } } }
Java
["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"]
2 seconds
["3\n2\n0\n4"]
NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$).
Java 8
standard input
[ "constructive algorithms", "sortings", "greedy", "math" ]
9d480b3979a7c9789fd8247120f31f03
The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$.
1,700
For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag.
standard output
PASSED
bcfc8fdec6324742ead7413cd819dac7
train_000.jsonl
1596810900
Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags!
256 megabytes
// package com.company; import java.util.*; import java.lang.*; import java.io.*; //****Use Integer Wrapper Class for Arrays.sort()**** public class EO3 { static PrintWriter out=new PrintWriter(new OutputStreamWriter(System.out)); public static void main(String[] Args)throws Exception{ FastReader scan=new FastReader(System.in); int t=1; t=scan.nextInt(); while(t-->0){ int n=scan.nextInt(); int[] f=new int[n+1]; for(int i=0;i<n;i++){ int num=scan.nextInt(); f[num]++; } ArrayList<Integer> arr=new ArrayList<>(); for(int i=1;i<=n;i++){ if(f[i]!=0){ arr.add(f[i]); } } Collections.sort(arr,Collections.reverseOrder()); int l=0; int r=arr.size()-1; int ans=0; while(l<=r){ int mid=(l+r)/2; if(pos(arr,mid)){ ans=mid; l=mid+1; }else{ r=mid-1; } } out.println(ans); } out.flush(); out.close(); } static boolean pos(ArrayList<Integer> arr,int gap){ PriorityQueue<Integer> pq=new PriorityQueue<>(arr.size(),Collections.reverseOrder()); for(Integer i:arr){ pq.add(i); } int not=0; while(!pq.isEmpty()){ int itr=pq.size(); if(itr<gap+1){ not++; } if(not>1){ break; } ArrayList<Integer> add=new ArrayList<>(); for(int i=0;i<Math.min(gap+1,itr);i++){ int num=pq.remove(); if(num>1){ add.add(num-1); } } for(Integer i:add){ pq.add(i); } } return not<=1; } static class Pair implements Comparable<Pair>{ int x; int y; Pair(int x,int y){ this.x=x; this.y=y; } @Override public int compareTo(Pair o) { return -this.y+o.y; } } static class FastReader { byte[] buf = new byte[2048]; int index, total; InputStream in; FastReader(InputStream is) { in = is; } int scan() throws IOException { if (index >= total) { index = 0; total = in.read(buf); if (total <= 0) { return -1; } } return buf[index++]; } String next() throws IOException { int c; for (c = scan(); c <= 32; c = scan()) ; StringBuilder sb = new StringBuilder(); for (; c > 32; c = scan()) { sb.append((char) c); } return sb.toString(); } int nextInt() throws IOException { int c, val = 0; for (c = scan(); c <= 32; c = scan()) ; boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } long nextLong() throws IOException { int c; long val = 0; for (c = scan(); c <= 32; c = scan()) ; boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } } }
Java
["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"]
2 seconds
["3\n2\n0\n4"]
NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$).
Java 8
standard input
[ "constructive algorithms", "sortings", "greedy", "math" ]
9d480b3979a7c9789fd8247120f31f03
The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$.
1,700
For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag.
standard output
PASSED
320daf1fca4c084747c7220e9c497c91
train_000.jsonl
1596810900
Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags!
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.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; public class PattyCakes { // Template for CF public static class ListComparator implements Comparator<List<Integer>> { @Override public int compare(List<Integer> l1, List<Integer> l2) { for (int i = 0; i < l1.size(); ++i) { if (l1.get(i).compareTo(l2.get(i)) != 0) { return l1.get(i).compareTo(l2.get(i)); } } return 0; } } public static class Pair { int first; int second; public Pair(int first, int second) { this.first = first; this.second = second; } public int getFirst() { return first; } public int getSecond() { return second; } @Override public String toString() { return first + " " + second; } } public static void main(String[] args) throws IOException { // Check for int overflow!!!! // Should you use a long to store the sum or smthn? BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int T = Integer.parseInt(f.readLine()); for (int i = 0; i < T; i++) { int n = Integer.parseInt(f.readLine()); StringTokenizer st = new StringTokenizer(f.readLine()); Map<Integer, Integer> map = new HashMap<>(); Set<Integer> keySet = new HashSet<>(); for (int j = 0; j < n; j++) { int a = Integer.parseInt(st.nextToken()); if (map.containsKey(a)) { map.put(a, map.get(a) + 1); } else { map.put(a, 1); } keySet.add(a); } List<Integer> list = new ArrayList<>(); for (int a : keySet) { list.add(map.get(a)); } Collections.sort(list); int max = list.get(list.size() - 1); int sum = 0; for (int j = 0; j < list.size(); j++) { if (list.get(j) == max) { sum++; } } if (sum <= 1) { out.println((n - max) / (max - 1)); } else { out.println((n - max - (sum - 1)) / (max - 1)); } } out.close(); } }
Java
["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"]
2 seconds
["3\n2\n0\n4"]
NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$).
Java 8
standard input
[ "constructive algorithms", "sortings", "greedy", "math" ]
9d480b3979a7c9789fd8247120f31f03
The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$.
1,700
For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag.
standard output
PASSED
d50ef1d8b722335a8cab1e96d288a680
train_000.jsonl
1596810900
Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags!
256 megabytes
import java.io.*;import java.util.*; import javax.swing.text.rtf.RTFEditorKit; import java.math.*; public class Main { static long mod=1000000007l; static int max=Integer.MAX_VALUE,min=Integer.MIN_VALUE; static long maxl=Long.MAX_VALUE,minl=Long.MIN_VALUE; static BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st; static StringBuilder sb; static public void main(String[] args)throws Exception { st=new StringTokenizer(br.readLine()); int t=i(); sb=new StringBuilder(t*10); while(t-->0) { int n=i(); int ar[]=ari(n); int m=-1; HashMap<Integer,Integer> h=new HashMap<>((int)(n*0.76)); for(int x:ar) { h.put(x, h.getOrDefault(x, 0)+1); m=max(m,h.get(x)); } int c=0; for(int a:h.keySet())if(h.get(a)==m)c++; int r=n-(c*m); int re=r/(m-1); sl(re+c-1); } p(sb); } static void s(String s){sb.append(s);} static void s(int s){sb.append(s);} static void s(long s){sb.append(s);} static void s(char s){sb.append(s);} static void s(double s){sb.append(s);} static void ss(){sb.append(' ');} static void sl(String s){sb.append(s);sb.append("\n");} static void sl(int s){sb.append(s);sb.append("\n");} static void sl(long s){sb.append(s);sb.append("\n");} static void sl(char s){sb.append(s);sb.append("\n");} static void sl(double s){sb.append(s);sb.append("\n");} static void sl(){sb.append("\n");} static int max(int a,int b){return a>b?a:b;} static int min(int a,int b){return a<b?a:b;} static int abs(int a){return Math.abs(a);} static long max(long a,long b){return a>b?a:b;} static long min(long a,long b){return a<b?a:b;} static long abs(long a){return Math.abs(a);} static int sq(int a){return (int)Math.sqrt(a);} static long sq(long a){return (long)Math.sqrt(a);} static int gcd(int a,int b){return b==0?a:gcd(b,a%b);} // static void g(int i,int p) // { // for(int e:ar[i]) // { // if(e==p)continue; // al[i].add(e); // g(e,i); // } // } static boolean pa(String s,int i,int j) { while(i<j)if(s.charAt(i++)!=s.charAt(j--))return false; return true; } static int ncr(int n,int c,long m) { long a=1l; for(int x=n-c+1;x<=n;x++)a=((a*x)%m); long b=1l; for(int x=2;x<=c;x++)b=((b*x)%m); return (int)((a*(mul((int)b,m-2,m)%m))%m); } static boolean[] sieve(int n) { boolean bo[]=new boolean[n+1]; bo[0]=true;bo[1]=true; for(int x=4;x<=n;x+=2)bo[x]=true; for(int x=3;x*x<=n;x+=2)if(!bo[x])for(int y=x*x;y<=n;y+=x)bo[y]=true; return bo; } static int[] fac(int n) { int bo[]=new int[n+1]; for(int x=1;x<=n;x++)for(int y=x;y<=n;y+=x)bo[y]++; return bo; } static long mul(long a,long b,long m) { long r=1l; a%=m; while(b>0) { if((b&1)==1)r=(r*a)%m; b>>=1; a=(a*a)%m; } return r; } static int i()throws IOException { if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine()); return Integer.parseInt(st.nextToken()); } static long l()throws IOException { if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine()); return Long.parseLong(st.nextToken()); } static String s()throws IOException { if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine()); return st.nextToken(); } static double d()throws IOException { if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine()); return Double.parseDouble(st.nextToken()); } static void p(Object p){System.out.print(p);} static void p(String p){System.out.print(p);} static void p(int p){System.out.print(p);} static void p(double p){System.out.print(p);} static void p(long p){System.out.print(p);} static void p(char p){System.out.print(p);} static void p(boolean p){System.out.print(p);} static void pl(Object p){System.out.println(p);} static void pl(String p){System.out.println(p);} static void pl(int p){System.out.println(p);} static void pl(char p){System.out.println(p);} static void pl(double p){System.out.println(p);} static void pl(long p){System.out.println(p);} static void pl(boolean p){System.out.println(p);} static void pl(){System.out.println();} static int[] ari(int n)throws IOException { int ar[]=new int[n]; if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine()); for(int x=0;x<n;x++)ar[x]=Integer.parseInt(st.nextToken()); return ar; } static int[][] ari(int n,int m)throws IOException { int ar[][]=new int[n][m]; for(int x=0;x<n;x++) { if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine()); for(int y=0;y<m;y++)ar[x][y]=Integer.parseInt(st.nextToken()); } return ar; } static long[] arl(int n)throws IOException { long ar[]=new long[n]; if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine()); for(int x=0;x<n;x++) ar[x]=Long.parseLong(st.nextToken()); return ar; } static long[][] arl(int n,int m)throws IOException { long ar[][]=new long[n][m]; for(int x=0;x<n;x++) { if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine()); for(int y=0;y<m;y++)ar[x][y]=Long.parseLong(st.nextToken()); } return ar; } static String[] ars(int n)throws IOException { String ar[]=new String[n]; if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine()); for(int x=0;x<n;x++) ar[x]=st.nextToken(); return ar; } static double[] ard(int n)throws IOException { double ar[]=new double[n]; if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine()); for(int x=0;x<n;x++)ar[x]=Double.parseDouble(st.nextToken()); return ar; } static double[][] ard(int n,int m)throws IOException { double ar[][]=new double[n][m]; for(int x=0;x<n;x++) { if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine()); for(int y=0;y<m;y++)ar[x][y]=Double.parseDouble(st.nextToken()); } return ar; } static char[] arc(int n)throws IOException { char ar[]=new char[n]; if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine()); for(int x=0;x<n;x++)ar[x]=st.nextToken().charAt(0); return ar; } static char[][] arc(int n,int m)throws IOException { char ar[][]=new char[n][m]; for(int x=0;x<n;x++) { String s=br.readLine(); for(int y=0;y<m;y++)ar[x][y]=s.charAt(y); } return ar; } static void p(int ar[]) { StringBuilder sb=new StringBuilder(2*ar.length); for(int a:ar) { sb.append(a); sb.append(' '); } System.out.println(sb); } static void p(int ar[][]) { StringBuilder sb=new StringBuilder(2*ar.length*ar[0].length); for(int a[]:ar) { for(int aa:a) { sb.append(aa); sb.append(' '); } sb.append("\n"); } p(sb); } static void p(long ar[]) { StringBuilder sb=new StringBuilder(2*ar.length); for(long a:ar) { sb.append(a); sb.append(' '); } System.out.println(sb); } static void p(long ar[][]) { StringBuilder sb=new StringBuilder(2*ar.length*ar[0].length); for(long a[]:ar) { for(long aa:a) { sb.append(aa); sb.append(' '); } sb.append("\n"); } p(sb); } static void p(String ar[]) { int c=0; for(String s:ar)c+=s.length()+1; StringBuilder sb=new StringBuilder(c); for(String a:ar) { sb.append(a); sb.append(' '); } System.out.println(sb); } static void p(double ar[]) { StringBuilder sb=new StringBuilder(2*ar.length); for(double a:ar) { sb.append(a); sb.append(' '); } System.out.println(sb); } static void p(double ar[][]) { StringBuilder sb=new StringBuilder(2*ar.length*ar[0].length); for(double a[]:ar) { for(double aa:a) { sb.append(aa); sb.append(' '); } sb.append("\n"); } p(sb); } static void p(char ar[]) { StringBuilder sb=new StringBuilder(2*ar.length); for(char aa:ar) { sb.append(aa); sb.append(' '); } System.out.println(sb); } static void p(char ar[][]) { StringBuilder sb=new StringBuilder(2*ar.length*ar[0].length); for(char a[]:ar) { for(char aa:a) { sb.append(aa); sb.append(' '); } sb.append("\n"); } p(sb); } }
Java
["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"]
2 seconds
["3\n2\n0\n4"]
NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$).
Java 8
standard input
[ "constructive algorithms", "sortings", "greedy", "math" ]
9d480b3979a7c9789fd8247120f31f03
The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$.
1,700
For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag.
standard output
PASSED
b73ed658747526159afd8f2ef2e6d90b
train_000.jsonl
1596810900
Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags!
256 megabytes
import java.util.*; import java.io.*; import java.math.BigInteger; public class cf1 { static long mod = (long)1e9 + 7; static long mod1 = 998244353; static FastScanner f; static PrintWriter pw = new PrintWriter(System.out); static Scanner S = new Scanner(System.in); static long x0; static long y0; static int inf = (int)(1e9); static long iinf = (long)(1e18); public static void solve()throws NumberFormatException , IOException { int n = f.ni(); HashMap<Integer , Integer> h = new HashMap<>(); for (int i = 0; i < n; ++i) { int x = f.ni(); if (h.containsKey(x)) h.put(x , h.get(x) + 1); else h.put(x , 1); } int max = 0 , cnt = 0; for (Integer i : h.keySet()) { if (h.get(i) > max) { max = h.get(i); cnt = 1; } else if (h.get(i) == max) ++cnt; } int ans = ((n - cnt) / (max - 1)) - 1; pn(ans); } public static void main(String[] args)throws NumberFormatException , IOException { init(); boolean tc = true; int t = tc ? f.ni() : 1; while(t --> 0) solve(); pw.flush(); pw.close(); } /******************************END OF MAIN PROGRAM*******************************************/ public static void init()throws IOException{if(System.getProperty("ONLINE_JUDGE")==null){f=new FastScanner("");}else{f=new FastScanner(System.in);}} public static class FastScanner { BufferedReader br;StringTokenizer st; FastScanner(InputStream stream){try{br=new BufferedReader(new InputStreamReader(stream));}catch(Exception e){e.printStackTrace();}} FastScanner(String str){try{br=new BufferedReader(new FileReader("!a.txt"));}catch(Exception e){e.printStackTrace();}} String next(){while(st==null||!st.hasMoreTokens()){try{st=new StringTokenizer(br.readLine());}catch(IOException e){e.printStackTrace();}}return st.nextToken();} String nextLine()throws IOException{return br.readLine();}int ni(){return Integer.parseInt(next());}long nl(){return Long.parseLong(next());}double nd(){return Double.parseDouble(next());} } public static void pn(Object o){pw.println(o);} public static void p(Object o){pw.print(o);} public static void pni(Object o){pw.println(o);pw.flush();} static int gcd(int a,int b){if(b==0)return a;else{return gcd(b,a%b);}} static long gcd(long a,long b){if(b==0l)return a;else{return gcd(b,a%b);}} static long lcm(long a,long b){return (a*b/gcd(a,b));} static long exgcd(long a,long b){if(b==0){x0=1;y0=0;return a;}long temp=exgcd(b,a%b);long t=x0;x0=y0;y0=t-a/b*y0;return temp;} static long pow(long a,long b){long res=1;while(b>0){if((b&1)==1)res=res*a;b>>=1;a=a*a;}return res;} static long mpow(long a,long b){long res=1;while(b>0l){if((b&1)==1l)res=((res%mod)*(a%mod))%mod;b>>=1l;a=((a%mod)*(a%mod))%mod;}return res;} static long mul(long a , long b){return ((a%mod)*(b%mod)%mod);} static long adp(long a , long b){return ((a%mod)+(b%mod)%mod);} static int log2(int x){return (int)(Math.log(x)/Math.log(2));} static boolean isPrime(long n){if(n<=1)return false;if(n<=3)return true;if(n%2==0||n%3==0)return false;for(long i=5;i*i<=n;i=i+6)if(n%i==0||n%(i+2)==0)return false;return true;} static boolean isPrime(int n){if(n<=1)return false;if(n<=3)return true;if(n%2==0||n%3==0)return false;for(int i=5;i*i<=n;i=i+6)if(n%i==0||n%(i+2)==0)return false;return true;} static HashSet<Long> factors(long n){HashSet<Long> hs=new HashSet<Long>();for(long i=1;i<=(long)Math.sqrt(n);i++){if(n%i==0){hs.add(i);hs.add(n/i);}}return hs;} static HashSet<Integer> factors(int n){HashSet<Integer> hs=new HashSet<Integer>();for(int i=1;i<=(int)Math.sqrt(n);i++){if(n%i==0){hs.add(i);hs.add(n/i);}}return hs;} static HashSet<Long> pf(long n){HashSet<Long> ff=factors(n);HashSet<Long> res=new HashSet<Long>();for(Long i:ff)if(isPrime(i))res.add(i);return res;} static HashSet<Integer> pf(int n){HashSet<Integer> ff=factors(n);HashSet<Integer> res=new HashSet<Integer>();for(Integer i:ff)if(isPrime(i))res.add(i);return res;} static int[] inpint(int n){int arr[]=new int[n+1];for(int i=1;i<=n;++i){arr[i]=f.ni();}return arr;} static long[] inplong(int n){long arr[] = new long[n+1];for(int i=1;i<=n;++i){arr[i]=f.nl();}return arr;} static boolean ise(int x){return ((x&1)==0);}static boolean ise(long x){return ((x&1)==0);} static int gnv(char c){return Character.getNumericValue(c);}//No. of integers less than equal to i in ub static int log(long x){return x==1?0:(1+log(x/2));} static int log(int x){return x==1?0:(1+log(x/2));} static int upperbound(int a[],int i){int lo=0,hi=a.length-1,mid=0;int count=0;while(lo<=hi){mid=(lo+hi)/2;if(a[mid]<=i){count=mid+1;lo=mid+1;}else hi=mid-1;}return count;} static void sort(int[] a){ArrayList<Integer> l=new ArrayList<>();for(int i:a)l.add(i);Collections.sort(l);for(int i=0;i<a.length;++i)a[i]=l.get(i);} static void sort(long[] a){ArrayList<Long> l=new ArrayList<>();for(long i:a)l.add(i);Collections.sort(l);for(int i=0;i<a.length;++i)a[i]=l.get(i);} static void sort(ArrayList<Integer> a){Collections.sort(a);}//!Precompute fact in ncr()! static int nextPowerOf2(int n){int count=0;if(n>0&&(n&(n-1))==0)return n;while(n!=0){n>>=1;count += 1;}return 1<<count;} }
Java
["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"]
2 seconds
["3\n2\n0\n4"]
NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$).
Java 8
standard input
[ "constructive algorithms", "sortings", "greedy", "math" ]
9d480b3979a7c9789fd8247120f31f03
The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$.
1,700
For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag.
standard output
PASSED
096056d3b2defbcf7f4d148faa6a2904
train_000.jsonl
1596810900
Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags!
256 megabytes
import java.util.Collections; import java.util.*; import java.lang.*; import java.math.BigInteger; import java.io.*; import java.io.*; import java.util.*; import java.util.Arrays; public class CodeChef { public static void main (String[] args) throws IOException { StringBuilder sb=new StringBuilder(); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(br.readLine()); while(t-->0) { int n=Integer.parseInt(br.readLine()); String[] sr=br.readLine().split(" "); int[] arr=new int[n]; int[] count=new int[n+1]; for(int i=0;i<n;i++) { arr[i]=Integer.parseInt(sr[i]); count[arr[i]]++; } Arrays.sort(count); int max=count[n]; long sum1=0; int i=n-1; while((i>0)&&(count[i]>=max-1)) {sum1++; i--; } long sum2=0; while((i>0)&&(count[i]!=0)) {sum2+=count[i]; i--; } sum1+=sum2/(max-1); System.out.println(sum1); } } }
Java
["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"]
2 seconds
["3\n2\n0\n4"]
NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$).
Java 8
standard input
[ "constructive algorithms", "sortings", "greedy", "math" ]
9d480b3979a7c9789fd8247120f31f03
The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$.
1,700
For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag.
standard output
PASSED
ed882d6164f8ac7e96e441a4c4ccf92f
train_000.jsonl
1596810900
Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags!
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class demo_C { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int t = scan.nextInt(),n; int a[] = new int[200005]; while( t-- != 0) { n = scan.nextInt(); int num=0,max1=0; for(int i=1,x;i<=n;i++) { x = scan.nextInt(); max1=Math.max(max1,++a[x]); } for(int i=1;i<=n;i++) { if( a[i]==max1 ) num++; a[i]=0; } int ans = (n-max1*num)/(max1-1)+num-1; System.out.println(ans); } } }
Java
["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"]
2 seconds
["3\n2\n0\n4"]
NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$).
Java 8
standard input
[ "constructive algorithms", "sortings", "greedy", "math" ]
9d480b3979a7c9789fd8247120f31f03
The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$.
1,700
For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag.
standard output
PASSED
ab1b414be30935a9e59324756f83d9a8
train_000.jsonl
1596810900
Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags!
256 megabytes
import java.io.PrintWriter; import java.util.*; public class Main { static Scanner in; static PrintWriter out; public static void main(String[] args) { in = new Scanner(System.in); out = new PrintWriter(System.out); int t = in.nextInt(); while (t-- > 0) { int n = in.nextInt(); int[] a = new int[n]; Map<Integer, Integer> mp = new HashMap<>(); for (int i = 0; i < a.length; i++) { a[i] = in.nextInt(); mp.put(a[i], mp.getOrDefault(a[i], 0) + 1); } List<Pie> toSort = new ArrayList<>(); for (int key : mp.keySet()) { toSort.add(new Pie(mp.get(key), key)); } Collections.sort(toSort, Comparator.comparing(p1 -> -p1.c)); int biggest = toSort.get(0).c; int ans = 0; long sum = 0; for (int i = 1; i < toSort.size(); i++) { if (toSort.get(i).c == biggest) { ans++; } else { sum += toSort.get(i).c; } } ans += sum / (biggest - 1); out.println(ans); } out.close(); } static class Pie { public Pie(int c, int t) { this.c = c; this.t = t; } int c; int t; } }
Java
["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"]
2 seconds
["3\n2\n0\n4"]
NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$).
Java 8
standard input
[ "constructive algorithms", "sortings", "greedy", "math" ]
9d480b3979a7c9789fd8247120f31f03
The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$.
1,700
For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag.
standard output
PASSED
2ea51ded0c0c1e476af770541095c2ed
train_000.jsonl
1596810900
Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags!
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.PriorityQueue; import java.util.StringTokenizer; public class Main { public static void main(String[] args) { FastReader sc = new FastReader(); int tt = sc.nextInt(); while(tt-- > 0){ int n = sc.nextInt(); int[] arr = sc.readIntArray(n); int[] arrFreq = new int[n]; for(int i : arr) ++arrFreq[i - 1]; int minDist = 1, maxDist = n; while(minDist < maxDist){ int mid = (minDist + maxDist + 1) / 2; if(possible(arrFreq, mid, n)){ minDist = mid; }else maxDist = mid - 1; } System.out.println(minDist - 1); } } private static boolean possible(int[] arrFreq, int dist, int n) { ArrayList<Integer>[] idxList = new ArrayList[n]; for(int i = 0; i < n; ++i) idxList[i] = new ArrayList<>(); for(int freq : arrFreq){ if(freq != 0) idxList[0].add(freq); } PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> b - a); for(int i = 0; i < n; ++i){ for(int freqToAdd : idxList[i]) pq.offer(freqToAdd); if(pq.isEmpty()) // distance selected should be smaller return false; int freqToPlaceHere = pq.poll(); --freqToPlaceHere; if(freqToPlaceHere > 0){ if(i + dist >= n) return false; idxList[i + dist].add(freqToPlaceHere); } } return true; } private static class FastReader { private BufferedReader br; StringTokenizer st; int[] readIntArray(int n){ int[] arr = new int[n]; for(int i = 0; i < n; ++i) arr[i] = nextInt(); return arr; } long[] readLongArray(int n){ long[] arr = new long[n]; for(int i = 0; i < n; ++i) arr[i] = nextLong(); return arr; } double[] readDoubleArray(int n){ double[] arr = new double[n]; for(int i = 0; i < n; ++i) arr[i] = nextDouble(); return arr; } public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"]
2 seconds
["3\n2\n0\n4"]
NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$).
Java 8
standard input
[ "constructive algorithms", "sortings", "greedy", "math" ]
9d480b3979a7c9789fd8247120f31f03
The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$.
1,700
For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag.
standard output
PASSED
760755a602402d04e6c0240d03718337
train_000.jsonl
1596810900
Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags!
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.lang.*; import static java.lang.Math.*; public class Solution implements Runnable { static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } public int[] readint(int st,int n){ int[] arr=new int[n+st]; for(int i=st;i<n+st;i++) arr[i]=nextInt(); return arr; } public long[] readlong(int st,int n){ long[] arr=new long[n+st]; for(int i=st;i<n+st;i++) arr[i]=nextLong(); return arr; } } public static void main(String args[]) throws Exception { new Thread(null, new Solution(),"Main",1<<27).start(); } public static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } public static long findGCD(long arr[], int n) { long result = arr[0]; for (int i = 1; i < n; i++) result = gcd(arr[i], result); return result; } static void sortbycolomn(long arr[][], int col) { Arrays.sort(arr, new Comparator<long[]>() { @Override public int compare(final long[] entry1, final long[] entry2) { if (entry1[col] > entry2[col]) return 1; else return -1; } }); } public void run() { InputReader in = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int t=in.nextInt(); while(t--!=0){ int n=in.nextInt(); int[] has=new int[n+1]; for(int i=0;i<n;i++) has[in.nextInt()]++; Arrays.sort(has); int x=has[n]; int count=1; for(int i=n-1;i>=0;i--) if(has[i]==x) count++; int ans = count-1; ans+=(n-count*x)/(x-1); w.println(ans); } w.flush(); w.close(); } }
Java
["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"]
2 seconds
["3\n2\n0\n4"]
NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$).
Java 8
standard input
[ "constructive algorithms", "sortings", "greedy", "math" ]
9d480b3979a7c9789fd8247120f31f03
The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$.
1,700
For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag.
standard output
PASSED
e4b80878be7f765fd560f3e7fbe46e6c
train_000.jsonl
1596810900
Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags!
256 megabytes
import java.io.*; import java.lang.Math; import java.util.*; public class Main { public BufferedReader in; public PrintStream out; public boolean log_enabled = false; public boolean multiply_tests = true; public static boolean do_gen_test = false; public void gen_test() { } private class TestCase { public Object solve() { int n = readInt(); int[] a = readIntArray(n); int[] cnt = new int[100001]; Arrays.fill(cnt, 0); int i; for (i=0; i<n; i++) { cnt[a[i]] ++; } int cnt_max = 0; for (i=1; i<=n; i++) { if (cnt[i] > cnt_max) { cnt_max = cnt[i]; } } int mx_count = 0; for (i=1; i<=n; i++) { if (cnt[i]==cnt_max) { mx_count ++; } } return (n- mx_count*cnt_max) / (cnt_max-1) + (mx_count-1) ; //return strf("%f", 0); //out.printf("Case #%d: \n", caseNumber); //return null; } public int caseNumber; TestCase(int number) { caseNumber = number; } public void run(){ Object r = this.solve(); if ((r != null)) { //outputCaseNumber(r); out.println(r); } } public String impossible(){ return "IMPOSSIBLE"; } public String strf(String format, Object... args) { return String.format(format, args); } // public void outputCaseNumber(Object r){ // //out.printf("Case #%d:", caseNumber); // if (r != null) // { // // out.print(" "); // out.print(r); // } // out.print("\n"); // } } public void run() { //while (true) { int t = multiply_tests ? readInt() : 1; for (int i = 0; i < t; i++) { TestCase T = new TestCase(i + 1); T.run(); } } } public Main(BufferedReader _in, PrintStream _out){ in = _in; out = _out; } public static void main(String args[]) { Locale.setDefault(Locale.US); Main S; try { S = new Main( new BufferedReader(new InputStreamReader(System.in)), System.out ); } catch (Exception e) { return; } S.run(); } private StringTokenizer tokenizer = null; public int readInt() { return Integer.parseInt(readToken()); } public long readLong() { return Long.parseLong(readToken()); } public double readDouble() { return Double.parseDouble(readToken()); } public String readLn() { try { String s; while ((s = in.readLine()).length() == 0); return s; } catch (Exception e) { return ""; } } public String readToken() { try { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(in.readLine()); } return tokenizer.nextToken(); } catch (Exception e) { return ""; } } public int[] readIntArray(int n) { int[] x = new int[n]; readIntArray(x, n); return x; } public int[] readIntArrayBuf(int n) { int[] x = new int[n]; readIntArrayBuf(x, n); return x; } public void readIntArray(int[] x, int n) { for (int i = 0; i < n; i++) { x[i] = readInt(); } } public long[] readLongArray(int n) { long[] x = new long[n]; readLongArray(x, n); return x; } public long[] readLongArrayBuf(int n) { long[] x = new long[n]; readLongArrayBuf(x, n); return x; } public void readLongArray(long[] x, int n) { for (int i = 0; i < n; i++) { x[i] = readLong(); } } public void logWrite(String format, Object... args) { if (!log_enabled) { return; } out.printf(format, args); } public void readLongArrayBuf(long[] x, int n) { char[]buf = new char[1000000]; long r = -1; int k= 0, l = 0; long d; while (true) { try{ l = in.read(buf, 0, 1000000); } catch(Exception E){}; for (int i=0; i<l; i++) { if (('0'<=buf[i])&&(buf[i]<='9')) { if (r == -1) { r = 0; } d = buf[i] - '0'; r = 10 * r + d; } else { if (r != -1) { x[k++] = r; } r = -1; } } if (l<1000000) return; } } public void readIntArrayBuf(int[] x, int n) { char[]buf = new char[1000000]; int r = -1; int k= 0, l = 0; int d; while (true) { try{ l = in.read(buf, 0, 1000000); } catch(Exception E){}; for (int i=0; i<l; i++) { if (('0'<=buf[i])&&(buf[i]<='9')) { if (r == -1) { r = 0; } d = buf[i] - '0'; r = 10 * r + d; } else { if (r != -1) { x[k++] = r; } r = -1; } } if (l<1000000) return; } } public void printArray(long[] a, int n) { printArray(a, n, ' '); } public void printArray(int[] a, int n) { printArray(a, n, ' '); } public void printArray(long[] a, int n, char dl) { long x; int i, l = 0; for (i=0; i<n; i++) { x = a[i]; if (x<0) { x = -x; l++; } if (x==0) { l++; } else { while (x>0) { x /= 10; l++; } } } l += n-1; char[] s = new char[l]; l--; boolean z; for (i=n-1; i>=0; i--) { x = a[i]; z = false; if (x<0) { x = -x; z = true; } do{ s[l--] = (char)('0' + (x % 10)); x /= 10; } while (x>0); if (z) { s[l--] = '-'; } if (i>0) { s[l--] = dl; } } out.println(new String(s)); } public void printArray(int[] a, int n, char dl) { int x; int i, l = 0; for (i=0; i<n; i++) { x = a[i]; if (x<0) { x = -x; l++; } if (x==0) { l++; } else { while (x>0) { x /= 10; l++; } } } l += n-1; char[] s = new char[l]; l--; boolean z; for (i=n-1; i>=0; i--) { x = a[i]; z = false; if (x<0) { x = -x; z = true; } do{ s[l--] = (char)('0' + (x % 10)); x /= 10; } while (x>0); if (z) { s[l--] = '-'; } if (i>0) { s[l--] = dl; } } out.println(new String(s)); } public void printMatrix(int[][] a, int n, int m) { int x; int i,j, l = 0; for (i=0; i<n; i++) { for (j=0; j<m; j++) { x = a[i][j]; if (x<0) { x = -x; l++; } if (x==0) { l++; } else { while (x>0) { x /= 10; l++; } } } l += m-1; } l += n-1; char[] s = new char[l]; l--; boolean z; for (i=n-1; i>=0; i--) { for (j=m-1; j>=0; j--) { x = a[i][j]; z = false; if (x<0) { x = -x; z = true; } do{ s[l--] = (char)('0' + (x % 10)); x /= 10; } while (x>0); if (z) { s[l--] = '-'; } if (j>0) { s[l--] = ' '; } } if (i>0) { s[l--] = '\n'; } } out.println(new String(s)); } public void printMatrix(long[][] a, int n, int m) { long x; int i,j, l = 0; for (i=0; i<n; i++) { for (j=0; j<m; j++) { x = a[i][j]; if (x<0) { x = -x; l++; } if (x==0) { l++; } else { while (x>0) { x /= 10; l++; } } } l += m-1; } l += n-1; char[] s = new char[l]; l--; boolean z; for (i=n-1; i>=0; i--) { for (j=m-1; j>=0; j--) { x = a[i][j]; z = false; if (x<0) { x = -x; z = true; } do{ s[l--] = (char)('0' + (x % 10)); x /= 10; } while (x>0); if (z) { s[l--] = '-'; } if (j>0) { s[l--] = ' '; } } if (i>0) { s[l--] = '\n'; } } out.println(new String(s)); } }
Java
["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"]
2 seconds
["3\n2\n0\n4"]
NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$).
Java 8
standard input
[ "constructive algorithms", "sortings", "greedy", "math" ]
9d480b3979a7c9789fd8247120f31f03
The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$.
1,700
For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag.
standard output
PASSED
0bf5dd40b8563578e4bbf85abb9bf73b
train_000.jsonl
1596810900
Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags!
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class C1393 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int test = Integer.parseInt(br.readLine()); while (test-- > 0){ int n = Integer.parseInt(br.readLine()); int a[] = new int[n]; String in[] = br.readLine().trim().split(" "); Map<Integer, Integer>M = new HashMap<>(); int mx = -1; for (int i=0;i<n;++i){ a[i] = Integer.parseInt(in[i]); if (M.containsKey(a[i])){ M.put(a[i], M.get(a[i])+1); } else { M.put(a[i], 1); } mx = Math.max(mx, M.get(a[i])); } //List<Integer>L = new ArrayList<>(); int cnt = 0; for (int i=0;i<n;++i){ if (M.get(a[i]) == mx){ cnt++; M.put(a[i], 0); } } int ans = 0; if (cnt == 1){ int res = n - mx; if (mx > 1){ ans = res / (mx - 1); } } else { int res = n - (mx * cnt); ans = cnt - 1; if (mx == 2){ ans += res; } else { if (mx > 1){ ans += res / ( mx - 1); } } } if (mx == 1) ans = 0; System.out.println(ans); } } // expected: '1', found: '2' //7 //1 2 1 2 1 2 3 }
Java
["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"]
2 seconds
["3\n2\n0\n4"]
NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$).
Java 8
standard input
[ "constructive algorithms", "sortings", "greedy", "math" ]
9d480b3979a7c9789fd8247120f31f03
The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$.
1,700
For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag.
standard output
PASSED
d11057911764080e6442373f86bfeea1
train_000.jsonl
1596810900
Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags!
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { int T = in.nextInt(); while (T-- > 0) { int N = in.nextInt(); int mx = 0; int top = 0; int[] cnt = new int[(int) 1e5]; for (int i = 0; i < N; i++) { int a = in.nextInt() - 1; cnt[a]++; if (cnt[a] > mx) { mx = cnt[a]; top = 1; } else if (cnt[a] == mx) { top++; } } out.println((N - top) / (mx - 1) - 1); } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"]
2 seconds
["3\n2\n0\n4"]
NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$).
Java 8
standard input
[ "constructive algorithms", "sortings", "greedy", "math" ]
9d480b3979a7c9789fd8247120f31f03
The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$.
1,700
For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag.
standard output
PASSED
0def282e081a7b1a9406a0793b72dba3
train_000.jsonl
1596810900
Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags!
256 megabytes
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { public static void main (String[] args) throws java.lang.Exception { FastReader sc1 = new FastReader(); StringBuilder sb = new StringBuilder(); int tc = sc1.nextInt(); int ch = 0; while(ch<tc){ int n = sc1.nextInt(); int[] arr = new int[n]; int[] fre = new int[n+1]; int maxfre = 0; for(int i=0; i<n; i++){ arr[i] = sc1.nextInt(); fre[arr[i]]++; maxfre = Math.max(maxfre, fre[arr[i]]); } int cnt = 0; for(int i=1;i<=n; i++){ if(fre[i] == maxfre){ cnt++; } } int num = (n - maxfre - cnt + 1); int den = maxfre-1; int res = num/den; sb.append(res+"\n"); ch++; } System.out.print(sb.toString()); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"]
2 seconds
["3\n2\n0\n4"]
NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$).
Java 8
standard input
[ "constructive algorithms", "sortings", "greedy", "math" ]
9d480b3979a7c9789fd8247120f31f03
The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$.
1,700
For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag.
standard output
PASSED
3ed64e81fce0e4a77034956f9812b6b7
train_000.jsonl
1596810900
Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags!
256 megabytes
//package codeforces.D662; import java.io.IOException; import java.util.HashMap; import java.util.InputMismatchException; import java.util.Map; /** * @author muhossain * @since 2020-08-08 */ public class C { public static void main(String[] args) { FasterScanner fs = new FasterScanner(); int t = fs.nextInt(); StringBuilder output = new StringBuilder(); for (int i = 1; i <= t; i++) { int n = fs.nextInt(); Map<Integer, Integer> freMap = new HashMap<>(); int maxFreq = 0; int maxFreqCount = 0; for (int j = 0; j < n; j++) { int a = fs.nextInt(); freMap.putIfAbsent(a, 0); freMap.put(a, freMap.get(a) + 1); if (freMap.get(a) > maxFreq) { maxFreq = freMap.get(a); maxFreqCount = 1; } else if (freMap.get(a) == maxFreq) { maxFreqCount++; } } int result = (((n - maxFreqCount) / (maxFreq - 1)) - 1); output.append(result).append("\n"); } System.out.print(output); } static class Item { int a; int freq; public Item(int a, int freq) { this.a = a; this.freq = freq; } } public static class FasterScanner { private byte[] buf = new byte[1024]; private int curChar; private int numChars; public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = System.in.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"]
2 seconds
["3\n2\n0\n4"]
NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$).
Java 8
standard input
[ "constructive algorithms", "sortings", "greedy", "math" ]
9d480b3979a7c9789fd8247120f31f03
The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$.
1,700
For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag.
standard output
PASSED
95bda585312f6246aee6b5b037303830
train_000.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.util.*; import java.io.*; public class TaskC { public static void main(String[] args) { FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); boolean[] d = new boolean[n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { int t = in.nextInt(); if (i == j) d[i] = t == 1; } } boolean ans = false; for (int i = 0; i < n; i++) { ans ^= d[i]; } int q = in.nextInt(); for (int i = 0; i < q; i++) { int t = in.nextInt(); if (t == 3) { out.print(ans ? 1 : 0); } else { in.nextInt(); ans = !ans; } } out.close(); } } class FastScanner { public BufferedReader br; public StringTokenizer st; public FastScanner(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); st = null; } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public String nextLine() { String s = ""; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return s; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
12a3025196be34267c39c51f226e3e6b
train_000.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.util.Scanner; public class C { static StreamTokenizer st; public static void main(String[] args) throws IOException{ st= new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); PrintWriter pw= new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int n=nextInt(); int a[][]= new int [n][n]; for (int i = 0; i < a.length; i++) { for (int j = 0; j < a.length; j++) { a[i][j]=nextInt(); } } int cnt=0; for (int i = 0; i < a.length; i++) { cnt+=a[i][i]; } cnt%=2; // System.out.println(cnt); int q=nextInt(); for (int i = 0; i < q; i++) { int x=nextInt(); if(x==1){ int y=nextInt(); if(cnt==1) cnt=0; else cnt=1; } if(x==2){ int y=nextInt(); if(cnt==1) cnt=0; else cnt=1; } if(x==3){ pw.print(cnt); } } pw.close(); } private static int nextInt() throws IOException{ st.nextToken(); return (int)st.nval; } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
0c5810fcae5dd71834630b43f0f25aef
train_000.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashMap; import java.util.StringTokenizer; public class C { void solve() throws Exception{ int n = in.nextInt(); int a[][] = new int[n][n]; for (int i = 0;i < n; i++) { for (int j = 0; j<n; j++) a[i][j] = in.nextInt(); } int q = in.nextInt(); int total = 0; for (int i = 0; i<n; i++) { for (int j = 0; j<n; j++) total += a[i][j] * a[j][i]; } HashMap<Integer, Integer> columnDiff = new HashMap<>(); HashMap<Integer, Integer> rowDiff = new HashMap<>(); for (int i = 0; i<q; i++) { total = Math.abs(total) % 2; int type = in.nextInt(); if (type == 3) { out.print(total); } if (type == 2) { int j = in.nextInt() - 1; if (columnDiff.containsKey(j)) { total += columnDiff.get(j); continue; } int diff = 0; for (int k = 0; k<n; k++) { int oldSum = a[k][j] * a[j][k]; a[k][j] = a[k][j] == 1 ? 0 : 1; int newSum = a[k][j] * a[j][k]; if (oldSum > newSum) { if (k == j) { diff -= 1; } else { diff -= 2; } } else if (oldSum < newSum) { if (k == j) { diff += 1; } else { diff += 2; } } } total += diff; columnDiff.put(j, diff); } if (type == 1) { int j = in.nextInt() - 1; if (rowDiff.containsKey(j)) { total += rowDiff.get(j); continue; } int diff = 0; for (int k = 0; k<n; k++) { int oldSum = a[k][j] * a[j][k]; a[j][k] = a[j][k] == 1 ? 0 : 1; int newSum = a[k][j] * a[j][k]; if (oldSum > newSum) { if (k == j) { diff -= 1; } else { diff -= 2; } } else if (oldSum < newSum) { if (k == j) { diff += 1; } else { diff += 2; } } } total += diff; rowDiff.put(j, diff); } } } String input = ""; String output = ""; FastScanner in; PrintWriter out; void run() throws Exception { if (input.length() == 0) { in = new FastScanner(System.in); } else { in = new FastScanner(new File(input)); } if (output.length() == 0) { out = new PrintWriter(System.out); } else { out = new PrintWriter(new File(output)); } solve(); out.close(); } public static void main(String[] args) throws Exception { new C().run(); } class FastScanner { BufferedReader bf; StringTokenizer st; public FastScanner(InputStream is) { bf = new BufferedReader(new InputStreamReader(is)); } public FastScanner(File fr) throws FileNotFoundException { bf = new BufferedReader(new FileReader(fr)); } public String next() { try { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(bf.readLine()); } } catch (IOException ex) { ex.printStackTrace(); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public int[] readIntArray(int length) { int arr[] = new int[length]; for (int i = 0; i<length; i++) arr[i] = nextInt(); return arr; } } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
2e612938e4c80a1a0f34ccc0e9a1d5ea
train_000.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.io.*; import java.util.*; public class Task1 { public static void main(String[] args) throws IOException { new Task1().solve(); } boolean[] used; int[] a; int n; PrintWriter out; void solve() throws IOException{ Reader in = new Reader(); out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out)) ); //out = new PrintWriter(new FileWriter(new File("output.txt"))); n = in.nextInt(); int[][] a = new int[n+1][n+1]; for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) { a[i][j] = in.nextInt(); } int sum = 0; for (int i = 1; i <= n; i++) { sum += a[i][i]; } StringBuilder buff = new StringBuilder(); int m = in.nextInt(); int o; sum %= 2; for (int i = 0; i < m; i++) { o = in.nextInt(); if (o == 3) { buff.append(sum); } else { in.nextInt(); sum = Math.abs(sum-1); } } System.out.println(buff.toString()); out.flush(); out.close(); } } class Reader { StringTokenizer token; BufferedReader in; public Reader() throws IOException { // in = new BufferedReader( new FileReader( "input.txt" ) ); in = new BufferedReader( new InputStreamReader( System.in ) ); } public byte nextByte() throws IOException { return Byte.parseByte(Next()); } public int nextInt() throws IOException { return Integer.parseInt(Next()); } public long nextLong() throws IOException { return Long.parseLong(Next()); } public String nextString() throws IOException { return in.readLine(); } private String Next() throws IOException { while (token == null || !token.hasMoreTokens()) { token = new StringTokenizer(in.readLine()); } return token.nextToken(); } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
b509b85cefa7b27a1ab56514f96c84d7
train_000.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) { // get input FastScanner in = new FastScanner(System.in); // n int n = in.nextInt(); // set flag to be 0 int flag = 0; // read matrix // every time we have 1 on diagonal line // flag = 1 - falg for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { if (in.nextInt() == 1 && i == j) { flag = 1 - flag; } } } // get m int m = in.nextInt(); StringBuilder sb = new StringBuilder(); // for q = 1 : m for (int q = 1; q <= m; q++) { // get query // if the first number is 1 or 2, ignore the next one and flag = 1 - falg // if the first number is 3, then print flag int query = in.nextInt(); if (query == 3) { sb.append(flag); } else { in.nextInt(); flag = 1 - flag; } } System.out.println(sb); } static class FastScanner { StringTokenizer tokenizer; BufferedReader reader; FastScanner(InputStream input) { reader = new BufferedReader(new InputStreamReader(input)); } String nextToken() { while (tokenizer == null || ! tokenizer.hasMoreTokens()) { try { String input = reader.readLine(); tokenizer = new StringTokenizer(input); } catch (Exception e) {} } return tokenizer.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
f637e74314258dfc97ca61a080aa99cc
train_000.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.io.PrintStream; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Lokesh Khandelwal */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(), i, j; int a[][] = new int[n][n]; int rowData[][] = new int[n][4], colData[][] = new int[n][4]; int rowFlips[] = new int[n], colFlips[] = new int[n]; for(i=0;i<n;i++) { for(j=0;j<n;j++) { a[i][j] = in.nextInt(); } } int tot = 0; // 00 01 10 11 for(i=0;i<n;i++) { for(j=0;j<n;j++) { if(i == j) { tot += (a[i][i] == 1) ? 1 : 0; continue; } if(a[i][j] == 1) { if(a[j][i] == 1) { rowData[i][3]++; tot++; } else rowData[i][2]++; } else { if(a[j][i] == 1) { rowData[i][1]++; } else rowData[i][0]++; } } } for(i=0;i<n;i++) { for(j=0;j<n;j++) { if(i == j) continue; if(a[i][j] == 1) { if(a[j][i] == 1) { colData[j][3]++; } else colData[j][2]++; } else { if(a[j][i] == 1) { colData[j][1]++; } else colData[j][0]++; } } } int q = in.nextInt(); DebugUtils.print(tot); DebugUtils.print(colData); DebugUtils.print(rowData); while (q-- > 0) { int p = in.nextInt(); if(p == 3) { if(tot < 0) tot = -tot; out.print(tot % 2); continue; } int r = in.nextInt() - 1; if(p == 1) { rowFlips[r]++; //if(rowFlips[r] % 2 == 1) { tot -= 2 * rowData[r][3]; tot += 2 * rowData[r][1]; if(a[r][r] == 0) tot++; else tot--; int temp = rowData[r][1]; rowData[r][1] = rowData[r][3]; rowData[r][3] = temp; temp = rowData[r][2]; rowData[r][2] = rowData[r][0]; rowData[r][0] = temp; //} } else if(p == 2) { colFlips[r]++; //if(colFlips[r] % 2 == 1) { tot -= 2 * colData[r][3]; tot += 2 * colData[r][1]; if(a[r][r] == 0) tot++; else tot--; int temp = colData[r][1]; colData[r][1] = colData[r][3]; colData[r][3] = temp; temp = colData[r][2]; colData[r][2] = colData[r][0]; colData[r][0] = temp; //} } } out.printLine(); } } class InputReader { BufferedReader in; StringTokenizer tokenizer=null; public InputReader(InputStream inputStream) { in=new BufferedReader(new InputStreamReader(inputStream)); } public String next() { try{ while (tokenizer==null||!tokenizer.hasMoreTokens()) { tokenizer=new StringTokenizer(in.readLine()); } return tokenizer.nextToken(); } catch (IOException e) { return null; } } public int nextInt() { return Integer.parseInt(next()); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } } class DebugUtils { public static void print(Object... a) { boolean oj=System.getProperty("ONLINE_JUDGE")!=null; if(!oj) System.out.println(Arrays.deepToString(a)); } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
e2dc85ae1f6b05dfed87eab371191279
train_000.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; public class Test { public static void main(String[] args) { // try { // InputStream inputStream = new FileInputStream( // "D:\\codeforse\\CF\\input.txt"); // OutputStream outputStream = new FileOutputStream( // "D:\\codeforse\\CF\\output.txt"); InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); C solver = new C(); // int t = in.nextInt(); // for (int i = 1; i <= t; i++) { solver.solve(1, in, out); // } out.close(); // } catch (FileNotFoundException e) { // TODO Auto-generated catch block // e.printStackTrace(); // } catch (IOException e) { // TODO Auto-generated catch block // e.printStackTrace(); // } } } class C { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int[] a = new int[n]; int t; int sum = 0; for (int i = 0; i < n; i++){ for (int j = 0; j <n; j++){ t = in.nextInt(); if (j == i){ a[i] = t; if (t == 1){ sum++; } } } } int q = in.nextInt(); int s ; for (int i = 0; i < q; i++){ t = in.nextInt(); if (t == 1 || t == 2){ s = in.nextInt() -1; if (a[s] == 1){ sum--; a[s] = 0; }else{ a[s] = 1; sum++; } }else{ out.print(sum%2); } } } class Pair implements Comparable<Pair> { // ArrayList<Pair> p = new ArrayList<Pair>(); // Collections.sort(p, Comparators.AGE); int r; int me; int to; int toNext; Pair parent; ArrayList<Integer> toF; public Pair(int me, int to) { this.me = me; this.to = to; this.toNext = 0; } public void addTo(Pair p) { parent = p; } @Override public int compareTo(Pair o) { return Comparators.AGE.compare(this, o); } public String toString() { return "" + r + " "; } } public static class Comparators { public static Comparator<Pair> AGE = new Comparator<Pair>() { @Override public int compare(Pair o1, Pair o2) { return o1.r > o2.r ? 1 : (o1.r < o2.r ? -1 : 0); } }; } } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public Double nextDouble() { return Double.parseDouble(next()); } public String nextString() { return next(); } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
75ab19ed701f0c4ed179ec4e2dd15053
train_000.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; public class C405E { public static void main(String[] args) throws IOException { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out)); int n = Integer.parseInt(bf.readLine()); int[] a = new int[n]; int one = 0, zero = 0; String s[]; for (int i = 0; i < n; i++) { s = bf.readLine().trim().split(" "); a[i] = Integer.parseInt(s[i]); if (a[i] == 1) one++; else zero++; } int q = Integer.parseInt(bf.readLine()), w; for (int i = 0; i < q; i++) { s = bf.readLine().trim().split(" "); if (s.length == 1){ if (one % 2 != 0) pw.print("1"); else pw.print("0"); } else { w = Integer.parseInt(s[1]); if (a[w - 1] == 1) { a[w - 1] = 0; one--; zero++; } else { a[w - 1] = 1; one++; zero--; } } } bf.close(); pw.close(); } } /* 3 1 1 1 0 1 1 1 0 0 12 3 2 3 3 2 2 2 2 1 3 3 3 1 2 2 1 1 1 3 */
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
323cddff78863d9dac7889823396987c
train_000.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; public class Contest405C { public static void solve() throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); // int t = Integer.parseInt(br.readLine()); int t = 1; while (t-- > 0) { int n = Integer.parseInt(br.readLine()); int[] diag = new int[n]; int sum = 0; for(int i=0;i<n;i++){ String[] ip = br.readLine().split(" "); diag[i] = Integer.parseInt(ip[i]); sum += diag[i]; sum %= 2; } int q = Integer.parseInt(br.readLine()); while(q-->0){ String[] ip = br.readLine().split(" "); if(ip.length>1){ int i = Integer.parseInt(ip[1]); sum -= diag[i-1]; if(sum<0) sum += 2; diag[i-1] = 1 - diag[i-1]; sum += diag[i-1]; sum %= 2; } else{ sb.append(sum); } } sb.append("\n"); } System.out.print(sb.toString()); } public static void main(String[] args) throws Exception { solve(); } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
c545ddfb838ad4257e659f1e2860b343
train_000.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.io.IOException; import java.util.InputMismatchException; import java.io.PrintStream; import java.io.OutputStream; import java.io.PrintWriter; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author karan173 */ 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); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { int n; long dots[]; long sumRow[], sumCol[]; public void solve(int testNumber, FastReader in, PrintWriter out) { n = in.ni (); int a[][] = new int[n][]; for (int i = 0; i < n; i++) { a[i] = in.iArr (n); } // out.println (Arrays.deepToString (a)); dots = new long[n]; sumCol = new long[n]; sumRow = new long[n]; long curAns = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { int x1 = a[i][j]; int x2 = a[j][i]; dots[i] += x1 * x2; sumRow[i] += x1; sumCol[j] += x1; } curAns += dots[i]; } int q = in.ni (); for (int i = 0; i < q; i++) { int t = in.ni (); if (t == 3) { out.print (curAns % 2); continue; } else if (t == 1) //flip row { int r = in.ni () - 1; long oldDots = dots[r]; dots[r] = n - sumRow[r] - sumCol[r] + oldDots; curAns =curAns - 2 * oldDots + 2 * dots[r]+a[r][r]; sumRow[r] = n - sumRow[r]; sumCol[r] -= (a[r][r] == 1 ? 1 : 0); a[r][r] = 1 - a[r][r]; curAns -= a[r][r]; } else { int r = in.ni () - 1; long oldDots = dots[r]; dots[r] = n - sumRow[r] - sumCol[r] + oldDots; curAns = curAns- 2 * oldDots + 2 * dots[r]+a[r][r]; sumCol[r] = n - sumCol[r]; sumRow[r] -= (a[r][r] == 1 ? 1 : 0); a[r][r] = 1 - a[r][r]; curAns -= a[r][r]; } // out.println ("--"+curAns); } out.println (); } } class FastReader { public InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private 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 ni() { int c = read (); while (isSpaceChar (c)) c = read (); int sgn = 1; if (c == '-') { sgn = -1; c = read (); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException (); } res *= 10; res += c - '0'; c = read (); } while (!isSpaceChar (c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar (c); } return isWhitespace (c); } public static boolean isWhitespace(int c) { return c==' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int[] iArr(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = ni (); } return a; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
d98e89d11f049619396119b74666e790
train_000.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.io.*; import java.util.*; public class p405c { BufferedReader in; PrintWriter out; StringTokenizer st; String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (Exception e) { } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } public void run() throws Exception { in = new BufferedReader(new InputStreamReader(System.in)); //in = new BufferedReader(new FileReader(new File("./src/input.txt"))); out = new PrintWriter(System.out); int a[] = new int[1003]; int n = nextInt(); int sum = 0; for (int i = 0; i<n; i++) for (int j = 0; j<n; j++) { int x = nextInt(); if (i == j){ a[i] = x; sum = (sum + x) % 2; } } int q = nextInt(); for (int i = 0; i<q; i++){ int r = nextInt(); if (r == 1 || r == 2){ int t = nextInt(); sum = (sum - a[t] + 2) % 2; a[t] = (a[t] + 1) % 2; sum = (sum + a[t] + 2) % 2; } else { out.print(sum); } } out.close(); } public static void main(String[] args) throws Exception { new p405c().run(); } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
f24ee1fd238c1e6f746e62b42299f4a9
train_000.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.io.*; import java.util.*; public class cf405c { static FastIO in = new FastIO(), out = in; public static void main(String[] args) { int n = in.nextInt(); int ret = 0; for(int i=0; i<n; i++) for(int j=0; j<n; j++) { if(i == j) ret ^= in.nextInt(); else in.nextInt(); } int q = in.nextInt(); for(int i=0; i<q; i++) { int type = in.nextInt(); if(type != 3) { ret ^= 1; in.nextInt(); } else out.print(ret); } out.close(); } static class FastIO extends PrintWriter { BufferedReader br; StringTokenizer st; public FastIO() { this(System.in, System.out); } public FastIO(InputStream in, OutputStream out) { super(new BufferedWriter(new OutputStreamWriter(out))); br = new BufferedReader(new InputStreamReader(in)); scanLine(); } public void scanLine() { try { st = new StringTokenizer(br.readLine().trim()); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } } public int numTokens() { if (!st.hasMoreTokens()) { scanLine(); return numTokens(); } return st.countTokens(); } public String next() { if (!st.hasMoreTokens()) { scanLine(); return next(); } return st.nextToken(); } public double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
5fe2e0b8f38217f22944f3a776d4184c
train_000.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; public class C_UnusualProduct { public static void main(String[] args) throws java.io.IOException { BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); final int N = Integer.parseInt(input.readLine()); boolean[] diag = new boolean[N]; for (int i = 0 ; i < N ; i++) { String[] vals = input.readLine().split(" "); diag[i] = (vals[i].equals("1")); } boolean ans = false; for (boolean b : diag) { if (b) { ans = !ans; } } StringBuilder sb = new StringBuilder(); final int Q = Integer.parseInt(input.readLine()); int count = 0; for (int i = 0 ; i < Q ; i++) { if (input.readLine().charAt(0) == '3') { if (count % 2 == 1) { ans = !ans; } sb.append((ans) ? '1' : '0'); count = 0; } else { count++; } } System.out.println(sb.toString()); } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
76190e798f9f59788cc55ec7b5bed058
train_000.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.util.*; import java.lang.reflect.Array; import java.math.*; import java.io.*; import java.awt.*; public class Main{ static FastReader in = new FastReader(new BufferedReader(new InputStreamReader(System.in))); static PrintWriter out = new PrintWriter(System.out); static final int maxn = (int)1e3 + 11; static int inf = (1<<30) - 1; static int a[][] = new int [maxn][maxn]; public static void main(String[] args) throws Exception { solve(); out.close(); } public static void solve() throws Exception { int n = in.nextInt(); int ans = 0; for (int i=1; i<=n; i++) { for (int j=1; j<=n; j++) { a[i][j] = in.nextInt(); if (i==j) { ans+=a[i][j]; } } } ans%=2; int q = in.nextInt(); for (int i=1; i<=q; i++) { int t = in.nextInt(); if (t==1 || t==2) { int r = in.nextInt(); ans+=1; ans%=2; } if (t==3) { out.print(ans); } } } } class Pair implements Comparable<Pair> { int x,y; public Pair (int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(Pair p) { if (this.x<p.x) { return -1; } else if (this.x == p.x) { return 0; } else { return 1; } } } class FastReader { BufferedReader bf; StringTokenizer tk = null; String DELIM = " "; public FastReader(BufferedReader bf) { this.bf = bf; } public String nextToken() throws Exception { if(tk==null || !tk.hasMoreTokens()) { tk = new StringTokenizer(bf.readLine(),DELIM); } return tk.nextToken(); } public int nextInt() throws Exception { return Integer.parseInt(nextToken()); } public long nextLong() throws Exception { return Long.parseLong(nextToken()); } public double nextDouble() throws Exception { return Double.parseDouble(nextToken()); } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
3412bc7f39e50059ba042f640ed1b6e9
train_000.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
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.List; import java.util.StringTokenizer; public class Main { static BufferedReader reader; static StringTokenizer tokenizer; static PrintWriter writer; static int nextInt() throws IOException { return Integer.parseInt(nextToken()); } static long nextLong() throws IOException { return Long.parseLong(nextToken()); } static double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } static boolean eof = false; static String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } public static void main(String[] args) throws IOException { tokenizer = null; reader = new BufferedReader(new InputStreamReader(System.in)); writer = new PrintWriter(System.out); banana(); reader.close(); writer.close(); } public static class Node { public List<Node> child = new ArrayList<Node>(); public Node parent = null; public long data = 0; public String name; public boolean isUsed = false; public Node(String _name) { name = _name; } } public static String test(String x) { x = "2"; return x; } public static class Int { public long data; Int(long d) { data = d; } } public static long gcd(long a, long b, Int x, Int y) { if (b == 0) { x = new Int(1); y = new Int(0); return a; } else { Int x1 = new Int(1l), y1 = new Int(0l); long d = gcd(b, a % b, x1, y1); x.data = y1.data; y.data = x1.data - y1.data * (a / b); return d; } } /* * String s = nextToken(); int n = s.length(); int f[][] = new int[n][n]; * * for (int i = 0 ; i < n; ++i) for (int j = 0; i + j < n; ++j) { //[i,i+j] } */ static void banana() throws IOException { int n = nextInt(); int a[][] = new int[n][n]; for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) a[i][j] = nextInt(); int cur = 0; for (int i = 0; i < n; ++i) cur += a[i][i]; cur = cur % 2; int q = nextInt(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < q; ++i) { int query = nextInt(); if (query != 3) { nextInt(); cur = 1 - cur; } else sb.append(cur); } writer.print(sb.toString()); } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
5673d02beda24d105b08d7529d3d4f04
train_000.jsonl
1395502200
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * Class: Product<br /> * Date: 2014/03/23 00:24<br /> * Description:<br /> * * @author Laiping Zhou(sjtudesigner) */ public class Product { public static void main(String[] args) throws IOException { BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in)); // Scanner sc = new Scanner(System.in); // n = sc.nextInt(); int n = Integer.parseInt(buffer.readLine()); int result = 0; for (int i = 0;i < n;i++) { String t = buffer.readLine(); result ^= t.charAt(2 * i) - '0'; } int t = Integer.parseInt(buffer.readLine()); byte[] res = new byte[t]; int z = 0; for (int i = 0;i < t;i++) { String s = null; s = buffer.readLine(); if (s.charAt(0) == '3') res[z++] += result + '0'; else result = 1 - result; } System.out.println(new String(res, 0, z)); } }
Java
["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"]
1 second
["01001"]
null
Java 7
standard input
[ "implementation", "math" ]
332902284154faeaf06d5d05455b7eb6
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i — flip the values of the i-th row; 2 i — flip the values of the i-th column; 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
1,600
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
standard output
PASSED
775862eefd11fbe05cb7d17d06372d8f
train_000.jsonl
1471698300
Like all children, Alesha loves New Year celebration. During the celebration he and his whole family dress up the fir-tree. Like all children, Alesha likes to play with garlands — chains consisting of a lightbulbs.Alesha uses a grid field sized n × m for playing. The rows of the field are numbered from 1 to n from the top to the bottom and columns are numbered from 1 to m from the left to the right.Alesha has k garlands which he places at the field. He does so in the way such that each lightbulb of each garland lies in the center of some cell in the field, and each cell contains at most one lightbulb. Of course lightbulbs, which are neighbours in some garland, appears in cells neighbouring by a side.The example of garland placing.Each garland is turned off or turned on at any moment. If some garland is turned on then each of its lightbulbs is turned on, the same applies for garland turned off. Each lightbulb in the whole garland set is unique, and thus, being turned on, brings Alesha some pleasure, described by an integer value. Turned off lightbulbs don't bring Alesha any pleasure.Alesha can turn garlands on and off and wants to know the sum of pleasure value which the lightbulbs, placed in the centers of the cells in some rectangular part of the field, bring him. Initially all the garlands are turned on.Alesha is still very little and can't add big numbers. He extremely asks you to help him.
256 megabytes
// practice with rainboy import java.io.*; import java.util.*; public class CF707E extends PrintWriter { CF707E() { super(System.out); } static class Scanner { Scanner(InputStream in) { this.in = in; } InputStream in; int k, l; byte[] bb = new byte[1 << 15]; byte getc() { if (k >= l) { k = 0; try { l = in.read(bb); } catch (IOException e) { l = 0; } if (l <= 0) return -1; } return bb[k++]; } int nextInt() { byte c = 0; while (c <= 32) c = getc(); boolean minus = c == '-'; if (minus) c = getc(); int a = 0; while (c > 32) { a = a * 10 + c - '0'; c = getc(); } return minus ? -a : a; } int m = 1 << 7; byte[] cc = new byte[m]; int read() { byte c = 0; while (c <= 32) c = getc(); int n = 0; while (c > 32) { if (n == m) cc = Arrays.copyOf(cc, m <<= 1); cc[n++] = c; c = getc(); } return n; } String next() { int n = read(); return new String(cc, 0, n); } } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF707E o = new CF707E(); o.main(); o.flush(); } static final int N = 2000, Z = 10; int[] ii = new int[N], jj = new int[N], ww = new int[N]; static class V { V l, r; int imin, imax, jmin, jmax; long w; long[][] ww; V(int imin, int imax, int jmin, int jmax, long w) { this.imin = imin; this.imax = imax; this.jmin = jmin; this.jmax = jmax; this.w = w; } } V process(int l, int r) { int imin, imax, jmin, jmax; imin = jmin = N; imax = jmax = -1; long w = 0; for (int h = l; h < r; h++) { imin = Math.min(imin, ii[h]); imax = Math.max(imax, ii[h]); jmin = Math.min(jmin, jj[h]); jmax = Math.max(jmax, jj[h]); w += ww[h]; } V v = new V(imin, imax, jmin, jmax, w); int n = imax - imin + 1; int m = jmax - jmin + 1; if (n * m <= (r - l) * Z) { v.ww = new long[n][m]; for (int h = l; h < r; h++) { int i = ii[h] - imin; int j = jj[h] - jmin; v.ww[i][j] = ww[h]; } for (int i = 1; i < n; i++) for (int j = 0; j < m; j++) v.ww[i][j] += v.ww[i - 1][j]; for (int i = 0; i < n; i++) for (int j = 1; j < m; j++) v.ww[i][j] += v.ww[i][j - 1]; } else { m = (l + r) / 2; v.l = process(l, m); v.r = process(m, r); } return v; } int imin, imax, jmin, jmax; long query(V v) { if (imin <= v.imin && v.imax <= imax && jmin <= v.jmin && v.jmax <= jmax) return v.w; if (v.imax < imin || imax < v.imin || v.jmax < jmin || jmax < v.jmin) return 0; if (v.ww == null) return query(v.l) + query(v.r); int i1 = Math.max(imin, v.imin) - v.imin; int i2 = Math.min(imax, v.imax) - v.imin; int j1 = Math.max(jmin, v.jmin) - v.jmin; int j2 = Math.min(jmax, v.jmax) - v.jmin; long ans = v.ww[i2][j2]; if (i1 > 0) ans -= v.ww[i1 - 1][j2]; if (j1 > 0) ans -= v.ww[i2][j1 - 1]; if (i1 > 0 && j1 > 0) ans += v.ww[i1 - 1][j1 - 1]; return ans; } void main() { int n = sc.nextInt(); int m = sc.nextInt(); int k = sc.nextInt(); V[] vv = new V[k]; for (int h = 0; h < k; h++) { int l = sc.nextInt(); for (int h_ = 0; h_ < l; h_++) { ii[h_] = sc.nextInt() - 1; jj[h_] = sc.nextInt() - 1; ww[h_] = sc.nextInt(); } vv[h] = process(0, l); } boolean[] off = new boolean[k]; int q = sc.nextInt(); while (q-- > 0) { String e = sc.next(); if (e.charAt(0) == 'S') { int h = sc.nextInt() - 1; off[h] = !off[h]; } else { imin = sc.nextInt() - 1; jmin = sc.nextInt() - 1; imax = sc.nextInt() - 1; jmax = sc.nextInt() - 1; long ans = 0; for (int h = 0; h < k; h++) if (!off[h]) ans += query(vv[h]); println(ans); } } } }
Java
["4 4 3\n5\n1 1 2\n1 2 3\n2 2 1\n2 1 4\n3 1 7\n4\n1 3 1\n2 3 3\n2 4 3\n1 4 1\n7\n4 1 1\n4 2 9\n3 2 8\n3 3 3\n4 3 4\n4 4 1\n3 4 1\n2\nASK 2 2 3 3\nASK 1 1 4 4", "4 4 1\n8\n4 1 1\n3 1 2\n2 1 1\n1 1 7\n1 2 5\n2 2 4\n2 3 1\n1 3 1\n3\nASK 1 1 3 2\nSWITCH 1\nASK 1 1 3 2"]
3 seconds
["15\n52", "19\n0"]
NoteThis image illustrates the first sample case.
Java 11
standard input
[ "data structures" ]
a45f38aae8dadb6f0991b41ecb1be855
The first line of the input contains three integers n, m and k (1 ≤ n, m, k ≤ 2000) — the number of field rows, the number of field columns and the number of garlands placed at the field respectively. Next lines contains garlands set description in the following format: The first line of a single garland description contains a single integer len (1 ≤ len ≤ 2000) — the number of lightbulbs in the garland. Each of the next len lines contains three integers i, j and w (1 ≤ i ≤ n, 1 ≤ j ≤ m, 1 ≤ w ≤ 109) — the coordinates of the cell containing a lightbullb and pleasure value Alesha gets from it if it is turned on. The lightbulbs are given in the order they are forming a chain in the garland. It is guaranteed that neighbouring lightbulbs are placed in the cells neighbouring by a side. The next line contains single integer q (1 ≤ q ≤ 106) — the number of events in Alesha's game. The next q lines describes events in chronological order. The i-th of them describes the i-th event in the one of the following formats: SWITCH i — Alesha turns off i-th garland if it is turned on, or turns it on if it is turned off. It is guaranteed that 1 ≤ i ≤ k. ASK x1 y1 x2 y2 — Alesha wants to know the sum of pleasure values the lightbulbs, placed in a rectangular part of the field. Top-left cell of a part has coordinates (x1, y1) and right-bottom cell has coordinates (x2, y2). It is guaranteed that 1 ≤ x1 ≤ x2 ≤ n and 1 ≤ y1 ≤ y2 ≤ m. There is no more than 2000 events of this type in the input. All the numbers in the input are integers. Please note that the input is quite large, so be careful while using some input ways. In particular, it's not recommended to use cin in codes on C++ and class Scanner in codes on Java.
2,400
For each ASK operation print the sum Alesha wants to know in a separate line. Print the answers in chronological order.
standard output
PASSED
ee17bc1684bf69e8a6d845231233c397
train_000.jsonl
1471698300
Like all children, Alesha loves New Year celebration. During the celebration he and his whole family dress up the fir-tree. Like all children, Alesha likes to play with garlands — chains consisting of a lightbulbs.Alesha uses a grid field sized n × m for playing. The rows of the field are numbered from 1 to n from the top to the bottom and columns are numbered from 1 to m from the left to the right.Alesha has k garlands which he places at the field. He does so in the way such that each lightbulb of each garland lies in the center of some cell in the field, and each cell contains at most one lightbulb. Of course lightbulbs, which are neighbours in some garland, appears in cells neighbouring by a side.The example of garland placing.Each garland is turned off or turned on at any moment. If some garland is turned on then each of its lightbulbs is turned on, the same applies for garland turned off. Each lightbulb in the whole garland set is unique, and thus, being turned on, brings Alesha some pleasure, described by an integer value. Turned off lightbulbs don't bring Alesha any pleasure.Alesha can turn garlands on and off and wants to know the sum of pleasure value which the lightbulbs, placed in the centers of the cells in some rectangular part of the field, bring him. Initially all the garlands are turned on.Alesha is still very little and can't add big numbers. He extremely asks you to help him.
256 megabytes
import java.io.*; import java.util.*; public class Main { static class ft2d { long[][]tree; int max_x;int max_y; ft2d(int x,int y){ tree=new long[x+1][y+1]; max_x=x;max_y=y; } void update(int x , int y , long val){ int y1; while (x <= max_x){ y1 = y; while (y1 <= max_y){ tree[x][y1] += val; y1 += (y1 & -y1); } x += (x & -x); } } long read(int x,int y){ long sum = 0; int y1; while (x >0){ y1 = y; while (y1 >0){ sum+=tree[x][y1]; y1 -= (y1 & -y1); } x -= (x & -x); } return sum; } long sum(int lx,int rx,int ly,int ry) { return read(rx,ry)-read(rx,ly-1)-read(lx-1,ry)+read(lx-1,ly-1); } } static class tri implements Comparable<tri>{ int x, y , v; tri(int a,int b,int c){ x=a;y=b;v=c; } @Override public int compareTo(tri o) { if(x!=o.x) { return x-o.x; } return y-o.y; } public String toString() { return "("+x+" "+y+")"; } } public static void main(String[] args) throws Exception { MScanner sc=new MScanner(System.in); PrintWriter pw=new PrintWriter(System.out); int n=sc.nextInt(),m=sc.nextInt(),k=sc.nextInt(); ft2d ft=new ft2d(n+1, m+1); tri[][]gars=new tri[k][]; for(int i=0;i<k;i++) { int len=sc.nextInt(); gars[i]=new tri[len]; for(int j=0;j<len;j++) { gars[i][j]=new tri(sc.nextInt(), sc.nextInt(), sc.nextInt()); } } boolean[][]queries=new boolean[2000][k];int cntAsks=0; int q=sc.nextInt(); boolean[]garlands=new boolean[k]; int[][]qs=new int[q][4]; Arrays.fill(garlands, true); for(int o=0;o<q;o++) { String cmd=sc.next(); if(cmd.equals("ASK")) { qs[cntAsks]=sc.takearr(4); for(int i=0;i<k;i++) { queries[cntAsks][i]=garlands[i]; } cntAsks++; } else { int x=sc.nextInt()-1; garlands[x]=!garlands[x]; } } long []ans=new long[cntAsks]; for(int i=0;i<k;i++) { for(tri t:gars[i]) { ft.update(t.x, t.y, t.v); } for(int o=0;o<cntAsks;o++) { if(!queries[o][i])continue; int lx=qs[o][0],ly=qs[o][1],rx=qs[o][2],ry=qs[o][3]; long sum=ft.sum(lx, rx, ly, ry); ans[o]+=sum; } for(tri t:gars[i]) { ft.update(t.x, t.y, -t.v); } } for(long o:ans)pw.println(o); pw.flush(); } static class MScanner { StringTokenizer st; BufferedReader br; public MScanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public MScanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int[] takearr(int n) throws IOException { int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public long[] takearrl(int n) throws IOException { long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } public Integer[] takearrobj(int n) throws IOException { Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public Long[] takearrlobj(int n) throws IOException { Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } }
Java
["4 4 3\n5\n1 1 2\n1 2 3\n2 2 1\n2 1 4\n3 1 7\n4\n1 3 1\n2 3 3\n2 4 3\n1 4 1\n7\n4 1 1\n4 2 9\n3 2 8\n3 3 3\n4 3 4\n4 4 1\n3 4 1\n2\nASK 2 2 3 3\nASK 1 1 4 4", "4 4 1\n8\n4 1 1\n3 1 2\n2 1 1\n1 1 7\n1 2 5\n2 2 4\n2 3 1\n1 3 1\n3\nASK 1 1 3 2\nSWITCH 1\nASK 1 1 3 2"]
3 seconds
["15\n52", "19\n0"]
NoteThis image illustrates the first sample case.
Java 11
standard input
[ "data structures" ]
a45f38aae8dadb6f0991b41ecb1be855
The first line of the input contains three integers n, m and k (1 ≤ n, m, k ≤ 2000) — the number of field rows, the number of field columns and the number of garlands placed at the field respectively. Next lines contains garlands set description in the following format: The first line of a single garland description contains a single integer len (1 ≤ len ≤ 2000) — the number of lightbulbs in the garland. Each of the next len lines contains three integers i, j and w (1 ≤ i ≤ n, 1 ≤ j ≤ m, 1 ≤ w ≤ 109) — the coordinates of the cell containing a lightbullb and pleasure value Alesha gets from it if it is turned on. The lightbulbs are given in the order they are forming a chain in the garland. It is guaranteed that neighbouring lightbulbs are placed in the cells neighbouring by a side. The next line contains single integer q (1 ≤ q ≤ 106) — the number of events in Alesha's game. The next q lines describes events in chronological order. The i-th of them describes the i-th event in the one of the following formats: SWITCH i — Alesha turns off i-th garland if it is turned on, or turns it on if it is turned off. It is guaranteed that 1 ≤ i ≤ k. ASK x1 y1 x2 y2 — Alesha wants to know the sum of pleasure values the lightbulbs, placed in a rectangular part of the field. Top-left cell of a part has coordinates (x1, y1) and right-bottom cell has coordinates (x2, y2). It is guaranteed that 1 ≤ x1 ≤ x2 ≤ n and 1 ≤ y1 ≤ y2 ≤ m. There is no more than 2000 events of this type in the input. All the numbers in the input are integers. Please note that the input is quite large, so be careful while using some input ways. In particular, it's not recommended to use cin in codes on C++ and class Scanner in codes on Java.
2,400
For each ASK operation print the sum Alesha wants to know in a separate line. Print the answers in chronological order.
standard output
PASSED
004672080e92a4b005204806f08f41cf
train_000.jsonl
1492356900
You are given a convex polygon P with n distinct vertices p1, p2, ..., pn. Vertex pi has coordinates (xi, yi) in the 2D plane. These vertices are listed in clockwise order.You can choose a real number D and move each vertex of the polygon a distance of at most D from their original positions.Find the maximum value of D such that no matter how you move the vertices, the polygon does not intersect itself and stays convex.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.Reader; import java.util.StringTokenizer; public class TaskB { public static void main(String[] args) throws Exception { Tokenizer in = new Tokenizer(new InputStreamReader(System.in)); int n = in.nextInt(); Point[] p = new Point[n]; double res = Double.MAX_VALUE; for(int i = 0; i < n; i++) p[i] = new Point(in.nextLong(), in.nextLong()); for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { if(i == j) continue; Point A = p[i], B = p[j]; res = Math.min(res, Math.sqrt(sqr(A.x - B.x) + sqr(A.y - B.y)) / 2); } } for(int i = 0; i < n; i++) { Point A = p[i], B = p[(i + 2) % n], C = p[(i + 1) % n]; Point AC = new Point(C.x - A.x, C.y - A.y); Point AB = new Point(B.x - A.x, B.y - A.y); double h = Math.abs((AC.x * AB.y - AC.y * AB.x) / Math.sqrt(sqr(AB.x) + sqr(AB.y))); res = Math.min(res, h / 2); } System.out.println(res); } private static double sqr(double a) { return a * a; } private static class Point { double x, y; public Point(double _x, double _y) { x = _x; y = _y; } } private static class Tokenizer { private BufferedReader in; private StringTokenizer tokenizer; public Tokenizer(Reader reader) { in = new BufferedReader(reader); } public String next() throws Exception { while(tokenizer == null || !tokenizer.hasMoreElements()) { String line = in.readLine(); if(line == null) return null; tokenizer = new StringTokenizer(line); } return tokenizer.nextToken(); } public int nextInt() throws Exception { return Integer.parseInt(next()); } public long nextLong() throws Exception { return Long.parseLong(next()); } } }
Java
["4\n0 0\n0 1\n1 1\n1 0", "6\n5 0\n10 0\n12 -4\n10 -8\n5 -8\n3 -4"]
2 seconds
["0.3535533906", "1.0000000000"]
NoteHere is a picture of the first sampleHere is an example of making the polygon non-convex.This is not an optimal solution, since the maximum distance we moved one point is  ≈ 0.4242640687, whereas we can make it non-convex by only moving each point a distance of at most  ≈ 0.3535533906.
Java 8
standard input
[ "geometry" ]
495488223483401ff12ae9c456b4e5fe
The first line has one integer n (4 ≤ n ≤ 1 000) — the number of vertices. The next n lines contain the coordinates of the vertices. Line i contains two integers xi and yi ( - 109 ≤ xi, yi ≤ 109) — the coordinates of the i-th vertex. These points are guaranteed to be given in clockwise order, and will form a strictly convex polygon (in particular, no three consecutive points lie on the same straight line).
1,800
Print one real number D, which is the maximum real number such that no matter how you move the vertices, the polygon stays convex. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely, let's assume that your answer is a and the answer of the jury is b. The checker program will consider your answer correct if .
standard output
PASSED
8e0c0f7f9cdba6c863f3809c37c4a73f
train_000.jsonl
1492356900
You are given a convex polygon P with n distinct vertices p1, p2, ..., pn. Vertex pi has coordinates (xi, yi) in the 2D plane. These vertices are listed in clockwise order.You can choose a real number D and move each vertex of the polygon a distance of at most D from their original positions.Find the maximum value of D such that no matter how you move the vertices, the polygon does not intersect itself and stays convex.
256 megabytes
import java.util.*; import java.io.*; public class B { FastScanner in; PrintWriter out; class Point { long x, y; public Point(long x, long y) { super(); this.x = x; this.y = y; } } Point[] pts; double vecMul(Point p0, Point p1, Point p2) { double x1 = p1.x - p0.x; double x2 = p2.x - p0.x; double y1 = p1.y - p0.y; double y2 = p2.y - p0.y; return x1 * y2 - x2 * y1; } double len(Point p, Point q) { double dx = q.x - p.x; double dy = q.y - p.y; return Math.sqrt(dx * dx + dy * dy); } public void solve() throws IOException { int n = in.nextInt(); pts = new Point[n]; for (int i = 0; i < n; i++) { pts[i] = new Point(in.nextLong(), in.nextLong()); } double ans = Double.MAX_VALUE; for (int i = 0; i < n; i++) { Point p = pts[i]; Point q = pts[(i + 1) % n]; Point r = pts[(i + 2) % n]; double curDist = Math.abs(vecMul(p, q, r)) / len(p, r); ans = Math.min(ans, curDist * 0.5); } out.println(ans); } public void run() { try { in = new FastScanner(); out = new PrintWriter(System.out); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); } } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } public static void main(String[] arg) { new B().run(); } }
Java
["4\n0 0\n0 1\n1 1\n1 0", "6\n5 0\n10 0\n12 -4\n10 -8\n5 -8\n3 -4"]
2 seconds
["0.3535533906", "1.0000000000"]
NoteHere is a picture of the first sampleHere is an example of making the polygon non-convex.This is not an optimal solution, since the maximum distance we moved one point is  ≈ 0.4242640687, whereas we can make it non-convex by only moving each point a distance of at most  ≈ 0.3535533906.
Java 8
standard input
[ "geometry" ]
495488223483401ff12ae9c456b4e5fe
The first line has one integer n (4 ≤ n ≤ 1 000) — the number of vertices. The next n lines contain the coordinates of the vertices. Line i contains two integers xi and yi ( - 109 ≤ xi, yi ≤ 109) — the coordinates of the i-th vertex. These points are guaranteed to be given in clockwise order, and will form a strictly convex polygon (in particular, no three consecutive points lie on the same straight line).
1,800
Print one real number D, which is the maximum real number such that no matter how you move the vertices, the polygon stays convex. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely, let's assume that your answer is a and the answer of the jury is b. The checker program will consider your answer correct if .
standard output
PASSED
e9a13751ab7ee4aadbadb3ef17d7f460
train_000.jsonl
1492356900
You are given a convex polygon P with n distinct vertices p1, p2, ..., pn. Vertex pi has coordinates (xi, yi) in the 2D plane. These vertices are listed in clockwise order.You can choose a real number D and move each vertex of the polygon a distance of at most D from their original positions.Find the maximum value of D such that no matter how you move the vertices, the polygon does not intersect itself and stays convex.
256 megabytes
import java.io.*; import java.util.StringTokenizer; /** * Created by gamezovladislav on 21.03.2017. */ public class TaskB { public static void main(String[] args) throws IOException { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); solve(in, out); out.close(); } private static void solve(InputReader in, PrintWriter out) { int n = in.nextInt(); double[] x = new double[n + 2]; double[] y = new double[n + 2]; for (int i = 0; i < n; i++) { x[i] = in.nextInt() * 1.0D; y[i] = in.nextInt() * 1.0D; } x[n] = x[0]; y[n] = y[0]; x[n + 1] = x[1]; y[n + 1] = y[1]; double dist = 1e15; for (int i = 0; i < n; i++) { dist = StrictMath.min(dist, foo(x[i], y[i], x[i + 2], y[i + 2], x[i + 1], y[i + 1])); } out.println(dist / 2); } private static double foo(double x1, double y1, double x2, double y2, double x, double y) { double A = y1 - y2; double B = x2 - x1; double C = -A * x1 - B * y1; return StrictMath.abs((A * x + B * y + C) / StrictMath.hypot(A, B)); } /** * A = P_y1 - Q_y2, * // B = x2 - P_x1, * // C = - A * P_x1 - B * P_y1. **/ private static double dist(double x1, double y1, double x2, double y2) { return StrictMath.hypot(x1 - x2, y1 - y2); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["4\n0 0\n0 1\n1 1\n1 0", "6\n5 0\n10 0\n12 -4\n10 -8\n5 -8\n3 -4"]
2 seconds
["0.3535533906", "1.0000000000"]
NoteHere is a picture of the first sampleHere is an example of making the polygon non-convex.This is not an optimal solution, since the maximum distance we moved one point is  ≈ 0.4242640687, whereas we can make it non-convex by only moving each point a distance of at most  ≈ 0.3535533906.
Java 8
standard input
[ "geometry" ]
495488223483401ff12ae9c456b4e5fe
The first line has one integer n (4 ≤ n ≤ 1 000) — the number of vertices. The next n lines contain the coordinates of the vertices. Line i contains two integers xi and yi ( - 109 ≤ xi, yi ≤ 109) — the coordinates of the i-th vertex. These points are guaranteed to be given in clockwise order, and will form a strictly convex polygon (in particular, no three consecutive points lie on the same straight line).
1,800
Print one real number D, which is the maximum real number such that no matter how you move the vertices, the polygon stays convex. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely, let's assume that your answer is a and the answer of the jury is b. The checker program will consider your answer correct if .
standard output
PASSED
23cb4290dec456bb0d099b87c567c28a
train_000.jsonl
1492356900
You are given a convex polygon P with n distinct vertices p1, p2, ..., pn. Vertex pi has coordinates (xi, yi) in the 2D plane. These vertices are listed in clockwise order.You can choose a real number D and move each vertex of the polygon a distance of at most D from their original positions.Find the maximum value of D such that no matter how you move the vertices, the polygon does not intersect itself and stays convex.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int[] x = new int[n]; int[] y = new int[n]; for (int i = 0; i < n; i++) { x[i] = in.nextInt(); y[i] = in.nextInt(); } double[] h = new double[n]; h[0] = getH(x[n - 1], y[n - 1], x[n - 2], y[n - 2], x[0], y[0]); h[1] = getH(x[0], y[0], x[n - 1], y[n - 1], x[1], y[1]); double hMin = Math.min(h[0], h[1]); for (int i = 2; i < n; i++) { h[i] = getH(x[i - 1], y[i - 1], x[i - 2], y[i - 2], x[i], y[i]); hMin = Math.min(hMin, h[i]); } out.println(hMin / 2); } double getH(long x, long y, long ax, long ay, long bx, long by) { double t = (bx - ax) * (y - ay) - (by - ay) * (x - ax); return Math.abs(t / fastHypot(ax - bx, ay - by)); } double fastHypot(double x, double y) { return Math.sqrt(x * x + y * y); } } static class InputReader { private BufferedReader reader; private StringTokenizer stt; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { return null; } } public String next() { while (stt == null || !stt.hasMoreTokens()) { stt = new StringTokenizer(nextLine()); } return stt.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["4\n0 0\n0 1\n1 1\n1 0", "6\n5 0\n10 0\n12 -4\n10 -8\n5 -8\n3 -4"]
2 seconds
["0.3535533906", "1.0000000000"]
NoteHere is a picture of the first sampleHere is an example of making the polygon non-convex.This is not an optimal solution, since the maximum distance we moved one point is  ≈ 0.4242640687, whereas we can make it non-convex by only moving each point a distance of at most  ≈ 0.3535533906.
Java 8
standard input
[ "geometry" ]
495488223483401ff12ae9c456b4e5fe
The first line has one integer n (4 ≤ n ≤ 1 000) — the number of vertices. The next n lines contain the coordinates of the vertices. Line i contains two integers xi and yi ( - 109 ≤ xi, yi ≤ 109) — the coordinates of the i-th vertex. These points are guaranteed to be given in clockwise order, and will form a strictly convex polygon (in particular, no three consecutive points lie on the same straight line).
1,800
Print one real number D, which is the maximum real number such that no matter how you move the vertices, the polygon stays convex. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely, let's assume that your answer is a and the answer of the jury is b. The checker program will consider your answer correct if .
standard output
PASSED
cbc0f3987c296dbdd5de982fe74fe9e4
train_000.jsonl
1492356900
You are given a convex polygon P with n distinct vertices p1, p2, ..., pn. Vertex pi has coordinates (xi, yi) in the 2D plane. These vertices are listed in clockwise order.You can choose a real number D and move each vertex of the polygon a distance of at most D from their original positions.Find the maximum value of D such that no matter how you move the vertices, the polygon does not intersect itself and stays convex.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class Solution { public static void main(String[] args) throws Exception { MyReader reader = new MyReader(System.in); MyWriter writer = new MyWriter(System.out); new Solution().run(reader, writer); writer.close(); } long[] a; long[] b; private void run(MyReader reader, MyWriter writer) throws IOException { int n = reader.nextInt(); a = new long[n + 2]; b = new long[n + 2]; for (int i = 0; i < n; i++) { a[i] = reader.nextInt(); b[i] = reader.nextInt(); } a[n] = a[0]; b[n] = b[0]; a[n + 1] = a[1]; b[n + 1] = b[1]; double min = Double.MAX_VALUE; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { double w = Math.sqrt(Math.pow(b[i] - b[j], 2) + Math.pow(a[i] - a[j], 2)); min = Math.min(min, w); } } for (int i = 0; i < n; i++) { min = Math.min(min, f(i, i + 1, i + 2)); min = Math.min(min, f(i + 1, i + 2, i)); min = Math.min(min, f(i + 2, i, i + 1)); } writer.print(min / 2 + ""); } double f(int i, int j, int k) { double q = Math.abs((b[k] - b[i]) * a[j] - (a[k] - a[i]) * b[j] + a[k] * b[i] - b[k] * a[i]); double w = Math.sqrt(Math.pow(b[k] - b[i], 2) + Math.pow(a[k] - a[i], 2)); return q / w; } static class MyReader { final BufferedInputStream in; final int bufSize = 1 << 16; final byte buf[] = new byte[bufSize]; int i = bufSize; int k = bufSize; final StringBuilder str = new StringBuilder(); MyReader(InputStream in) { this.in = new BufferedInputStream(in, bufSize); } int nextInt() throws IOException { return (int) nextLong(); } int[] nextIntArray(int n) throws IOException { int[] m = new int[n]; for (int i = 0; i < n; i++) { m[i] = nextInt(); } return m; } int[][] nextIntMatrix(int n, int m) throws IOException { int[][] a = new int[n][0]; for (int j = 0; j < n; j++) { a[j] = nextIntArray(m); } return a; } long nextLong() throws IOException { int c; long x = 0; boolean sign = true; while ((c = nextChar()) <= 32) ; if (c == '-') { sign = false; c = nextChar(); } if (c == '+') { c = nextChar(); } while (c >= '0') { x = x * 10 + (c - '0'); c = nextChar(); } return sign ? x : -x; } long[] nextLongArray(int n) throws IOException { long[] m = new long[n]; for (int i = 0; i < n; i++) { m[i] = nextLong(); } return m; } String nextString() throws IOException { int c; str.setLength(0); while ((c = nextChar()) <= 32 && c != -1) ; if (c == -1) { return null; } while (c > 32) { str.append((char) c); c = nextChar(); } return str.toString(); } String[] nextStringArray(int n) throws IOException { String[] m = new String[n]; for (int i = 0; i < n; i++) { m[i] = nextString(); } return m; } int nextChar() throws IOException { if (i == k) { k = in.read(buf, 0, bufSize); i = 0; } return i >= k ? -1 : buf[i++]; } } static class MyWriter { final BufferedOutputStream out; final int bufSize = 1 << 16; final byte buf[] = new byte[bufSize]; int i = 0; final byte c[] = new byte[30]; static final String newLine = System.getProperty("line.separator"); MyWriter(OutputStream out) { this.out = new BufferedOutputStream(out, bufSize); } void print(long x) throws IOException { int j = 0; if (i + 30 >= bufSize) { flush(); } if (x < 0) { buf[i++] = (byte) ('-'); x = -x; } while (j == 0 || x != 0) { c[j++] = (byte) (x % 10 + '0'); x /= 10; } while (j-- > 0) buf[i++] = c[j]; } void print(int[] m) throws Exception { for (int a : m) { print(a); print(' '); } } void print(long[] m) throws Exception { for (long a : m) { print(a); print(' '); } } void print(String s) throws IOException { for (int i = 0; i < s.length(); i++) { print(s.charAt(i)); } } void print(char x) throws IOException { if (i == bufSize) { flush(); } buf[i++] = (byte) x; } void print(char[] m) throws Exception { for (char c : m) { print(c); } } void println(String s) throws IOException { print(s); println(); } void println() throws IOException { print(newLine); } void flush() throws IOException { out.write(buf, 0, i); i = 0; } void close() throws IOException { flush(); out.close(); } } }
Java
["4\n0 0\n0 1\n1 1\n1 0", "6\n5 0\n10 0\n12 -4\n10 -8\n5 -8\n3 -4"]
2 seconds
["0.3535533906", "1.0000000000"]
NoteHere is a picture of the first sampleHere is an example of making the polygon non-convex.This is not an optimal solution, since the maximum distance we moved one point is  ≈ 0.4242640687, whereas we can make it non-convex by only moving each point a distance of at most  ≈ 0.3535533906.
Java 8
standard input
[ "geometry" ]
495488223483401ff12ae9c456b4e5fe
The first line has one integer n (4 ≤ n ≤ 1 000) — the number of vertices. The next n lines contain the coordinates of the vertices. Line i contains two integers xi and yi ( - 109 ≤ xi, yi ≤ 109) — the coordinates of the i-th vertex. These points are guaranteed to be given in clockwise order, and will form a strictly convex polygon (in particular, no three consecutive points lie on the same straight line).
1,800
Print one real number D, which is the maximum real number such that no matter how you move the vertices, the polygon stays convex. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely, let's assume that your answer is a and the answer of the jury is b. The checker program will consider your answer correct if .
standard output
PASSED
0b4773f44834cfec3cd46ea4e53c4c4c
train_000.jsonl
1492356900
You are given a convex polygon P with n distinct vertices p1, p2, ..., pn. Vertex pi has coordinates (xi, yi) in the 2D plane. These vertices are listed in clockwise order.You can choose a real number D and move each vertex of the polygon a distance of at most D from their original positions.Find the maximum value of D such that no matter how you move the vertices, the polygon does not intersect itself and stays convex.
256 megabytes
import java.io.*; import java.util.*; public class solver { static BufferedReader in; static PrintWriter out; static StringTokenizer tok = new StringTokenizer(""); public static void main(String[] args) throws IOException { String filename = ""; if (filename.isEmpty()) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader(filename + ".in")); out = new PrintWriter(filename + ".out"); } solve(); out.close(); } static String readString() throws IOException { while (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } static int readInt() throws IOException { return Integer.parseInt(readString()); } static long readLong() throws IOException { return Long.parseLong(readString()); } private static void solve() throws IOException { int n = readInt(); Pair[] points = new Pair[n]; for (int i = 0; i < n; i++) { points[i] = new Pair(readInt(), readInt()); } double ans = Double.MAX_VALUE; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == j) continue; double a = Math.sqrt(length2(points[i], points[j])); ans = Math.min(ans, a / 2.0); } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (j == i || j == (i + 1) % n) continue; double a = Math.sqrt(length2(points[i], points[(i + 1) % n])); double b = Math.sqrt(length2(points[(i + 1) % n], points[j])); double c = Math.sqrt(length2(points[i], points[j])); double s = s2(points[i], points[(i + 1) % n], points[j]); double h = s / a; ans = Math.min(ans, h / 2.0); h = s / b; ans = Math.min(ans, h / 2.0); h = s / c; ans = Math.min(ans, h / 2.0); } } //out.println(Long.MAX_VALUE); out.print(ans); } static long s2(Pair p1, Pair p2, Pair p3) { return Math.abs((p2.x - p1.x) * (p3.y - p1.y) - (p2.y - p1.y) * (p3.x - p1.x)); } static long length2(Pair p1, Pair p2) { return (p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y); } static class Pair { long x, y; public Pair(long x, long y) { this.x = x; this.y = y; } } }
Java
["4\n0 0\n0 1\n1 1\n1 0", "6\n5 0\n10 0\n12 -4\n10 -8\n5 -8\n3 -4"]
2 seconds
["0.3535533906", "1.0000000000"]
NoteHere is a picture of the first sampleHere is an example of making the polygon non-convex.This is not an optimal solution, since the maximum distance we moved one point is  ≈ 0.4242640687, whereas we can make it non-convex by only moving each point a distance of at most  ≈ 0.3535533906.
Java 8
standard input
[ "geometry" ]
495488223483401ff12ae9c456b4e5fe
The first line has one integer n (4 ≤ n ≤ 1 000) — the number of vertices. The next n lines contain the coordinates of the vertices. Line i contains two integers xi and yi ( - 109 ≤ xi, yi ≤ 109) — the coordinates of the i-th vertex. These points are guaranteed to be given in clockwise order, and will form a strictly convex polygon (in particular, no three consecutive points lie on the same straight line).
1,800
Print one real number D, which is the maximum real number such that no matter how you move the vertices, the polygon stays convex. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely, let's assume that your answer is a and the answer of the jury is b. The checker program will consider your answer correct if .
standard output
PASSED
5fcc2e763a02c6a505b3ec4facfc467f
train_000.jsonl
1492356900
You are given a convex polygon P with n distinct vertices p1, p2, ..., pn. Vertex pi has coordinates (xi, yi) in the 2D plane. These vertices are listed in clockwise order.You can choose a real number D and move each vertex of the polygon a distance of at most D from their original positions.Find the maximum value of D such that no matter how you move the vertices, the polygon does not intersect itself and stays convex.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); Point[] points = new Point[n]; for (int i = 0; i < n; i++) points[i] = new Point(in.readInt(), in.readInt()); double res = 1e20; for (int leftIndex = 0; leftIndex < n; leftIndex++) { Point left = points[leftIndex]; Point middle = points[(leftIndex + 1) % n]; Point right = points[(leftIndex + 2) % n]; res = Math.min(res, new Segment(left, right).distance(middle) / 2); } out.printLine(res); } } static class Line { public final double a; public final double b; public final double c; public Line(Point p, double angle) { a = Math.sin(angle); b = -Math.cos(angle); c = -p.x * a - p.y * b; } public Line(double a, double b, double c) { double h = GeometryUtils.fastHypot(a, b); this.a = a / h; this.b = b / h; this.c = c / h; } public boolean parallel(Line other) { return Math.abs(a * other.b - b * other.a) < GeometryUtils.epsilon; } public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Line line = (Line) o; if (!parallel(line)) { return false; } if (Math.abs(a * line.c - c * line.a) > GeometryUtils.epsilon || Math.abs(b * line.c - c * line.b) > GeometryUtils.epsilon) { return false; } return true; } } static class GeometryUtils { public static double epsilon = 1e-8; public static double fastHypot(double x, double y) { return Math.sqrt(x * x + y * y); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class Segment { public final Point a; public final Point b; private double distance = Double.NaN; private Line line = null; public Segment(Point a, Point b) { this.a = a; this.b = b; } public double length() { if (Double.isNaN(distance)) { distance = a.distance(b); } return distance; } public double distance(Point point) { double length = length(); double left = point.distance(a); if (length < GeometryUtils.epsilon) { return left; } double right = point.distance(b); if (left * left > right * right + length * length) { return right; } if (right * right > left * left + length * length) { return left; } return point.distance(line()); } public Line line() { if (line == null) { line = a.line(b); } return line; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } static class Point { public final double x; public final double y; public String toString() { return "(" + x + ", " + y + ")"; } public Point(double x, double y) { this.x = x; this.y = y; } public Line line(Point other) { if (equals(other)) { return null; } double a = other.y - y; double b = x - other.x; double c = -a * x - b * y; return new Line(a, b, c); } public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Point point = (Point) o; return Math.abs(x - point.x) <= GeometryUtils.epsilon && Math.abs(y - point.y) <= GeometryUtils.epsilon; } public int hashCode() { int result; long temp; temp = x != +0.0d ? Double.doubleToLongBits(x) : 0L; result = (int) (temp ^ (temp >>> 32)); temp = y != +0.0d ? Double.doubleToLongBits(y) : 0L; result = 31 * result + (int) (temp ^ (temp >>> 32)); return result; } public double distance(Point other) { return GeometryUtils.fastHypot(x - other.x, y - other.y); } public double distance(Line line) { return Math.abs(line.a * x + line.b * y + line.c); } } }
Java
["4\n0 0\n0 1\n1 1\n1 0", "6\n5 0\n10 0\n12 -4\n10 -8\n5 -8\n3 -4"]
2 seconds
["0.3535533906", "1.0000000000"]
NoteHere is a picture of the first sampleHere is an example of making the polygon non-convex.This is not an optimal solution, since the maximum distance we moved one point is  ≈ 0.4242640687, whereas we can make it non-convex by only moving each point a distance of at most  ≈ 0.3535533906.
Java 8
standard input
[ "geometry" ]
495488223483401ff12ae9c456b4e5fe
The first line has one integer n (4 ≤ n ≤ 1 000) — the number of vertices. The next n lines contain the coordinates of the vertices. Line i contains two integers xi and yi ( - 109 ≤ xi, yi ≤ 109) — the coordinates of the i-th vertex. These points are guaranteed to be given in clockwise order, and will form a strictly convex polygon (in particular, no three consecutive points lie on the same straight line).
1,800
Print one real number D, which is the maximum real number such that no matter how you move the vertices, the polygon stays convex. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely, let's assume that your answer is a and the answer of the jury is b. The checker program will consider your answer correct if .
standard output
PASSED
530d38a5e2be7c89aa5d8624305fdc16
train_000.jsonl
1492356900
You are given a convex polygon P with n distinct vertices p1, p2, ..., pn. Vertex pi has coordinates (xi, yi) in the 2D plane. These vertices are listed in clockwise order.You can choose a real number D and move each vertex of the polygon a distance of at most D from their original positions.Find the maximum value of D such that no matter how you move the vertices, the polygon does not intersect itself and stays convex.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); int[] x = new int[n], y = new int[n]; IOUtils.readIntArrays(in, x, y); Point[] points = new Point[n]; for (int i = 0; i < n; i++) { points[i] = new Point(x[i], y[i]); } double low = 0, high = 1e10; for (int iter = 0; iter < 130; iter++) { double mid = (low + high) / 2; if (nonConvex(mid, points)) { high = mid; } else { low = mid; } } out.printLine(low); } private boolean nonConvex(double moveBy, Point[] points) { for (int leftIndex = 0; leftIndex < points.length; leftIndex++) { Point left = points[leftIndex]; Point middle = points[(leftIndex + 1) % points.length]; Point right = points[(leftIndex + 2) % points.length]; if (left.distance(middle) <= moveBy || right.distance(middle) <= moveBy) return true; Line l = left.line(right); if (l.distance(middle) <= 2 * moveBy) return true; } return false; } } static class IOUtils { public static void readIntArrays(InputReader in, int[]... arrays) { for (int i = 0; i < arrays[0].length; i++) { for (int j = 0; j < arrays.length; j++) { arrays[j][i] = in.readInt(); } } } } static class Point { public final double x; public final double y; public String toString() { return "(" + x + ", " + y + ")"; } public Point(double x, double y) { this.x = x; this.y = y; } public Line line(Point other) { if (equals(other)) { return null; } double a = other.y - y; double b = x - other.x; double c = -a * x - b * y; return new Line(a, b, c); } public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Point point = (Point) o; return Math.abs(x - point.x) <= GeometryUtils.epsilon && Math.abs(y - point.y) <= GeometryUtils.epsilon; } public int hashCode() { int result; long temp; temp = x != +0.0d ? Double.doubleToLongBits(x) : 0L; result = (int) (temp ^ (temp >>> 32)); temp = y != +0.0d ? Double.doubleToLongBits(y) : 0L; result = 31 * result + (int) (temp ^ (temp >>> 32)); return result; } public double distance(Point other) { return GeometryUtils.fastHypot(x - other.x, y - other.y); } } static class GeometryUtils { public static double epsilon = 1e-8; public static double fastHypot(double x, double y) { return Math.sqrt(x * x + y * y); } } static class Line { public final double a; public final double b; public final double c; public Line(Point p, double angle) { a = Math.sin(angle); b = -Math.cos(angle); c = -p.x * a - p.y * b; } public Line(double a, double b, double c) { double h = GeometryUtils.fastHypot(a, b); this.a = a / h; this.b = b / h; this.c = c / h; } public boolean parallel(Line other) { return Math.abs(a * other.b - b * other.a) < GeometryUtils.epsilon; } public double value(Point point) { return a * point.x + b * point.y + c; } public double distance(Point center) { return Math.abs(value(center)); } public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Line line = (Line) o; if (!parallel(line)) { return false; } if (Math.abs(a * line.c - c * line.a) > GeometryUtils.epsilon || Math.abs(b * line.c - c * line.b) > GeometryUtils.epsilon) { return false; } return true; } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } }
Java
["4\n0 0\n0 1\n1 1\n1 0", "6\n5 0\n10 0\n12 -4\n10 -8\n5 -8\n3 -4"]
2 seconds
["0.3535533906", "1.0000000000"]
NoteHere is a picture of the first sampleHere is an example of making the polygon non-convex.This is not an optimal solution, since the maximum distance we moved one point is  ≈ 0.4242640687, whereas we can make it non-convex by only moving each point a distance of at most  ≈ 0.3535533906.
Java 8
standard input
[ "geometry" ]
495488223483401ff12ae9c456b4e5fe
The first line has one integer n (4 ≤ n ≤ 1 000) — the number of vertices. The next n lines contain the coordinates of the vertices. Line i contains two integers xi and yi ( - 109 ≤ xi, yi ≤ 109) — the coordinates of the i-th vertex. These points are guaranteed to be given in clockwise order, and will form a strictly convex polygon (in particular, no three consecutive points lie on the same straight line).
1,800
Print one real number D, which is the maximum real number such that no matter how you move the vertices, the polygon stays convex. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely, let's assume that your answer is a and the answer of the jury is b. The checker program will consider your answer correct if .
standard output
PASSED
772760357afcb73605ba2976262d61aa
train_000.jsonl
1492356900
You are given a convex polygon P with n distinct vertices p1, p2, ..., pn. Vertex pi has coordinates (xi, yi) in the 2D plane. These vertices are listed in clockwise order.You can choose a real number D and move each vertex of the polygon a distance of at most D from their original positions.Find the maximum value of D such that no matter how you move the vertices, the polygon does not intersect itself and stays convex.
256 megabytes
import static java.lang.Math.*; import static java.lang.System.currentTimeMillis; import static java.lang.System.exit; import static java.lang.System.arraycopy; import static java.util.Arrays.sort; import static java.util.Arrays.binarySearch; import static java.util.Arrays.fill; import java.util.*; import java.io.*; @SuppressWarnings("unused") public class Main { public static void main(String[] args) throws IOException { new Main().run(); } BufferedReader in; PrintWriter out; StringTokenizer st = new StringTokenizer(""); private void run() throws IOException { if (new File("input.txt").exists()) in = new BufferedReader(new FileReader("input.txt")); else in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); in.close(); out.close(); } private void solve() throws IOException { int n = nextInt(); double x[] = new double[n + 2]; double y[] = new double[n + 2]; for (int i = 0; i < n; i++) { x[i] = nextLong(); y[i] = nextLong(); } x[n] = x[0]; x[n + 1] = x[1]; y[n] = y[0]; y[n + 1] = y[1]; double ans = 1.E20; for (int i = 0; i < n; i++) { double x1 = x[i + 2] - x[i]; double y1 = y[i + 2] - y[i]; double x2 = x[i + 1] - x[i]; double y2 = y[i + 1] - y[i]; double s = abs(x1 * y2 - x2 * y1); double m = x1 * x1 + y1 * y1; double d = sqrt(m); d = s / d; ans = min(ans, d / 2.); x1 = x[i + 1] - x[i]; y1 = y[i + 1] - y[i]; x2 = x[i + 2] - x[i]; y2 = y[i + 2] - y[i]; s = abs(x1 * y2 - x2 * y1); m = x1 * x1 + y1 * y1; d = sqrt(m); d = s / d; ans = min(ans, d / 2.); x1 = x[i + 2] - x[i + 1]; y1 = y[i + 2] - y[i + 1]; x2 = x[i] - x[i + 1]; y2 = y[i] - y[i + 1]; s = abs(x1 * y2 - x2 * y1); m = x1 * x1 + y1 * y1; d = sqrt(m); d = s / d; // System.err.println(x1 + " " + y1 + " " + x2 + " " + y2); // System.err.println(s); ans = min(ans, d / 2.); } out.printf(Locale.US, "%.10f", ans); } void chk(boolean b) { if (b) return; System.out.println(new Error().getStackTrace()[1]); exit(999); } void deb(String fmt, Object... args) { System.out.printf(Locale.US, fmt + "%n", args); } String nextToken() throws IOException { while (!st.hasMoreTokens()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextLine() throws IOException { st = new StringTokenizer(""); return in.readLine(); } boolean EOF() throws IOException { while (!st.hasMoreTokens()) { String s = in.readLine(); if (s == null) return true; st = new StringTokenizer(s); } return false; } }
Java
["4\n0 0\n0 1\n1 1\n1 0", "6\n5 0\n10 0\n12 -4\n10 -8\n5 -8\n3 -4"]
2 seconds
["0.3535533906", "1.0000000000"]
NoteHere is a picture of the first sampleHere is an example of making the polygon non-convex.This is not an optimal solution, since the maximum distance we moved one point is  ≈ 0.4242640687, whereas we can make it non-convex by only moving each point a distance of at most  ≈ 0.3535533906.
Java 8
standard input
[ "geometry" ]
495488223483401ff12ae9c456b4e5fe
The first line has one integer n (4 ≤ n ≤ 1 000) — the number of vertices. The next n lines contain the coordinates of the vertices. Line i contains two integers xi and yi ( - 109 ≤ xi, yi ≤ 109) — the coordinates of the i-th vertex. These points are guaranteed to be given in clockwise order, and will form a strictly convex polygon (in particular, no three consecutive points lie on the same straight line).
1,800
Print one real number D, which is the maximum real number such that no matter how you move the vertices, the polygon stays convex. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely, let's assume that your answer is a and the answer of the jury is b. The checker program will consider your answer correct if .
standard output
PASSED
e0120bb8048ae258f793bbd7c4b69a6e
train_000.jsonl
1492356900
You are given a convex polygon P with n distinct vertices p1, p2, ..., pn. Vertex pi has coordinates (xi, yi) in the 2D plane. These vertices are listed in clockwise order.You can choose a real number D and move each vertex of the polygon a distance of at most D from their original positions.Find the maximum value of D such that no matter how you move the vertices, the polygon does not intersect itself and stays convex.
256 megabytes
import java.util.*; import java.io.*; public class B { class Line { double a, b, c; public Line(int x1, int y1, int x2, int y2) { a = y2 - y1; b = x1 - x2; c = -(a * x1 + b * y1); } double dist(int x, int y) { double d = a * x + b * y + c; return Math.abs(d) / Math.sqrt(a * a + b * b); } } void solve() { int n = in.nextInt(); int[] x = new int[n], y = new int[n]; double result = Long.MAX_VALUE; for (int i = 0; i < n; i++) { x[i] = in.nextInt(); y[i] = in.nextInt(); } for (int i = 0; i < n; i++) { Line l = new Line(x[i], y[i], x[(i + 1) % n], y[(i + 1) % n]); for (int j = 0; j < n; j++) { if (j == i || j == (i + 1) % n) { continue; } result = Math.min(result, l.dist(x[j], y[j]) / 2); } l = new Line(x[i], y[i], x[(i + 2) % n], y[(i + 2) % n]); result = Math.min(result, l.dist(x[(i + 1) % n], y[(i + 1) % n]) / 2); } out.println(result); } FastScanner in; PrintWriter out; void run() { in = new FastScanner(); out = new PrintWriter(System.out); solve(); out.close(); } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } public static void main(String[] args) { new B().run(); } }
Java
["4\n0 0\n0 1\n1 1\n1 0", "6\n5 0\n10 0\n12 -4\n10 -8\n5 -8\n3 -4"]
2 seconds
["0.3535533906", "1.0000000000"]
NoteHere is a picture of the first sampleHere is an example of making the polygon non-convex.This is not an optimal solution, since the maximum distance we moved one point is  ≈ 0.4242640687, whereas we can make it non-convex by only moving each point a distance of at most  ≈ 0.3535533906.
Java 8
standard input
[ "geometry" ]
495488223483401ff12ae9c456b4e5fe
The first line has one integer n (4 ≤ n ≤ 1 000) — the number of vertices. The next n lines contain the coordinates of the vertices. Line i contains two integers xi and yi ( - 109 ≤ xi, yi ≤ 109) — the coordinates of the i-th vertex. These points are guaranteed to be given in clockwise order, and will form a strictly convex polygon (in particular, no three consecutive points lie on the same straight line).
1,800
Print one real number D, which is the maximum real number such that no matter how you move the vertices, the polygon stays convex. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely, let's assume that your answer is a and the answer of the jury is b. The checker program will consider your answer correct if .
standard output
PASSED
8a66475f13832417e4fc6f8cce2a5fd0
train_000.jsonl
1492356900
You are given a convex polygon P with n distinct vertices p1, p2, ..., pn. Vertex pi has coordinates (xi, yi) in the 2D plane. These vertices are listed in clockwise order.You can choose a real number D and move each vertex of the polygon a distance of at most D from their original positions.Find the maximum value of D such that no matter how you move the vertices, the polygon does not intersect itself and stays convex.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.PrintStream; import java.io.BufferedInputStream; import java.util.concurrent.Callable; 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; BufferedInputStream in = new BufferedInputStream(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { public void solve(int testNumber, BufferedInputStream _in, PrintWriter out) { InputReader in = new InputReader(_in); long startTime = System.currentTimeMillis(); int nt = 1; Task t = new Task(1); t.readInput(in); t.call(); t.writeOutput(out); in.close(); System.err.println("Time: " + (System.currentTimeMillis() - startTime) + " miliseconds"); } } static class Line { Point a; Point ab; Line(Point a, Point b, boolean twoPoints) { this.a = new Point(a); if (twoPoints) { this.ab = Point._opSub(b, a); } else { this.ab = new Point(b); } } Line(long xa, long ya, long xb, long yb) { this.a = new Point(xa, ya); this.ab = new Point((xb - xa), (yb - ya)); } Point b() { return Point._opPlus(a, ab); } public String toString() { return "Line{" + "(" + a + ") (" + b() + ")}"; } public double distLine(Point point) { //if (!line) return dist(point, line.a); //return abs((point - line.a) ^ line.ab) / norm(line.ab); if (this.ab.isZeroPoint()) return a.dist(point); Point temp = Point._opSub(point, this.a); long temp2 = Point._opPow(temp, ab); return Math.abs(temp2) / this.ab.norm(); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new 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 static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public void close() { } } static class Point implements Comparable<Point> { public long x; public long y; public Point(Point o) { this.x = o.x; this.y = o.y; } public Point(long x, long y) { super(); this.x = x; this.y = y; } public boolean isZeroPoint() { return x == 0 && y == 0; } public int compareTo(Point o2) { int t = Long.compare(y, o2.y); if (t != 0) return t; return Long.compare(x, o2.x); } public double dist(Point p) { return Math.sqrt((x - p.x) * (x - p.x) + (y - p.y) * (y - p.y)); //return _Rational._opSub(this, p).norm(); } public long abs() { return (x * x) + (y * y); } public double norm() { return Math.sqrt(abs()); } public static long _opPow(Point lhs, Point rhs) { //return LongMath.checkedSubtract(LongMath.checkedMultiply(lhs.x , rhs.y) , LongMath.checkedMultiply(lhs.y , rhs.x)); return ((lhs.x * rhs.y) - (lhs.y * rhs.x)); } public static Point _opSub(Point lhs, Point rhs) { return new Point((lhs.x - rhs.x), (lhs.y - rhs.y)); } public static Point _opPlus(Point lhs, Point rhs) { return new Point((lhs.x + rhs.x), (lhs.y + rhs.y)); } public String toString() { return x + " " + y; } public int hashCode() { return Long.hashCode(x) ^ Long.hashCode(y); } public boolean equals(Object obj) { if (obj instanceof Point) { return compareTo((Point) obj) == 0; } return false; } } static class Polygon { public ArrayList<Point> lp = new ArrayList<>(); int next(int i) { return i == lp.size() - 1 ? 0 : i + 1; } int prev(int i) { return i == 0 ? lp.size() - 1 : i - 1; } public String toString() { return "[" + lp + "]"; } public Point get(int v) { return lp.get(v); } } static class Task implements Callable<Task> { Polygon poly = new Polygon(); int n; double re = Double.MAX_VALUE; int testNumber; public void readInput(InputReader in) { /* read input here */ n = in.nextInt(); for (int i = 0; i < n; ++i) { poly.lp.add(new Point(in.nextInt(), in.nextInt())); } } public Task call() { /* process main algorithm here */ for (int i = 0; i < n; ++i) { Line l = new Line(poly.get(poly.next(i)), poly.get(poly.prev(i)), true); re = Math.min(re, l.distLine(poly.get(i)) / 2.0); } System.err.println("Test case: " + testNumber + " done!"); return this; } public void writeOutput(PrintWriter out) { out.println(String.format("%.30f", re)); } Task(int testNumber) { this.testNumber = testNumber; } } }
Java
["4\n0 0\n0 1\n1 1\n1 0", "6\n5 0\n10 0\n12 -4\n10 -8\n5 -8\n3 -4"]
2 seconds
["0.3535533906", "1.0000000000"]
NoteHere is a picture of the first sampleHere is an example of making the polygon non-convex.This is not an optimal solution, since the maximum distance we moved one point is  ≈ 0.4242640687, whereas we can make it non-convex by only moving each point a distance of at most  ≈ 0.3535533906.
Java 8
standard input
[ "geometry" ]
495488223483401ff12ae9c456b4e5fe
The first line has one integer n (4 ≤ n ≤ 1 000) — the number of vertices. The next n lines contain the coordinates of the vertices. Line i contains two integers xi and yi ( - 109 ≤ xi, yi ≤ 109) — the coordinates of the i-th vertex. These points are guaranteed to be given in clockwise order, and will form a strictly convex polygon (in particular, no three consecutive points lie on the same straight line).
1,800
Print one real number D, which is the maximum real number such that no matter how you move the vertices, the polygon stays convex. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely, let's assume that your answer is a and the answer of the jury is b. The checker program will consider your answer correct if .
standard output
PASSED
a6368ba68ff74a76f69b67fd517bfcee
train_000.jsonl
1492356900
You are given a convex polygon P with n distinct vertices p1, p2, ..., pn. Vertex pi has coordinates (xi, yi) in the 2D plane. These vertices are listed in clockwise order.You can choose a real number D and move each vertex of the polygon a distance of at most D from their original positions.Find the maximum value of D such that no matter how you move the vertices, the polygon does not intersect itself and stays convex.
256 megabytes
import java.util.*; import java.awt.geom.Line2D; import java.io.*; public class VolatileKite { /************************ SOLUTION STARTS HERE ************************/ static double dot(double[] A, double[] B, double[] C){ double[] AB = new double[2]; double[] BC = new double[2]; AB[0] = B[0]-A[0]; AB[1] = B[1]-A[1]; BC[0] = C[0]-B[0]; BC[1] = C[1]-B[1]; double dot = AB[0] * BC[0] + AB[1] * BC[1]; return dot; } //Compute the cross product AB x AC static double cross(double[] A, double[] B, double[] C){ double[] AB = new double[2]; double[] AC = new double[2]; AB[0] = B[0]-A[0]; AB[1] = B[1]-A[1]; AC[0] = C[0]-A[0]; AC[1] = C[1]-A[1]; double cross = AB[0] * AC[1] - AB[1] * AC[0]; return cross; } //Compute the distance from A to B static double distance(double[] A, double[] B){ double d1 = A[0] - B[0]; double d2 = A[1] - B[1]; return Math.sqrt(d1*d1+d2*d2); } //Compute the distance from AB to C //if isSegment is true, AB is a segment, not a line. static double linePointDist(double[] A, double[] B, double[] C, boolean isSegment){ double dist = cross(A,B,C) / distance(A,B); if(isSegment){ double dot1 = dot(A,B,C); if(dot1 > 0)return distance(B,C); double dot2 = dot(B,A,C); if(dot2 > 0)return distance(A,C); } return Math.abs(dist); } private static void solve() { int n = nextInt(); double p[][] = new double[n][2]; for(int i = 0; i < n; i++) { p[i][0] = nextDouble(); p[i][1] = nextDouble(); } double min = Double.MAX_VALUE; for(int i = 0; i < n; i++) { int prev = (i - 1 + n) % n; int next = (i + 1) % n; min = Math.min(min , linePointDist(p[prev], p[next], p[i], true)); // min = Math.min(Line2D.Double.ptSegDist(p[prev][0], p[prev][1], p[next][0], p[next][1], p[i][0], p[i][1]), min); } println(min / 2.0); } /************************ SOLUTION ENDS HERE ************************/ /************************ TEMPLATE STARTS HERE **********************/ public static void main(String[] args) throws IOException { reader = new BufferedReader(new InputStreamReader(System.in)); writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), false); st = null; solve(); reader.close(); writer.close(); } static BufferedReader reader; static PrintWriter writer; static StringTokenizer st; static String next() {while(st == null || !st.hasMoreTokens()){try{String line = reader.readLine();if(line == null){return null;} st = new StringTokenizer(line);}catch (Exception e){throw new RuntimeException();}}return st.nextToken();} static String nextLine() {String s=null;try{s=reader.readLine();}catch(IOException e){e.printStackTrace();}return s;} static int nextInt() {return Integer.parseInt(next());} static long nextLong() {return Long.parseLong(next());} static double nextDouble(){return Double.parseDouble(next());} static char nextChar() {return next().charAt(0);} static int[] nextIntArray(int n) {int[] a= new int[n]; int i=0;while(i<n){a[i++]=nextInt();} return a;} static long[] nextLongArray(int n) {long[]a= new long[n]; int i=0;while(i<n){a[i++]=nextLong();} return a;} static int[] nextIntArrayOneBased(int n) {int[] a= new int[n+1]; int i=1;while(i<=n){a[i++]=nextInt();} return a;} static long[] nextLongArrayOneBased(int n){long[]a= new long[n+1];int i=1;while(i<=n){a[i++]=nextLong();}return a;} static void print(Object o) { writer.print(o); } static void println(Object o){ writer.println(o);} /************************ TEMPLATE ENDS HERE ************************/ }
Java
["4\n0 0\n0 1\n1 1\n1 0", "6\n5 0\n10 0\n12 -4\n10 -8\n5 -8\n3 -4"]
2 seconds
["0.3535533906", "1.0000000000"]
NoteHere is a picture of the first sampleHere is an example of making the polygon non-convex.This is not an optimal solution, since the maximum distance we moved one point is  ≈ 0.4242640687, whereas we can make it non-convex by only moving each point a distance of at most  ≈ 0.3535533906.
Java 8
standard input
[ "geometry" ]
495488223483401ff12ae9c456b4e5fe
The first line has one integer n (4 ≤ n ≤ 1 000) — the number of vertices. The next n lines contain the coordinates of the vertices. Line i contains two integers xi and yi ( - 109 ≤ xi, yi ≤ 109) — the coordinates of the i-th vertex. These points are guaranteed to be given in clockwise order, and will form a strictly convex polygon (in particular, no three consecutive points lie on the same straight line).
1,800
Print one real number D, which is the maximum real number such that no matter how you move the vertices, the polygon stays convex. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely, let's assume that your answer is a and the answer of the jury is b. The checker program will consider your answer correct if .
standard output
PASSED
f2c21821e0fcd6168ba540a1b0f87a3b
train_000.jsonl
1492356900
You are given a convex polygon P with n distinct vertices p1, p2, ..., pn. Vertex pi has coordinates (xi, yi) in the 2D plane. These vertices are listed in clockwise order.You can choose a real number D and move each vertex of the polygon a distance of at most D from their original positions.Find the maximum value of D such that no matter how you move the vertices, the polygon does not intersect itself and stays convex.
256 megabytes
import java.io.*; import java.util.StringTokenizer; /** * Created by gamezovladislav on 21.03.2017. */ public class TaskB { public static void main(String[] args) throws IOException { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); solve(in, out); out.close(); } private static void solve(InputReader in, PrintWriter out) { int n = in.nextInt(); double[] x = new double[n + 3]; double[] y = new double[n + 3]; for (int i = 0; i < n; i++) { x[i] = in.nextInt() * 1.0D; y[i] = in.nextInt() * 1.0D; } x[n] = x[0]; y[n] = y[0]; x[n+1] = x[1]; y[n+1] = y[1]; x[n+2] = x[2]; y[n+2] = y[2]; double dist = 1e15; for (int i = 0; i < n ; i++) { dist = StrictMath.min(dist, foo(x[i], y[i], x[i + 2], y[i + 2], x[i + 1], y[i + 1])); } out.println(dist / 2); } private static double foo(double x1, double y1, double x2, double y2, double x, double y) { double A = y1 - y2; double B = x2 - x1; double C = -A * x1 - B * y1; return StrictMath.abs((A * x + B * y + C) / StrictMath.hypot(A, B)); } /** * A = P_y1 - Q_y2, * // B = x2 - P_x1, * // C = - A * P_x1 - B * P_y1. **/ private static double dist(double x1, double y1, double x2, double y2) { return StrictMath.hypot(x1 - x2, y1 - y2); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["4\n0 0\n0 1\n1 1\n1 0", "6\n5 0\n10 0\n12 -4\n10 -8\n5 -8\n3 -4"]
2 seconds
["0.3535533906", "1.0000000000"]
NoteHere is a picture of the first sampleHere is an example of making the polygon non-convex.This is not an optimal solution, since the maximum distance we moved one point is  ≈ 0.4242640687, whereas we can make it non-convex by only moving each point a distance of at most  ≈ 0.3535533906.
Java 8
standard input
[ "geometry" ]
495488223483401ff12ae9c456b4e5fe
The first line has one integer n (4 ≤ n ≤ 1 000) — the number of vertices. The next n lines contain the coordinates of the vertices. Line i contains two integers xi and yi ( - 109 ≤ xi, yi ≤ 109) — the coordinates of the i-th vertex. These points are guaranteed to be given in clockwise order, and will form a strictly convex polygon (in particular, no three consecutive points lie on the same straight line).
1,800
Print one real number D, which is the maximum real number such that no matter how you move the vertices, the polygon stays convex. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely, let's assume that your answer is a and the answer of the jury is b. The checker program will consider your answer correct if .
standard output
PASSED
6e8c3a021c412b45c35d6c5ca344b55e
train_000.jsonl
1492356900
You are given a convex polygon P with n distinct vertices p1, p2, ..., pn. Vertex pi has coordinates (xi, yi) in the 2D plane. These vertices are listed in clockwise order.You can choose a real number D and move each vertex of the polygon a distance of at most D from their original positions.Find the maximum value of D such that no matter how you move the vertices, the polygon does not intersect itself and stays convex.
256 megabytes
import java.util.*; import java.io.*; public class TaskB { FastScanner in; PrintWriter out; public void solve() throws IOException { int n = in.nextInt(); long[] x = new long[n]; long[] y = new long[n]; for (int i = 0; i < n; i++) { x[i] = in.nextInt(); y[i] = in.nextInt(); } double r = Math.sqrt((x[0] - x[1]) * (x[0] - x[1]) + (y[0] - y[1]) * (y[0] - y[1])); for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { double d = Math.sqrt((x[i] - x[j]) * (x[i] - x[j]) + (y[i] - y[j]) * (y[i] - y[j])); if (d < r) { r = d; } } } r = r / 2; double min = 1000000000000000000.0; for (int i = 0; i < n; i++) { int j = (i + 2) % n; int k = (i + 1) % n; double a = y[i] - y[j]; double b = x[j] - x[i]; double c = x[i] * y[j] - x[j] * y[i]; double d = Math.abs((a * x[k] + b * y[k] + c)) / Math.sqrt(a * a + b * b); if (d < min) { min = d; } } min = min / 2; if (r < min) { min = r; } out.println(min); } public void run() { try { in = new FastScanner(new InputStreamReader(System.in)); out = new PrintWriter(new BufferedWriter(new OutputStreamWriter( System.out))); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); } } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(InputStreamReader isr) { br = new BufferedReader(isr); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } } public static void main(String[] arg) { new TaskB().run(); } }
Java
["4\n0 0\n0 1\n1 1\n1 0", "6\n5 0\n10 0\n12 -4\n10 -8\n5 -8\n3 -4"]
2 seconds
["0.3535533906", "1.0000000000"]
NoteHere is a picture of the first sampleHere is an example of making the polygon non-convex.This is not an optimal solution, since the maximum distance we moved one point is  ≈ 0.4242640687, whereas we can make it non-convex by only moving each point a distance of at most  ≈ 0.3535533906.
Java 8
standard input
[ "geometry" ]
495488223483401ff12ae9c456b4e5fe
The first line has one integer n (4 ≤ n ≤ 1 000) — the number of vertices. The next n lines contain the coordinates of the vertices. Line i contains two integers xi and yi ( - 109 ≤ xi, yi ≤ 109) — the coordinates of the i-th vertex. These points are guaranteed to be given in clockwise order, and will form a strictly convex polygon (in particular, no three consecutive points lie on the same straight line).
1,800
Print one real number D, which is the maximum real number such that no matter how you move the vertices, the polygon stays convex. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely, let's assume that your answer is a and the answer of the jury is b. The checker program will consider your answer correct if .
standard output
PASSED
123602289da5f79177da6b0947a84319
train_000.jsonl
1492356900
You are given a convex polygon P with n distinct vertices p1, p2, ..., pn. Vertex pi has coordinates (xi, yi) in the 2D plane. These vertices are listed in clockwise order.You can choose a real number D and move each vertex of the polygon a distance of at most D from their original positions.Find the maximum value of D such that no matter how you move the vertices, the polygon does not intersect itself and stays convex.
256 megabytes
import javafx.util.Pair; import java.io.*; import java.util.StringTokenizer; /** * @author Aydar Gizatullin a.k.a. lightning95, [email protected] * Created on 16.04.17. */ public class ProbB { private void solve() { int n = rw.nextInt(); Pair<Integer, Integer>[] a = new Pair[n]; for (int i = 0; i < n; ++i) { a[i] = new Pair<>(rw.nextInt(), rw.nextInt()); } double ans = Double.MAX_VALUE; for (int i = 0; i < n; ++i) { int x1 = a[i].getKey(); int y1 = a[i].getValue(); int x0 = a[(i + 1) % n].getKey(); int y0 = a[(i + 1) % n].getValue(); int x2 = a[(i + 2) % n].getKey(); int y2 = a[(i + 2) % n].getValue(); double A = x0 - x1; double B = y0 - y1; double C = x2 - x1; double D = y2 - y1; double dot = A * C + B * D; double len_sq = C * C + D * D; double param = -1; if (len_sq != 0) //in case of 0 length line param = dot / len_sq; double xx, yy; if (param < 0) { xx = x1; yy = y1; } else if (param > 1) { xx = x2; yy = y2; } else { xx = x1 + param * C; yy = y1 + param * D; } double dx = x0 - xx; double dy = y0 - yy; double d = Math.sqrt(dx * dx + dy * dy); ans = Math.min(ans, d / 2); } rw.out.printf("%.10f", ans); } long gcd(long a, long b) { while (a > 0 && b > 0) { if (a > b) a %= b; else b %= a; } return a + b; } private RW rw; private String FILE_NAME = "file"; public static void main(String[] args) { new ProbB().run(); } private void run() { rw = new RW(FILE_NAME + ".in", FILE_NAME + ".out"); solve(); rw.close(); } private class RW { private StringTokenizer st; private PrintWriter out; private BufferedReader br; private boolean eof; RW(String inputFile, String outputFile) { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); File f = new File(inputFile); if (f.exists() && f.canRead()) { try { br = new BufferedReader(new FileReader(inputFile)); out = new PrintWriter(new FileWriter(outputFile)); } catch (IOException e) { e.printStackTrace(); } } } private String nextLine() { String s = ""; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return s; } private String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { eof = true; return "-1"; } } return st.nextToken(); } private long nextLong() { return Long.parseLong(next()); } private int nextInt() { return Integer.parseInt(next()); } private void println() { out.println(); } private void println(Object o) { out.println(o); } private void print(Object o) { out.print(o); } private void close() { try { br.close(); } catch (IOException e) { e.printStackTrace(); } out.close(); } } }
Java
["4\n0 0\n0 1\n1 1\n1 0", "6\n5 0\n10 0\n12 -4\n10 -8\n5 -8\n3 -4"]
2 seconds
["0.3535533906", "1.0000000000"]
NoteHere is a picture of the first sampleHere is an example of making the polygon non-convex.This is not an optimal solution, since the maximum distance we moved one point is  ≈ 0.4242640687, whereas we can make it non-convex by only moving each point a distance of at most  ≈ 0.3535533906.
Java 8
standard input
[ "geometry" ]
495488223483401ff12ae9c456b4e5fe
The first line has one integer n (4 ≤ n ≤ 1 000) — the number of vertices. The next n lines contain the coordinates of the vertices. Line i contains two integers xi and yi ( - 109 ≤ xi, yi ≤ 109) — the coordinates of the i-th vertex. These points are guaranteed to be given in clockwise order, and will form a strictly convex polygon (in particular, no three consecutive points lie on the same straight line).
1,800
Print one real number D, which is the maximum real number such that no matter how you move the vertices, the polygon stays convex. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely, let's assume that your answer is a and the answer of the jury is b. The checker program will consider your answer correct if .
standard output
PASSED
087ffc4b562ae7d35e2c3f88518f228f
train_000.jsonl
1492356900
You are given a convex polygon P with n distinct vertices p1, p2, ..., pn. Vertex pi has coordinates (xi, yi) in the 2D plane. These vertices are listed in clockwise order.You can choose a real number D and move each vertex of the polygon a distance of at most D from their original positions.Find the maximum value of D such that no matter how you move the vertices, the polygon does not intersect itself and stays convex.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Rustam Musin ([email protected]) */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { private int n; private Point[] all; public void solve(int testNumber, InputReader in, OutputWriter out) { all = new Point[n = in.readInt()]; for (int i = 0; i < n; i++) { all[i] = new Point(in.readInt(), in.readInt()); } double minDist = Double.MAX_VALUE; for (int i = 0; i < n; i++) { Point a = all[i]; Point b = all[(i + 1) % n]; Point c = all[(i + 2) % n]; minDist = Math.min(minDist, getDist(a, b, c)); } out.printFormat("%.10f", minDist); } private double getDist(Point a, Point b, Point c) { Vector v = new Vector(a, b); double l = 0; double r = 1; for (int i = 0; i < 100; i++) { double m1 = l + (r - l) / 3; double m2 = r - (r - l) / 3; Point toCheck1 = new Point(a.x + v.x * m1, a.y + v.y * m1); Point toCheck2 = new Point(a.x + v.x * m2, a.y + v.y * m2); double dist1 = getDist(toCheck1, a, b, c); double dist2 = getDist(toCheck2, a, b, c); if (dist1 < dist2) { r = m2; } else { l = m1; } } Point p = new Point(a.x + v.x * l, a.y + v.y * l); return getDist(p, a, b, c); } private double getDist(Point fixed, Point a, Point b, Point c) { Vector v = new Vector(b, c); double l = 0; double r = 1; for (int i = 0; i < 100; i++) { double m1 = l + (r - l) / 3; double m2 = r - (r - l) / 3; Point toCheck1 = new Point(b.x + v.x * m1, b.y + v.y * m1); Point toCheck2 = new Point(b.x + v.x * m2, b.y + v.y * m2); double dist1 = getDist(fixed.line(toCheck1), a, b, c); double dist2 = getDist(fixed.line(toCheck2), a, b, c); if (dist1 < dist2) { r = m2; } else { l = m1; } } Point p = new Point(b.x + v.x * l, b.y + v.y * l); return getDist(fixed.line(p), a, b, c); } private double getDist(Line line, Point a, Point b, Point c) { return Math.max(a.distance(line), Math.max(b.distance(line), c.distance(line))); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class GeometryUtils { public static double epsilon = 1e-8; public static double fastHypot(double x, double y) { return Math.sqrt(x * x + y * y); } } static class Point { public final double x; public final double y; public String toString() { return "(" + x + ", " + y + ")"; } public Point(double x, double y) { this.x = x; this.y = y; } public Line line(Point other) { if (equals(other)) { return null; } double a = other.y - y; double b = x - other.x; double c = -a * x - b * y; return new Line(a, b, c); } public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Point point = (Point) o; return Math.abs(x - point.x) <= GeometryUtils.epsilon && Math.abs(y - point.y) <= GeometryUtils.epsilon; } public int hashCode() { int result; long temp; temp = x != +0.0d ? Double.doubleToLongBits(x) : 0L; result = (int) (temp ^ (temp >>> 32)); temp = y != +0.0d ? Double.doubleToLongBits(y) : 0L; result = 31 * result + (int) (temp ^ (temp >>> 32)); return result; } public double distance(Line line) { return Math.abs(line.a * x + line.b * y + line.c); } } 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 printFormat(String format, Object... objects) { writer.printf(format, objects); } public void close() { writer.close(); } } static class Vector { public final double x; public final double y; public final Point point; public Vector(double x, double y) { this.x = x; this.y = y; point = new Point(x, y); } public Vector(Point point) { this.x = point.x; this.y = point.y; this.point = point; } public Vector(Point from, Point to) { this(to.x - from.x, to.y - from.y); } } static class Line { public final double a; public final double b; public final double c; public Line(Point p, double angle) { a = Math.sin(angle); b = -Math.cos(angle); c = -p.x * a - p.y * b; } public Line(double a, double b, double c) { double h = GeometryUtils.fastHypot(a, b); this.a = a / h; this.b = b / h; this.c = c / h; } public boolean parallel(Line other) { return Math.abs(a * other.b - b * other.a) < GeometryUtils.epsilon; } public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Line line = (Line) o; if (!parallel(line)) { return false; } if (Math.abs(a * line.c - c * line.a) > GeometryUtils.epsilon || Math.abs(b * line.c - c * line.b) > GeometryUtils.epsilon) { return false; } return true; } } }
Java
["4\n0 0\n0 1\n1 1\n1 0", "6\n5 0\n10 0\n12 -4\n10 -8\n5 -8\n3 -4"]
2 seconds
["0.3535533906", "1.0000000000"]
NoteHere is a picture of the first sampleHere is an example of making the polygon non-convex.This is not an optimal solution, since the maximum distance we moved one point is  ≈ 0.4242640687, whereas we can make it non-convex by only moving each point a distance of at most  ≈ 0.3535533906.
Java 8
standard input
[ "geometry" ]
495488223483401ff12ae9c456b4e5fe
The first line has one integer n (4 ≤ n ≤ 1 000) — the number of vertices. The next n lines contain the coordinates of the vertices. Line i contains two integers xi and yi ( - 109 ≤ xi, yi ≤ 109) — the coordinates of the i-th vertex. These points are guaranteed to be given in clockwise order, and will form a strictly convex polygon (in particular, no three consecutive points lie on the same straight line).
1,800
Print one real number D, which is the maximum real number such that no matter how you move the vertices, the polygon stays convex. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely, let's assume that your answer is a and the answer of the jury is b. The checker program will consider your answer correct if .
standard output
PASSED
e91ddb431c8bae0bf8258627186e013b
train_000.jsonl
1492356900
You are given a convex polygon P with n distinct vertices p1, p2, ..., pn. Vertex pi has coordinates (xi, yi) in the 2D plane. These vertices are listed in clockwise order.You can choose a real number D and move each vertex of the polygon a distance of at most D from their original positions.Find the maximum value of D such that no matter how you move the vertices, the polygon does not intersect itself and stays convex.
256 megabytes
import java.awt.*; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; import java.util.List; import static java.lang.Math.*; public class B implements Runnable{ // SOLUTION!!! // HACK ME PLEASE IF YOU CAN!!! // PLEASE!!! // PLEASE!!! // PLEASE!!! private final static Random rnd = new Random(); private final static String fileName = ""; private void solve() { int n = readInt(); Point[] p = readPointArray(n); double answer = Double.POSITIVE_INFINITY; for (int cur = 0; cur < n; ++cur) { int prev = (cur + n - 1) % n; int next = (cur + 1) % n; long a = p[next].y - p[prev].y; long b = p[prev].x - p[next].x; long c = -a * p[prev].x -b * p[prev].y; long resultNumerator = a * p[cur].x + b * p[cur].y + c; long resultDenominator = a * a + b * b; double result = resultNumerator / sqrt(resultDenominator); answer = min(answer, abs(result) / 2); } out.println(answer); } ///////////////////////////////////////////////////////////////////// private final static boolean FIRST_INPUT_STRING = false; private final static boolean MULTIPLE_TESTS = true; 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; ///////////////////////////////////////////////////////////////////// public void run(){ try{ timeInit(); Locale.setDefault(Locale.US); init(); if (ONLINE_JUDGE) { solve(); } else { do { try { timeInit(); solve(); time(); out.println(); } catch (NumberFormatException e) { break; } catch (NullPointerException e) { if (FIRST_INPUT_STRING) break; else throw e; } } 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 B(), "", 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)); } private void debug(Object... objects){ if (ONLINE_JUDGE){ for (Object o: objects){ System.err.println(o.toString()); } } } ///////////////////////////////////////////////////////////////////// private String delim = " "; private String readLine() { try { return in.readLine(); } catch (IOException e) { throw new RuntimeIOException(e); } } private String readString() { try { while(!tok.hasMoreTokens()){ tok = new StringTokenizer(readLine()); } return tok.nextToken(delim); } catch (NullPointerException e) { return null; } } ///////////////////////////////////////////////////////////////// private final char NOT_A_SYMBOL = '\0'; 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(); } 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; } 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; } /////////////////////////////////////////////////////////////////// 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; } 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(); } } 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()); } private double[] readDoubleArray(int size) { double[] array = new double[size]; for (int index = 0; index < size; ++index){ array[index] = readDouble(); } return array; } //////////////////////////////////////////////////////////////////// private BigInteger readBigInteger() { return new BigInteger(readString()); } private BigDecimal readBigDecimal() { return new BigDecimal(readString()); } ///////////////////////////////////////////////////////////////////// private Point readPoint() { int x = readInt(); int y = readInt(); return new Point(x, y); } private Point[] readPointArray(int size) { Point[] array = new Point[size]; for (int index = 0; index < size; ++index){ array[index] = readPoint(); } return array; } ///////////////////////////////////////////////////////////////////// @Deprecated 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) { 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; } } ///////////////////////////////////////////////////////////////////// private static class IntIndexPair { static Comparator<IntIndexPair> increaseComparator = new Comparator<B.IntIndexPair>() { @Override public int compare(B.IntIndexPair indexPair1, B.IntIndexPair indexPair2) { int value1 = indexPair1.value; int value2 = indexPair2.value; if (value1 != value2) return value1 - value2; int index1 = indexPair1.index; int index2 = indexPair2.index; return index1 - index2; } }; static Comparator<IntIndexPair> decreaseComparator = new Comparator<B.IntIndexPair>() { @Override public int compare(B.IntIndexPair indexPair1, B.IntIndexPair indexPair2) { int value1 = indexPair1.value; int value2 = indexPair2.value; if (value1 != value2) return -(value1 - value2); int index1 = indexPair1.index; int index2 = indexPair2.index; return index1 - index2; } }; static 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; } int getRealIndex() { return index + 1; } } 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); } 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]); } @Override public void println(double d){ printlnAll(d); } void printlnAll(double... d){ printAll(d); println(); } } ///////////////////////////////////////////////////////////////////// private static class RuntimeIOException extends RuntimeException { /** * */ private static final long serialVersionUID = -6463830523020118289L; RuntimeIOException(Throwable cause) { super(cause); } } ///////////////////////////////////////////////////////////////////// //////////////// Some useful constants and functions //////////////// ///////////////////////////////////////////////////////////////////// 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} }; 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 boolean checkBit(int mask, int bit){ return (mask & (1 << bit)) != 0; } private static boolean checkBit(long mask, int bit){ return (mask & (1L << bit)) != 0; } ///////////////////////////////////////////////////////////////////// private static long getSum(int[] array) { long sum = 0; for (int value: array) { sum += value; } return sum; } 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); } ///////////////////////////////////////////////////////////////////// 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; } ///////////////////////////////////////////////////////////////////// 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 class MultiSet<ValueType> { public static <ValueType> MultiSet<ValueType> createMultiSet() { Map<ValueType, Integer> multiset = new HashMap<>(); return new MultiSet<>(multiset); } private final Map<ValueType, Integer> multiset; private int size; public MultiSet(Map<ValueType, Integer> multiset) { this.multiset = multiset; this.size = 0; } public int size() { return size; } public void inc(ValueType value) { int count = get(value); multiset.put(value, count + 1); ++size; } public void dec(ValueType value) { int count = get(value); if (count == 0) return; if (count == 1) multiset.remove(value); else multiset.put(value, count - 1); --size; } public int get(ValueType value) { Integer count = multiset.get(value); return (count == null ? 0 : count); } } ///////////////////////////////////////////////////////////////////// private static class IdMap<KeyType> extends HashMap<KeyType, Integer> { /** * */ private static final long serialVersionUID = -3793737771950984481L; public IdMap() { super(); } int getId(KeyType key) { Integer id = super.get(key); if (id == null) { super.put(key, id = size()); } return id; } } ///////////////////////////////////////////////////////////////////// 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; } 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 values 0..<n * @param n - exclusive limit of sequence */ private static List<Integer> order(int n) { List<Integer> sequence = new ArrayList<>(); for (int i = 0; i < n; ++i) { sequence.add(i); } return sequence; } }
Java
["4\n0 0\n0 1\n1 1\n1 0", "6\n5 0\n10 0\n12 -4\n10 -8\n5 -8\n3 -4"]
2 seconds
["0.3535533906", "1.0000000000"]
NoteHere is a picture of the first sampleHere is an example of making the polygon non-convex.This is not an optimal solution, since the maximum distance we moved one point is  ≈ 0.4242640687, whereas we can make it non-convex by only moving each point a distance of at most  ≈ 0.3535533906.
Java 8
standard input
[ "geometry" ]
495488223483401ff12ae9c456b4e5fe
The first line has one integer n (4 ≤ n ≤ 1 000) — the number of vertices. The next n lines contain the coordinates of the vertices. Line i contains two integers xi and yi ( - 109 ≤ xi, yi ≤ 109) — the coordinates of the i-th vertex. These points are guaranteed to be given in clockwise order, and will form a strictly convex polygon (in particular, no three consecutive points lie on the same straight line).
1,800
Print one real number D, which is the maximum real number such that no matter how you move the vertices, the polygon stays convex. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely, let's assume that your answer is a and the answer of the jury is b. The checker program will consider your answer correct if .
standard output
PASSED
7a1997acc04ea7ca8c81809f8637aa75
train_000.jsonl
1492356900
You are given a convex polygon P with n distinct vertices p1, p2, ..., pn. Vertex pi has coordinates (xi, yi) in the 2D plane. These vertices are listed in clockwise order.You can choose a real number D and move each vertex of the polygon a distance of at most D from their original positions.Find the maximum value of D such that no matter how you move the vertices, the polygon does not intersect itself and stays convex.
256 megabytes
import java.util.Scanner; /** * 772B * Created by happyboy on 2017/6/30. */ public class VilotileKite { public double findMaximumDistance(double[][] points) { double distance=Double.MAX_VALUE; int len=points.length; for(int i=0;i<len;i++) { double ABx=points[(i+1)%len][0]-points[i%len][0]; double ABy=points[(i+1)%len][1]-points[i%len][1]; double ACx=points[(i+2)%len][0]-points[i%len][0]; double ACy=points[(i+2)%len][1]-points[i%len][1]; distance=Math.min(distance,Math.abs((ABx*ACy)-(ACx*ABy))/Math.sqrt(ACx*ACx+ACy*ACy)/2); } return distance; } public static void main(String[] args) { Scanner input=new Scanner(System.in); VilotileKite vilotileKite=new VilotileKite(); int pointsNum=Integer.parseInt(input.nextLine()); double[][] points=new double[pointsNum][2]; for (int i=0;i<pointsNum;i++) { String[] eles=input.nextLine().split(" "); points[i][0]=Double.parseDouble(eles[0]); points[i][1]=Double.parseDouble(eles[1]); } System.out.println(vilotileKite.findMaximumDistance(points)); } }
Java
["4\n0 0\n0 1\n1 1\n1 0", "6\n5 0\n10 0\n12 -4\n10 -8\n5 -8\n3 -4"]
2 seconds
["0.3535533906", "1.0000000000"]
NoteHere is a picture of the first sampleHere is an example of making the polygon non-convex.This is not an optimal solution, since the maximum distance we moved one point is  ≈ 0.4242640687, whereas we can make it non-convex by only moving each point a distance of at most  ≈ 0.3535533906.
Java 8
standard input
[ "geometry" ]
495488223483401ff12ae9c456b4e5fe
The first line has one integer n (4 ≤ n ≤ 1 000) — the number of vertices. The next n lines contain the coordinates of the vertices. Line i contains two integers xi and yi ( - 109 ≤ xi, yi ≤ 109) — the coordinates of the i-th vertex. These points are guaranteed to be given in clockwise order, and will form a strictly convex polygon (in particular, no three consecutive points lie on the same straight line).
1,800
Print one real number D, which is the maximum real number such that no matter how you move the vertices, the polygon stays convex. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely, let's assume that your answer is a and the answer of the jury is b. The checker program will consider your answer correct if .
standard output
PASSED
0da2aed655134b68c2cdfc2ee3117fc4
train_000.jsonl
1492356900
You are given a convex polygon P with n distinct vertices p1, p2, ..., pn. Vertex pi has coordinates (xi, yi) in the 2D plane. These vertices are listed in clockwise order.You can choose a real number D and move each vertex of the polygon a distance of at most D from their original positions.Find the maximum value of D such that no matter how you move the vertices, the polygon does not intersect itself and stays convex.
256 megabytes
import java.io.*; import java.util.Locale; import java.util.StringTokenizer; public class A implements Runnable { private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; private BufferedReader in; private PrintWriter out; private StringTokenizer tok = new StringTokenizer(""); private void init() throws FileNotFoundException { Locale.setDefault(Locale.US); String fileName = ""; if (ONLINE_JUDGE && fileName.isEmpty()) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { if (fileName.isEmpty()) { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } else { in = new BufferedReader(new FileReader(fileName + ".in")); out = new PrintWriter(fileName + ".out"); } } } String readString() { while (!tok.hasMoreTokens()) { try { tok = new StringTokenizer(in.readLine()); } catch (Exception e) { return null; } } return tok.nextToken(); } int readInt() { return Integer.parseInt(readString()); } long readLong() { return Long.parseLong(readString()); } double readDouble() { return Double.parseDouble(readString()); } int[] readIntArray(int size) { int[] a = new int[size]; for (int i = 0; i < size; i++) { a[i] = readInt(); } return a; } public static void main(String[] args) { //new Thread(null, new _Solution(), "", 128 * (1L << 20)).start(); new A().run(); } long timeBegin, timeEnd; void time() { timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } @Override public void run() { try { timeBegin = System.currentTimeMillis(); init(); solve(); out.close(); time(); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } private int aiverson(boolean good) { return good ? 1 : 0; } class Point { int x, y; public Point(int x, int y) { this.x = x; this.y = y; } } private long get2S(Point p1, Point p2, Point p3) { return Math.abs(1l * (p2.x - p1.x) * (p3.y - p1.y) - 1l * (p3.x - p1.x) * (p2.y - p1.y)); } private void solve() { int n = readInt(); Point[] p = new Point[n]; for (int i = 0; i < n; i++) { p[i] = new Point(readInt(), readInt()); } double bestD = Long.MAX_VALUE; for (int iter = 0; iter < 322; iter++) { for (int i = 0; i < n; i++) { int prev = (i - 1 + n) % n; int next = (i + 1) % n; double myD = get2S(p[prev], p[i], p[next]) / getDist(p[prev], p[next]) / 2; bestD = Math.min(bestD, myD); } } out.println(bestD); } double getDist(Point p1, Point p2) { double dx = p1.x - p2.x; double dy = p1.y - p2.y; return Math.sqrt(dx * dx + dy * dy); } }
Java
["4\n0 0\n0 1\n1 1\n1 0", "6\n5 0\n10 0\n12 -4\n10 -8\n5 -8\n3 -4"]
2 seconds
["0.3535533906", "1.0000000000"]
NoteHere is a picture of the first sampleHere is an example of making the polygon non-convex.This is not an optimal solution, since the maximum distance we moved one point is  ≈ 0.4242640687, whereas we can make it non-convex by only moving each point a distance of at most  ≈ 0.3535533906.
Java 8
standard input
[ "geometry" ]
495488223483401ff12ae9c456b4e5fe
The first line has one integer n (4 ≤ n ≤ 1 000) — the number of vertices. The next n lines contain the coordinates of the vertices. Line i contains two integers xi and yi ( - 109 ≤ xi, yi ≤ 109) — the coordinates of the i-th vertex. These points are guaranteed to be given in clockwise order, and will form a strictly convex polygon (in particular, no three consecutive points lie on the same straight line).
1,800
Print one real number D, which is the maximum real number such that no matter how you move the vertices, the polygon stays convex. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely, let's assume that your answer is a and the answer of the jury is b. The checker program will consider your answer correct if .
standard output
PASSED
28f27829159378e2d0ef6e2907a27dff
train_000.jsonl
1349105400
Once upon a time an old man and his wife lived by the great blue sea. One day the old man went fishing and caught a real live gold fish. The fish said: "Oh ye, old fisherman! Pray set me free to the ocean and I will grant you with n gifts, any gifts you wish!". Then the fish gave the old man a list of gifts and their prices. Some gifts on the list can have the same names but distinct prices. However, there can't be two gifts with the same names and the same prices. Also, there can be gifts with distinct names and the same prices. The old man can ask for n names of items from the list. If the fish's list has p occurrences of the given name, then the old man can't ask for this name of item more than p times.The old man knows that if he asks for s gifts of the same name, the fish will randomly (i.e. uniformly amongst all possible choices) choose s gifts of distinct prices with such name from the list. The old man wants to please his greedy wife, so he will choose the n names in such a way that he can get n gifts with the maximum price. Besides, he isn't the brightest of fishermen, so if there are several such ways, he chooses one of them uniformly.The old man wondered, what is the probability that he can get n most expensive gifts. As the old man isn't good at probability theory, he asks you to help him.
256 megabytes
import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Egor Kulikov ([email protected]) */ 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); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } } class TaskE { public void solve(int testNumber, InputReader in, OutputWriter out) { int wishCount = in.readInt(); int titleCount = in.readInt(); int[][] values = new int[titleCount][]; for (int i = 0; i < titleCount; i++) values[i] = IOUtils.readIntArray(in, in.readInt()); int total = 0; for (int[] row : values) total += row.length; int[] all = new int[total]; int index = 0; for (int[] row : values) { System.arraycopy(row, 0, all, index, row.length); index += row.length; } Arrays.sort(all); int smallest = all[total - wishCount]; int[] shouldTake = new int[titleCount]; int[] mayTake = new int[titleCount]; int good = 0; int notBad = 0; for (int i = 0; i < titleCount; i++) { for (int j : values[i]) { if (j > smallest) { shouldTake[i]++; good++; } else if (j == smallest) { mayTake[i]++; notBad++; } } } int remaining = good + notBad - wishCount; double[] answer = new double[notBad - remaining + 1]; answer[0] = 1; double[] next = new double[answer.length]; double[][] c = new double[total + 1][total + 1]; for (int i = 0; i <= total; i++) { c[i][0] = 1; for (int j = 1; j <= i; j++) c[i][j] = c[i - 1][j - 1] + c[i - 1][j]; } int mayTakeRemaining = notBad; int willTake = answer.length - 1; for (int i = 0; i < titleCount; i++) { Arrays.fill(next, 0); for (int j = 0; j < answer.length; j++) { for (int k = 0; k <= mayTake[i] && j + k < answer.length; k++) { if (mayTakeRemaining < mayTake[i] || notBad < j + k) continue; double probability = c[mayTake[i]][k] * c[mayTakeRemaining - mayTake[i]][willTake - j - k] / c[mayTakeRemaining][willTake - j]; double win = c[mayTake[i]][k] / c[values[i].length][shouldTake[i] + k]; next[j + k] += answer[j] * probability * win; } } double[] temp = answer; answer = next; next = temp; mayTakeRemaining -= mayTake[i]; } out.printLine(answer[answer.length - 1]); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } } class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = in.readInt(); return array; } }
Java
["3 1\n3 10 20 30", "3 2\n1 40\n4 10 20 30 40"]
2 seconds
["1.000000000", "0.166666667"]
null
Java 6
standard input
[ "dp", "combinatorics", "probabilities", "math" ]
b8b3f75baaef9c4232e7fd7555d4fabb
The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 1000) — the number of the old man's wishes and the number of distinct names in the goldfish's list, correspondingly. Then m lines follow: the i-th line first contains integer ki (ki &gt; 0) — the number of distinct prices of gifts with the i-th name, then ki distinct space-separated integers cij (1 ≤ cij ≤ 109), the gifts' prices. It is guaranteed that the sum of all ki doesn't exceed 1000. It is guaranteed that n is not greater than the total number of the gifts.
2,600
On a single line print one real number — the probability of getting n most valuable gifts. The answer will be considered correct if its absolute or relative error does not exceed 10 - 9.
standard output
PASSED
26eac14712b7ab37a7726316000edfb9
train_000.jsonl
1349105400
Once upon a time an old man and his wife lived by the great blue sea. One day the old man went fishing and caught a real live gold fish. The fish said: "Oh ye, old fisherman! Pray set me free to the ocean and I will grant you with n gifts, any gifts you wish!". Then the fish gave the old man a list of gifts and their prices. Some gifts on the list can have the same names but distinct prices. However, there can't be two gifts with the same names and the same prices. Also, there can be gifts with distinct names and the same prices. The old man can ask for n names of items from the list. If the fish's list has p occurrences of the given name, then the old man can't ask for this name of item more than p times.The old man knows that if he asks for s gifts of the same name, the fish will randomly (i.e. uniformly amongst all possible choices) choose s gifts of distinct prices with such name from the list. The old man wants to please his greedy wife, so he will choose the n names in such a way that he can get n gifts with the maximum price. Besides, he isn't the brightest of fishermen, so if there are several such ways, he chooses one of them uniformly.The old man wondered, what is the probability that he can get n most expensive gifts. As the old man isn't good at probability theory, he asks you to help him.
256 megabytes
import java.io.*; import java.awt.geom.Point2D; import java.text.*; import java.math.*; import java.util.*; public class Main implements Runnable { final String filename = ""; public void solve() throws Exception { int n = iread(), m = iread(); double[] logNf = new double[1001]; for (int i = 1; i < logNf.length; i++) logNf[i] = logNf[i - 1] + Math.log(i); ArrayList<Integer> cost = new ArrayList<Integer>(); int[][] p = new int[m][]; for (int i = 0; i < m; i++) { int k = iread(); p[i] = new int[k]; for (int j = 0; j < k; j++) { p[i][j] = iread(); // p[i][j] = j+1; cost.add(p[i][j]); } } Collections.sort(cost); int A = cost.get(cost.size() - n); ArrayList<Double> b = new ArrayList<Double>(); double ans = 0.0; int n1 = 0; for (int i = 0; i < m; i++) { int k = p[i].length; int s = 0; boolean flag = false; for (int j = 0; j < k; j++) { if (p[i][j] > A) s++; if (p[i][j] == A) flag = true; } n1 += s; double p1 = logNf[k] - logNf[k - s] - logNf[s]; // System.out.println(k + " " + s); ans += p1; if (flag) { double p2 = logNf[k] - logNf[k - s - 1] - logNf[s + 1]; b.add(p2 - p1); } } Collections.sort(b); int k = b.size(); double[][] d = new double[k+1][k+1]; d[0][0] = 1.0; for (int i=0; i<k; i++) for (int j=0; j<k; j++) { double t = d[i][j]; if (t==0.0) continue; d[i+1][j+1] += t * Math.exp(-b.get(i)); d[i+1][j] += t; } double a = d[k][n-n1] * Math.exp(- logNf[k] + logNf[n-n1] + logNf[k-n+n1]); double ans2 = Math.exp(-ans) * a; DecimalFormat df = new DecimalFormat("0.0000000000"); out.write(df.format(ans2) + "\n"); } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new BufferedWriter(new OutputStreamWriter(System.out)); // in = new BufferedReader(new FileReader(filename+".in")); // out = new BufferedWriter(new FileWriter(filename+".out")); solve(); out.flush(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } public int iread() throws Exception { return Integer.parseInt(readword()); } public double dread() throws Exception { return Double.parseDouble(readword()); } public long lread() throws Exception { return Long.parseLong(readword()); } BufferedReader in; BufferedWriter out; public String readword() throws IOException { StringBuilder b = new StringBuilder(); int c; c = in.read(); while (c >= 0 && c <= ' ') c = in.read(); if (c < 0) return ""; while (c > ' ') { b.append((char) c); c = in.read(); } return b.toString(); } public static void main(String[] args) { try { Locale.setDefault(Locale.US); } catch (Exception e) { } // new Thread(new Main()).start(); new Thread(null, new Main(), "1", 1 << 25).start(); } }
Java
["3 1\n3 10 20 30", "3 2\n1 40\n4 10 20 30 40"]
2 seconds
["1.000000000", "0.166666667"]
null
Java 6
standard input
[ "dp", "combinatorics", "probabilities", "math" ]
b8b3f75baaef9c4232e7fd7555d4fabb
The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 1000) — the number of the old man's wishes and the number of distinct names in the goldfish's list, correspondingly. Then m lines follow: the i-th line first contains integer ki (ki &gt; 0) — the number of distinct prices of gifts with the i-th name, then ki distinct space-separated integers cij (1 ≤ cij ≤ 109), the gifts' prices. It is guaranteed that the sum of all ki doesn't exceed 1000. It is guaranteed that n is not greater than the total number of the gifts.
2,600
On a single line print one real number — the probability of getting n most valuable gifts. The answer will be considered correct if its absolute or relative error does not exceed 10 - 9.
standard output
PASSED
2a3868ae204a73743b8b2719348315d5
train_000.jsonl
1349105400
Once upon a time an old man and his wife lived by the great blue sea. One day the old man went fishing and caught a real live gold fish. The fish said: "Oh ye, old fisherman! Pray set me free to the ocean and I will grant you with n gifts, any gifts you wish!". Then the fish gave the old man a list of gifts and their prices. Some gifts on the list can have the same names but distinct prices. However, there can't be two gifts with the same names and the same prices. Also, there can be gifts with distinct names and the same prices. The old man can ask for n names of items from the list. If the fish's list has p occurrences of the given name, then the old man can't ask for this name of item more than p times.The old man knows that if he asks for s gifts of the same name, the fish will randomly (i.e. uniformly amongst all possible choices) choose s gifts of distinct prices with such name from the list. The old man wants to please his greedy wife, so he will choose the n names in such a way that he can get n gifts with the maximum price. Besides, he isn't the brightest of fishermen, so if there are several such ways, he chooses one of them uniformly.The old man wondered, what is the probability that he can get n most expensive gifts. As the old man isn't good at probability theory, he asks you to help him.
256 megabytes
import java.util.*; public class Main { static int maxn = 1005; static class node implements Comparable<node> { int val, id; node() {} @Override public int compareTo(node a) { if (val == a.val) return a.id - id; return a.val - val; } } public static void main(String[] args) { Scanner cin = new Scanner(System.in); int Got[] = new int[maxn]; int Left[] = new int[maxn]; double f[][] = new double[maxn][maxn]; int n = cin.nextInt(); int m = cin.nextInt(); List<node> g = new ArrayList<node>(); for (int i = 0; i < m; i++) { Left[i] = cin.nextInt(); for (int j = 0; j < Left[i]; j++) { node temp = new node(); temp.val = cin.nextInt(); temp.id = i; g.add(temp); } } Collections.sort(g); int t = g.size(); int d = g.get(n - 1).val, i; double p = 1; for (i = 0; g.get(i).val != d; i++) { int name = g.get(i).id; p *= (Got[name] + 1.0) / (Left[name] > 0 ? Left[name] : 1); Got[name]++; Left[name]--; } ArrayList<Integer> id = new ArrayList<Integer>(); int l = n - i; for (; i < t && g.get(i).val == d; i++) id.add(g.get(i).id); int s = id.size(); double Q[] = new double[maxn]; for (i = 0; i < s; i++) Q[i] = (Got[id.get(i)] + 1.0) / (Left[id.get(i)] > 0 ? Left[id.get(i)] : 1); f[0][0] = p; for (int y = 0; y < s; y++) { for (int x = 0; x <= y; x++) { f[x + 1][y + 1] += f[x][y] * Q[y] * (x + 1.0) / (y + 1.0); f[x][y + 1] += f[x][y] * (y - x + 1.0) / (y + 1); } } System.out.printf("%.9f\n", f[l][s]); } }
Java
["3 1\n3 10 20 30", "3 2\n1 40\n4 10 20 30 40"]
2 seconds
["1.000000000", "0.166666667"]
null
Java 6
standard input
[ "dp", "combinatorics", "probabilities", "math" ]
b8b3f75baaef9c4232e7fd7555d4fabb
The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 1000) — the number of the old man's wishes and the number of distinct names in the goldfish's list, correspondingly. Then m lines follow: the i-th line first contains integer ki (ki &gt; 0) — the number of distinct prices of gifts with the i-th name, then ki distinct space-separated integers cij (1 ≤ cij ≤ 109), the gifts' prices. It is guaranteed that the sum of all ki doesn't exceed 1000. It is guaranteed that n is not greater than the total number of the gifts.
2,600
On a single line print one real number — the probability of getting n most valuable gifts. The answer will be considered correct if its absolute or relative error does not exceed 10 - 9.
standard output
PASSED
9500393707c889a44b476f010dd3b5f6
train_000.jsonl
1349105400
Once upon a time an old man and his wife lived by the great blue sea. One day the old man went fishing and caught a real live gold fish. The fish said: "Oh ye, old fisherman! Pray set me free to the ocean and I will grant you with n gifts, any gifts you wish!". Then the fish gave the old man a list of gifts and their prices. Some gifts on the list can have the same names but distinct prices. However, there can't be two gifts with the same names and the same prices. Also, there can be gifts with distinct names and the same prices. The old man can ask for n names of items from the list. If the fish's list has p occurrences of the given name, then the old man can't ask for this name of item more than p times.The old man knows that if he asks for s gifts of the same name, the fish will randomly (i.e. uniformly amongst all possible choices) choose s gifts of distinct prices with such name from the list. The old man wants to please his greedy wife, so he will choose the n names in such a way that he can get n gifts with the maximum price. Besides, he isn't the brightest of fishermen, so if there are several such ways, he chooses one of them uniformly.The old man wondered, what is the probability that he can get n most expensive gifts. As the old man isn't good at probability theory, he asks you to help him.
256 megabytes
//package round142; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; public class E2 { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(), m = ni(); int[][] a = new int[m][]; int all = 0; for(int i = 0;i < m;i++){ int L = ni(); all += L; a[i] = new int[L]; for(int j = 0;j < L;j++){ a[i][j] = ni(); } Arrays.sort(a[i]); } int[] pr = new int[all]; int p = 0; for(int i = 0;i < m;i++){ for(int j = 0;j < a[i].length;j++){ pr[p++] = a[i][j]; } } Arrays.sort(pr); int tie = pr[all-1-n+1]; int[][] info = new int[m][3]; for(int i = 0;i < m;i++){ info[i][2] = a[i].length; for(int j = 0;j < a[i].length;j++){ if(a[i][j] > tie)info[i][0]++; if(a[i][j] == tie)info[i][1]++; } } double[][] C = new double[1001][1001]; for(int i = 0;i <= 1000;i++){ C[i][0] = 1; for(int j = 1;j <= i;j++){ C[i][j] = C[i-1][j] + C[i-1][j-1]; } } double[][] dp = new double[m+1][n+1]; double[][] ep = new double[m+1][n+1]; dp[0][0] = 1; ep[0][0] = 1; for(int i = 0;i < m;i++){ for(int j = 0;j <= n;j++){ if(dp[i][j] > 0){ for(int k = info[i][0];k <= info[i][0]+info[i][1] && j+k <= n;k++){ dp[i+1][j+k] += dp[i][j]*C[info[i][1]][k-info[i][0]]/C[info[i][2]][k]; ep[i+1][j+k] += ep[i][j]; } } } } out.printf("%.9f\n", dp[m][n] / ep[m][n]); } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new E2().run(); } public int ni() { try { int num = 0; boolean minus = false; while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-')); if(num == '-'){ num = 0; minus = true; }else{ num -= '0'; } while(true){ int b = is.read(); if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } } } catch (IOException e) { } return -1; } public long nl() { try { long num = 0; boolean minus = false; while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-')); if(num == '-'){ num = 0; minus = true; }else{ num -= '0'; } while(true){ int b = is.read(); if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } } } catch (IOException e) { } return -1; } public String ns() { try{ int b = 0; StringBuilder sb = new StringBuilder(); while((b = is.read()) != -1 && (b == '\r' || b == '\n' || b == ' ')); if(b == -1)return ""; sb.append((char)b); while(true){ b = is.read(); if(b == -1)return sb.toString(); if(b == '\r' || b == '\n' || b == ' ')return sb.toString(); sb.append((char)b); } } catch (IOException e) { } return ""; } public char[] ns(int n) { char[] buf = new char[n]; try{ int b = 0, p = 0; while((b = is.read()) != -1 && (b == ' ' || b == '\r' || b == '\n')); if(b == -1)return null; buf[p++] = (char)b; while(p < n){ b = is.read(); if(b == -1 || b == ' ' || b == '\r' || b == '\n')break; buf[p++] = (char)b; } return Arrays.copyOf(buf, p); } catch (IOException e) { } return null; } double nd() { return Double.parseDouble(ns()); } boolean oj = System.getProperty("ONLINE_JUDGE") != null; void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["3 1\n3 10 20 30", "3 2\n1 40\n4 10 20 30 40"]
2 seconds
["1.000000000", "0.166666667"]
null
Java 6
standard input
[ "dp", "combinatorics", "probabilities", "math" ]
b8b3f75baaef9c4232e7fd7555d4fabb
The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 1000) — the number of the old man's wishes and the number of distinct names in the goldfish's list, correspondingly. Then m lines follow: the i-th line first contains integer ki (ki &gt; 0) — the number of distinct prices of gifts with the i-th name, then ki distinct space-separated integers cij (1 ≤ cij ≤ 109), the gifts' prices. It is guaranteed that the sum of all ki doesn't exceed 1000. It is guaranteed that n is not greater than the total number of the gifts.
2,600
On a single line print one real number — the probability of getting n most valuable gifts. The answer will be considered correct if its absolute or relative error does not exceed 10 - 9.
standard output
PASSED
058cb28a515f02e846e4286e1ab0d2a6
train_000.jsonl
1555164300
It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them.
256 megabytes
import java.io.*; import java.util.*; public class Main{ static int mod = (int)(Math.pow(10, 9) + 7); public static void main(String[] args) { MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); int n =sc.nextInt(); int t = sc.nextInt(); int bestRoute = -1; int bestTime = Integer.MAX_VALUE; for (int i = 0; i < n; i++){ int s = sc.nextInt(); int d = sc.nextInt(); if (s == t){ bestRoute = i+1; bestTime = s; } else if (s > t){ if (s < bestTime){ bestRoute = i+1; bestTime = s; } } else{ int rem = (d - (t-s) % d)%d; if (t+rem < bestTime){ bestRoute = i+1; bestTime = t+rem; } } } out.println(bestRoute); out.close(); } static long pow(long a, long N) { if (N == 0) return 1; else if (N == 1) return a; else { long R = pow(a,N/2); if (N % 2 == 0) { return R*R; } else { return R*R*a; } } } static long powMod(long a, long N) { if (N == 0) return 1; else if (N == 1) return a % mod; else { long R = powMod(a,N/2) % mod; R *= R % mod; if (N % 2 == 1) { R *= a % mod; } return R % mod; } } static void mergeSort(int[] A){ // low to hi sort, single array only int n = A.length; if (n < 2) return; int[] l = new int[n/2]; int[] r = new int[n - n/2]; for (int i = 0; i < n/2; i++){ l[i] = A[i]; } for (int j = n/2; j < n; j++){ r[j-n/2] = A[j]; } mergeSort(l); mergeSort(r); merge(l, r, A); } static void merge(int[] l, int[] r, int[] a){ int i = 0, j = 0, k = 0; while (i < l.length && j < r.length && k < a.length){ if (l[i] < r[j]){ a[k] = l[i]; i++; } else{ a[k] = r[j]; j++; } k++; } while (i < l.length){ a[k] = l[i]; i++; k++; } while (j < r.length){ a[k] = r[j]; j++; k++; } } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } //-------------------------------------------------------- }
Java
["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"]
1 second
["1", "3", "1"]
NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not.
Java 11
standard input
[ "brute force", "math" ]
71be4cccd3b8c494ad7cc2d8a00cf5ed
The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$) — the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$) — the time when the first bus of this route arrives and the interval between two buses of this route.
1,000
Print one number — what bus route Serval will use. If there are several possible answers, you can print any of them.
standard output
PASSED
42cbe77e35282c0603d5e5fc5b0a8234
train_000.jsonl
1555164300
It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String args[])throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw=new PrintWriter(System.out); String str[]=br.readLine().split(" "); int n=Integer.parseInt(str[0]); int t=Integer.parseInt(str[1]); int arr[][]=new int[n][2]; int mx=Integer.MAX_VALUE; int ans=1; for(int i=0;i<n;i++) { str=br.readLine().split(" "); arr[i][0]=Integer.parseInt(str[0]); arr[i][1]=Integer.parseInt(str[1]); if(arr[i][0]>=t&&arr[i][0]<mx) { mx=arr[i][0]; ans=i+1; } else if(arr[i][0]<t) { int tp=(int)Math.ceil((double)(t-arr[i][0])/arr[i][1]); if(tp*arr[i][1]+arr[i][0]<mx) { mx=tp*arr[i][1]+arr[i][0]; ans=i+1; } } } pw.println(ans); pw.flush(); pw.close(); } }
Java
["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"]
1 second
["1", "3", "1"]
NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not.
Java 11
standard input
[ "brute force", "math" ]
71be4cccd3b8c494ad7cc2d8a00cf5ed
The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$) — the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$) — the time when the first bus of this route arrives and the interval between two buses of this route.
1,000
Print one number — what bus route Serval will use. If there are several possible answers, you can print any of them.
standard output
PASSED
43cc0cf2c9cf2fd52f5c451af1b24dfb
train_000.jsonl
1555164300
It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { FastReader scan = new FastReader(); //PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("taming.out"))); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); Task solver = new Task(); //int t = scan.nextInt(); int t = 1; for(int i = 1; i <= t; i++) solver.solve(i, scan, out); out.close(); } static class Task { public void solve(int testNumber, FastReader sc, PrintWriter pw) { int n = sc.nextInt(); int m = sc.nextInt(); int[] [] arr = new int[n][2]; for(int i=0;i<n;i++){ arr[i][0]=sc.nextInt(); arr[i][1]=sc.nextInt(); } int min=0; int val = Integer.MAX_VALUE; for(int i=0;i<n;i++){ int calc = arr[i][0]+Math.max(0,(m-arr[i][0]+arr[i][1]-1)/arr[i][1]*arr[i][1]); if (calc<val){ min = i; val = calc; } } pw.println(min+1); } } static class tup implements Comparable<tup> { int a, b; tup() { } ; tup(int a, int b) { this.a=a; this.b=b; } @Override public int compareTo(tup o2) { return Double.compare((double)o2.a/o2.b,(double)a/b); } } static void shuffle(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 void shuffle(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 class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(s))); } 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
["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"]
1 second
["1", "3", "1"]
NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not.
Java 11
standard input
[ "brute force", "math" ]
71be4cccd3b8c494ad7cc2d8a00cf5ed
The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$) — the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$) — the time when the first bus of this route arrives and the interval between two buses of this route.
1,000
Print one number — what bus route Serval will use. If there are several possible answers, you can print any of them.
standard output
PASSED
a46ba36fe950cb99a30abf27135f42a8
train_000.jsonl
1555164300
It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them.
256 megabytes
import java.sql.Array; import java.sql.SQLOutput; import java.util.*; import java.io.*; import java.math.*; public class MyProgram { public static FastIO file = new FastIO(); private static void solve() { // int tt = nextInt(); int tt = 1; long start = 0; while (tt-- > 0) { int n = nextInt(), k = nextInt(); int max = 100000, index = 0; for (int i = 0; i < n; i++) { int a = nextInt(), b = nextInt(); while(a < k) a+=b; if (a-k < max){ max = a-k; index = i; } } System.out.println(index+1); } } static int func(int[] a, int n, int count){ if (a[n] != -1) { count++; return func(a,a[n]-1,count); } return count+1; } private static int[] nextArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public static int[][] nextArray2D(int n, int m) { int[][] result = new int[n][]; for (int i = 0; i < n; i++) { result[i] = nextArray(m); } return result; } public static long pow(long n, long p) { long ret = 1L; while (p > 0) { if (p % 2 != 0L) ret *= n; n *= n; p >>= 1L; } return ret; } public static String next() { return file.next(); } public static int nextInt() { return file.nextInt(); } public static long nextLong() { return file.nextLong(); } public static double nextDouble() { return file.nextDouble(); } public static String nextLine() { return file.nextLine(); } public static class FastIO { BufferedReader br; StringTokenizer st; PrintWriter out; public FastIO() { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } 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) { solve(); } }
Java
["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"]
1 second
["1", "3", "1"]
NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not.
Java 11
standard input
[ "brute force", "math" ]
71be4cccd3b8c494ad7cc2d8a00cf5ed
The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$) — the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$) — the time when the first bus of this route arrives and the interval between two buses of this route.
1,000
Print one number — what bus route Serval will use. If there are several possible answers, you can print any of them.
standard output
PASSED
c56de345dfaf7b951c20508cfc8d9ee0
train_000.jsonl
1555164300
It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.StringTokenizer; public class Main { static final long M = 1000000007; public static void main(String args[]) { FastReader io = new FastReader(); int n = io.nextInt(); int t = io.nextInt(); int s[] = new int[n]; int d[] = new int[n]; for(int i = 0; i< n;i ++ ){ s[i] = io.nextInt(); d[i] = io.nextInt(); } long ret = -1,ans = 0; for(int i = 0;i < n; i++){ long low = 0,high = 100000; while(low <= high){ long mid = (low + high)/2; long time = s[i] + mid*d[i]; // System.out.println(time); if(time >= t){ if(time < ret || ret == -1){ ret = time; ans = i + 1; } high = mid - 1; } else{ low = mid + 1; } } } System.out.println(ans); } } class Solver{ static final long MAX = 10000000000L; public int solve(int start,int end,char s[],int count[][],int pre[][],char c){ if(start == end){ System.out.println(start + " " + end + " "+c); if(s[start] == c) return 0; return 1; } int mid = (start + end)/2; int c1 = solve(mid + 1,end,s,count,pre,(char)(c+1))+Math.abs(pre[c-'a'][mid]-pre[c-'a'][start]+count[c-'a'][start]-(mid-start+1)); int c2 = solve(start,mid,s,count,pre,(char)(c+1))+Math.abs(pre[c-'a'][end]-pre[c-'a'][mid]+count[c-'a'][mid]-(end-mid)); System.out.println(start + " " + end +" "+c+ " " + c1 + " " + c2); return Math.min(c1,c2); } } class Util{ static final long M = 1000000007; static long modexp(long n,long m){ if(m==0) return 1; else if(m==1) return n; else{ long p = modexp(n,m/2); if(m%2==1) return (((p*p)%M)*n)%M; else return (p*p)%M; } } static long exp(long n,long m){ if(m == 0) return 1; if(m == 1) return n; long p = exp(n,m/2); if(m%2 == 1) return p*p*n; else return p*p; } static long gcd(long a,long b){ if(a==0) return b; return gcd(b%a,a); } static long inv(long n){ return modexp(n,M-2); } static long lcm(long a,long b){ return a*b/gcd(a,b); } static long factorial(long fact[],long n){ fact[0]=1; fact[1]=1; long prod = 1; for(int i = 2;i <= n;i++){ prod = (prod*i)%M; fact[i] = prod; } return prod; } static boolean isPrime(long n){ for(int i = 2;i*i <= n;i++){ if(n%i == 0) return false; } return true; } } 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
["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"]
1 second
["1", "3", "1"]
NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not.
Java 11
standard input
[ "brute force", "math" ]
71be4cccd3b8c494ad7cc2d8a00cf5ed
The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$) — the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$) — the time when the first bus of this route arrives and the interval between two buses of this route.
1,000
Print one number — what bus route Serval will use. If there are several possible answers, you can print any of them.
standard output
PASSED
102956e19f199faccb8d83d8a8c8ecc7
train_000.jsonl
1555164300
It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class A { static class Pair{ int idx,s,d; public Pair(int idx,int s,int d){ this.idx=idx; this.s=s; this.d=d; } } static final int oo= Integer.MAX_VALUE; public static void process()throws IOException { int n=ni(),t=ni(); Pair arr[]=new Pair[n]; for(int i=0;i<n;i++) arr[i]=new Pair(i,ni(),ni()); Arrays.sort(arr,(A,B)->A.s-B.s); int res=0,curr_time=oo; for(int i=0;i<n;i++){ int curr=arr[i].s; while(curr<t) curr+=arr[i].d; if(curr-t<=curr_time){ curr_time=curr-t; res=arr[i].idx; } // System.out.println("curr "+curr+" s "+arr[i].s); } pn(res+1); } static FastReader sc; static PrintWriter out; public static void main(String[]args)throws IOException { out = new PrintWriter(System.out); sc=new FastReader(); long s = System.currentTimeMillis(); int t=1; //t=ni(); while(t-->0) process(); out.flush(); System.err.println(System.currentTimeMillis()-s+"ms"); } static void pn(Object o){out.println(o);} static void p(Object o){out.print(o);} static int ni()throws IOException{return Integer.parseInt(sc.next());} static long nl()throws IOException{return Long.parseLong(sc.next());} static double nd()throws IOException{return Double.parseDouble(sc.next());} static String nln()throws IOException{return sc.nextLine();} static long gcd(long a, long b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int gcd(int a, int b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int bit(long n)throws IOException{return (n==0)?0:(1+bit(n&(n-1)));} static long mod=(long)1e9+7l; static<T> void r_sort(T arr[],int n){ Random r = new Random(); for (int i = n-1; i > 0; i--){ int j = r.nextInt(i+1); T temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } Arrays.sort(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(); } String nextLine(){ String str = ""; try{ str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////// }
Java
["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"]
1 second
["1", "3", "1"]
NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not.
Java 11
standard input
[ "brute force", "math" ]
71be4cccd3b8c494ad7cc2d8a00cf5ed
The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$) — the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$) — the time when the first bus of this route arrives and the interval between two buses of this route.
1,000
Print one number — what bus route Serval will use. If there are several possible answers, you can print any of them.
standard output
PASSED
070060d592065229f2563dcb4695e9af
train_000.jsonl
1555164300
It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them.
256 megabytes
import java.io.*; import java.util.*; public class Solution { static int MAX = (int)1e5+1; static int ans = Integer.MAX_VALUE; static boolean vis[][]; static int arr[][]; static ArrayList<String> list = new ArrayList<>(); public static void main(String[] args)throws Exception{ //InputReader input = new InputReader(System.in); Scanner input = new Scanner(System.in); OutputStreamWriter out = new OutputStreamWriter(System.out); int n = input.nextInt(); int t = input.nextInt(); int res = Integer.MAX_VALUE; for(int i=0;i<n;i++) { int a = input.nextInt(); int b = input.nextInt(); int target = a>=t?a:0; if(a<t)target = a+((t-a)/b)*b; if(target<t)target+=b; if(res>target-t) { res = target-t; ans = i+1; } } System.out.println(ans); } public static int gcd(int arr[]) { int gcd = 0; for(int i =0;i<arr.length;i++) { gcd = gcd(arr[i],gcd); } return gcd; } public static boolean check(int arr[]) { for(int i =0;i<arr.length-1;i++) { if(arr[i] != arr[i+1])return false; } return true; } public static int sum(int n) { int sum =0; while(n>0) { sum+=(n%10); n/=10; } return sum; } public static boolean lucky(int n) { HashSet<Integer>set = new HashSet<>(); while(n>0) { set.add(n%10); n/=10; } if(set.contains(4) && set.contains(7) && set.size() ==2)return true; return false; } /* 3 10 3 5 12 1 1 1 1 1 1 1 2 1 1 1 3 1 1 1 4 1 1 1 5 1 1 1 6 1 1 1 7 1 1 1 8 1 1 1 9 1 1 1 10 1 1 2 2 1 1 2 1 */ public static boolean solve(int x,int y,int tx,int ty) { if(x<0 || y<0 || x>=arr.length || y>=arr[0].length || vis[x][y] ||arr[x][y] == -1)return false; vis[x][y] = true; if(x == tx && y == ty)return true; return solve(x-1,y,tx,ty)|| solve(x+1,y,tx,ty)|| solve(x,y+1,tx,ty)|| solve(x,y-1,tx,ty)|| solve(x-1,y-1,tx,ty)|| solve(x-1,y+1,tx,ty)|| solve(x+1,y+1,tx,ty)|| solve(x+1,y-1,tx,ty); } public static void construct(int a,int b,int arr[][]) { arr[a][b] = -1; int x = a,y=b; while(x>=0)arr[x--][b] = -1; x= a; while(x<arr.length)arr[x++][b] = -1; y =b; while(y<arr[0].length)arr[a][y++] = -1; y = b; while(y>=0)arr[a][y--] = -1; x = a;y=b; while(x>=0 && y>=0)arr[x--][y--] = -1; x = a;y=b; while(x>=0 && y<arr[0].length)arr[x--][y++] = -1; x=a;y=b; while(x<arr.length && y<arr[0].length)arr[x++][y++] = -1; x=a;y=b; while(x<arr.length && y>=0)arr[x++][y--] = -1; } public static int gcd(int a,int b) { return b==0? a:gcd(b,a%b); } public static boolean isPalindrome(int hh,int mm) { String s= ""; if(hh<10)s+="0"; s+=hh; if(mm<10)s+="0"; s+=mm; int l =0; int r = s.length()-1; while(l<r){ if(s.charAt(l)!= s.charAt(r))return false; l++; r--; } return true; } public static void sort(int arr[]) { ArrayList<Integer>list = new ArrayList<>(); for(int it:arr)list.add(it); Collections.sort(list); for(int i =0;i<arr.length;i++)arr[i] = list.get(i); } public static void swap(int a,int b,int arr[]){ int t = arr[a]; arr[a]= arr[b]; arr[b] = t; } } class Pair{ int x,y; public Pair(int x,int y) { this.x = x; this.y = y; } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public double readDouble() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') { return res * Math.pow(10, readInt()); } if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') { return res * Math.pow(10, readInt()); } if (c < '0' || c > '9') { throw new InputMismatchException(); } m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public long readLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } }
Java
["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"]
1 second
["1", "3", "1"]
NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not.
Java 11
standard input
[ "brute force", "math" ]
71be4cccd3b8c494ad7cc2d8a00cf5ed
The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$) — the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$) — the time when the first bus of this route arrives and the interval between two buses of this route.
1,000
Print one number — what bus route Serval will use. If there are several possible answers, you can print any of them.
standard output
PASSED
6f5920c7e6d2b6d433d702c77494ec67
train_000.jsonl
1555164300
It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them.
256 megabytes
import java.util.*; import java.io.*; /* */ public class Main{ public static OutputStream out=new BufferedOutputStream(System.out); //nl-->neew line; //l-->line; //arp-->array print; //arpnl-->array print new line public static void nl(Object o) throws IOException{out.write((o+"\n").getBytes());} public static void l(Object o) throws IOException{out.write((o+"").getBytes());} public static void arp(int[] o) throws IOException{for(int i=0;i<o.length;i++) out.write((o[i]+" ").getBytes());} public static void arpnl(int[] o) throws IOException{for(int i=0;i<o.length;i++) out.write((o[i]+"\n").getBytes());} // static int MOD=(int)1e9+7; static int[][] pascal_trgl=new int[4005][4005]; // public static void main(String[] args) throws IOException{ // long sttm=System.currentTimeMillis(); FastReader sc=new FastReader(); int n=sc.nextInt(),t=sc.nextInt(); int[][] a=new int[n][3]; for(int i=0;i<n;i++){ a[i][1]=i; int alpha=sc.nextInt(),beta=sc.nextInt(); if(alpha>=t) a[i][0]=alpha; else{ int temp=(t-alpha)/beta; if((t-alpha)%beta!=0) temp++; a[i][0]=temp*beta+alpha; } } sort_inc(a, 0); nl(a[n-1][1]+1); out.flush(); } public static int nCr(int n,int r){ return pascal_trgl[n][r]%MOD; } public static void intiTriangle(){ for (int i = 0; i <= 4004; i++) { Arrays.fill(pascal_trgl[i], 0); } pascal_trgl[0][0] = 1; for (int i = 1; i <= 4004; i++) { pascal_trgl[i][0] = 1; for (int j = 1; j <= i; j++) { pascal_trgl[i][j] = (pascal_trgl[i - 1][j - 1] + pascal_trgl[i - 1][j]) % MOD; } } } public static String decToBin(long val){ StringBuilder binstr=new StringBuilder(); while(val>0){ Long rem=val%2;val/=2; binstr.append(Long.toString(rem)); } binstr.reverse(); return new String(binstr); } public static long binToDec(String binstr){ long ans=0; long mul=1;int val=0; int n=binstr.length(); for(int i=0;i<n;i++){ if(binstr.charAt(n-1-i)=='1') val=1; ans+=(mul*val); val=0; mul*=2; } return ans; } public static StringBuilder OR(long val1,long val2){ StringBuilder s=new StringBuilder(); while(val1>0 || val2>0){ long rem1=0,rem2=0; if(val1>0) rem1=val1%2; if(val2>0) rem2=val2%2; val1/=2;val2/=2; s.append(Long.toString(Math.max(rem1,rem2))); } s.reverse(); return s; } public static boolean dfsCycle(ArrayList<Integer>[] arrl,int[] vis,int st,int pr){ vis[st]=1; int cupr=st; for(int elm:arrl[st]){ if(vis[elm]==1 && elm!=pr){ return true; } else if(vis[elm]==0 && dfsCycle(arrl, vis, elm, cupr)){ return true; } } vis[st]=2; return false; } public static long powMOD(long n,long k){ //n-pow(k) if(k==1){ return n%MOD; } if(k==0){ return 1; } long val=pow(n,k/2)%MOD; if(k%2==0)return ((val%MOD)*(val%MOD))%MOD; else return (((val*val)%MOD)*n)%MOD; } public static long pow(long n,long k){ //n-pow(k) if(k==1){ return n; } if(k==0){ return 1; } long val=pow(n,k/2); if(k%2==0)return ((val)*(val)); else return (((val*val))*n); } public static HashMap<Integer,Integer> lcm(int num){ ArrayList<Integer> arrl=new ArrayList<Integer>(); HashMap<Integer,Integer> map=new HashMap<Integer,Integer>(); while(num%2==0){ if(!map.containsKey(2)){ arrl.add(2); map.put(2, 1); } else{ map.put(2,map.get(2)+1); } num/=2; } for(int i=3;i*i<=num;i+=2){ while(num%i==0){ if(!map.containsKey(i)){ arrl.add(i); map.put(i, 1); } else{ map.put(i,map.get(i)+1); } num/=i; } } if(num>2){ if(!map.containsKey(num)){ arrl.add(num); map.put(num, 1); } else{ map.put(num,map.get(num)+1); } } return map; } static long m=998244353l; static long modInverse(long a,long m) { long m0 = m; long y = 0l, x = 1l; if (m == 1) return 0l; while (a > 1) { long q = a / m; long t = m; m = a % m; a = t; t = y; y = x - q * y; x = t; } if (x < 0) x += m0; return x; } public static int num_fact(int num){ ArrayList<Integer> arr=new ArrayList<Integer>(); int cnt=0; for(int i=1;i*i<=num;i++){ if(num%i==0){ if(i*i==num){ cnt+=1; } else{ cnt+=2; } } } return cnt; } public static void sort_inc(int[][] arr,int col){ //change dimention if req Arrays.sort(arr, new Comparator<int[]>() { public int compare(final int[] entry1,final int[] entry2) { if (entry1[col] < entry2[col]) //this is for dec return 1; else if(entry1[col]==entry2[col]) return 0; else return -1; } }); } public static boolean prime(int n){ for(int i=2;i*i<=n;i++){ if(n%i==0){ return false; } } return true; } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } public static long lcmOfTwo(int a,int b){ return a*b/gcd(a,b); } } 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; } } //Pair Task in process // class Pair<D1,D2> extends Comparable{ // D1 v1; // D2 v2; // Pair(D1 a,D2 b){ // v1=a;v2=b; // } // }
Java
["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"]
1 second
["1", "3", "1"]
NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not.
Java 11
standard input
[ "brute force", "math" ]
71be4cccd3b8c494ad7cc2d8a00cf5ed
The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$) — the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$) — the time when the first bus of this route arrives and the interval between two buses of this route.
1,000
Print one number — what bus route Serval will use. If there are several possible answers, you can print any of them.
standard output
PASSED
c4a37390a074ed31c655a23f71857949
train_000.jsonl
1555164300
It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them.
256 megabytes
import java.util.*; public class codeforces{ public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int t=sc.nextInt(); int max=Integer.MAX_VALUE; int index=0; for(int i=1;i<=n;i++){ int s=sc.nextInt(); int d=sc.nextInt(); while(s<t){ s+=d; } if(max>s){ max=s; index=i; } } System.out.println(index); } }
Java
["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"]
1 second
["1", "3", "1"]
NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not.
Java 11
standard input
[ "brute force", "math" ]
71be4cccd3b8c494ad7cc2d8a00cf5ed
The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$) — the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$) — the time when the first bus of this route arrives and the interval between two buses of this route.
1,000
Print one number — what bus route Serval will use. If there are several possible answers, you can print any of them.
standard output
PASSED
d754bc3725d32d83fd8e133262186988
train_000.jsonl
1555164300
It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them.
256 megabytes
import java.util.*; public class servalAndBus { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int t=sc.nextInt(); int a[]=new int [n]; int b[]=new int [n]; for(int i=0;i<n;i++) { a[i]=sc.nextInt(); b[i]=sc.nextInt(); if(a[i]<t) { while(a[i]<t) { a[i]+=b[i]; } } } // for(int i=0;i<n;i++) // { // System.out.print(a[i]+" "); // } int min=Integer.MAX_VALUE; int temp=-1; for(int i=0;i<n;i++) { if(a[i]-t<min) { min=a[i]-t; { temp=i+1; } } } System.out.println(temp); } }
Java
["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"]
1 second
["1", "3", "1"]
NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not.
Java 11
standard input
[ "brute force", "math" ]
71be4cccd3b8c494ad7cc2d8a00cf5ed
The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$) — the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$) — the time when the first bus of this route arrives and the interval between two buses of this route.
1,000
Print one number — what bus route Serval will use. If there are several possible answers, you can print any of them.
standard output
PASSED
138fcd2e1bb968c087f1974cbb7ef32f
train_000.jsonl
1555164300
It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Scanner; /** * Built using CHelper plug-in * Actual solution is at the top * * @author ky112233 */ 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); AServalAndBus solver = new AServalAndBus(); solver.solve(1, in, out); out.close(); } static class AServalAndBus { public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(); int t = in.nextInt(); int[][] a = new int[n][2]; for (int i = 0; i < n; i++) { a[i][0] = in.nextInt(); a[i][1] = in.nextInt(); } int[] ans = new int[n]; for (int i = 0; i < n; i++) { if (a[i][0] >= t) { ans[i] = a[i][0] - t; } else { int temp = t - a[i][0]; ans[i] = temp % a[i][1] == 0 ? 0 : a[i][1] - temp % a[i][1]; } } int idx = 0; int mn = ans[0]; for (int i = 1; i < n; i++) { if (ans[i] < mn) { idx = i; mn = ans[i]; } } out.println(idx + 1); } } }
Java
["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"]
1 second
["1", "3", "1"]
NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not.
Java 11
standard input
[ "brute force", "math" ]
71be4cccd3b8c494ad7cc2d8a00cf5ed
The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$) — the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$) — the time when the first bus of this route arrives and the interval between two buses of this route.
1,000
Print one number — what bus route Serval will use. If there are several possible answers, you can print any of them.
standard output
PASSED
b909b0dfca275d3748a543e4ebda6346
train_000.jsonl
1555164300
It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner cin = new Scanner(System.in); int n = cin.nextInt(); int t = cin.nextInt(); int[] s = new int[n]; int[] d = new int[n]; int least = 99999999, id = 0; for (int i = 0; i < n; i++) { s[i] = cin.nextInt(); d[i] = cin.nextInt(); } for (int i = 0; i < n; i++) { while (s[i] < t) { s[i] += d[i]; } if (least > s[i]) { least = s[i]; id = i + 1; } } System.out.println(id); } }
Java
["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"]
1 second
["1", "3", "1"]
NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not.
Java 11
standard input
[ "brute force", "math" ]
71be4cccd3b8c494ad7cc2d8a00cf5ed
The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$) — the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$) — the time when the first bus of this route arrives and the interval between two buses of this route.
1,000
Print one number — what bus route Serval will use. If there are several possible answers, you can print any of them.
standard output
PASSED
720f283209544020f90476a07d32fa8f
train_000.jsonl
1555164300
It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them.
256 megabytes
import java.io.*; import java.util.*; public class A { static void solve(FastIO io) { int n = io.nextInt(); int t = io.nextInt(); int min = (int)1e8; int id = -1; for (int i = 0; i < n; i++) { int s = io.nextInt(); int d = io.nextInt(); int w; if (s >= t) w = s - t; else { int k = t - s; int q = k / d; if (k % d != 0) q++; w = s + q * d; w = w - t; } if (w < min) { min = w; id = i+1; } } io.println(id); } public static void main(String[] args) { FastIO io = new FastIO(); // int t = io.nextInt(); // for (int i = 0; i < t; i++) solve(io); io.close(); } } class FastIO extends PrintWriter { BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); FastIO() { super(System.out); } public String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(r.readLine()); } catch (Exception e) { //TODO: handle exception } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } }
Java
["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"]
1 second
["1", "3", "1"]
NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not.
Java 11
standard input
[ "brute force", "math" ]
71be4cccd3b8c494ad7cc2d8a00cf5ed
The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$) — the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$) — the time when the first bus of this route arrives and the interval between two buses of this route.
1,000
Print one number — what bus route Serval will use. If there are several possible answers, you can print any of them.
standard output
PASSED
86741c0c6bb112e30c9fc68330f6b16b
train_000.jsonl
1555164300
It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them.
256 megabytes
import java.io.*; import java.util.*; public class ProgEc { public static void main(String[] args) throws Exception { //FileInputStream inputStream = new FileInputStream("input.txt"); //FileOutputStream outputStream = new FileOutputStream("output.txt"); InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Solver solver = new Solver(); solver.solve(1, in, out); out.close(); } static class Solver { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int t = in.nextInt(); int ans = 0; int min = 2000000000; for (int q = 0; q < n; q++) { int s = in.nextInt(); int d = in.nextInt(); while (s < t) { s += d; } if (s-t <= min) { min = s-t; ans = q; } } out.println(ans+1); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while(tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException (e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public float nextFloat() { return Float.parseFloat(next()); } } }
Java
["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"]
1 second
["1", "3", "1"]
NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not.
Java 11
standard input
[ "brute force", "math" ]
71be4cccd3b8c494ad7cc2d8a00cf5ed
The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$) — the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$) — the time when the first bus of this route arrives and the interval between two buses of this route.
1,000
Print one number — what bus route Serval will use. If there are several possible answers, you can print any of them.
standard output
PASSED
803106979f0aeb0650781859d0c5c992
train_000.jsonl
1555164300
It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class BusRoutes { public static void main(String[] args) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); final int buses; final int firstTime; try { StringTokenizer st = new StringTokenizer(br.readLine()); buses = Integer.parseInt(st.nextToken()); firstTime = Integer.parseInt(st.nextToken()); int[] busRouteArrival = new int[buses]; int[] interval = new int[buses]; for (int i = 0; i < buses; i++) { StringTokenizer st1 = new StringTokenizer(br.readLine()); busRouteArrival[i] = Integer.parseInt(st1.nextToken()); interval[i] = Integer.parseInt(st1.nextToken()); } Solver sol = new Solver(); sol.solve(buses, firstTime, busRouteArrival, interval); } catch (IOException e) { e.printStackTrace(); } } } class Solver { public void solve(int buses, int first, int[] arrivals, int[] intervals) { int min = 0; int minIndex = 0; for (int i = 0; i < buses; i++) { int temp1 = arrivals[i]; if (arrivals[i] < first) { int temp = intervals[i]; while (temp1 < first) { temp1 += temp; } } if (i == 0) { min = temp1 - first; minIndex = 1; } int temp2 = temp1 - first; if (temp2 < min) { min = temp2; minIndex = i + 1; } if (min == 0) { break; } } System.out.println(minIndex); } }
Java
["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"]
1 second
["1", "3", "1"]
NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not.
Java 11
standard input
[ "brute force", "math" ]
71be4cccd3b8c494ad7cc2d8a00cf5ed
The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$) — the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$) — the time when the first bus of this route arrives and the interval between two buses of this route.
1,000
Print one number — what bus route Serval will use. If there are several possible answers, you can print any of them.
standard output
PASSED
f073bd65eca17d5cc0d1840036933a8a
train_000.jsonl
1555164300
It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them.
256 megabytes
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; import java.util.Arrays; import java.math.BigInteger; /* Name of the class has to be "Main" only if the class is public. */ public class Main { public static void main (String[] args) throws java.lang.Exception { Scanner in =new Scanner(System.in); int t,i,j=0,n,m,k=0,l,p,h,min=100001; String st; n=in.nextInt(); t=in.nextInt(); int s[]=new int[n]; int d[]=new int[n]; int c[]=new int[n]; for(i=0;i<n;i++) { s[i]=in.nextInt(); d[i]=in.nextInt(); } for(i=0;i<n;i++) { if(t>s[i]) { k=(int)(t-s[i])/d[i]; c[i]=(k*d[i]+s[i])-t; if(c[i]<0) c[i]=((k+1)*d[i]+s[i])-t; } else c[i]=(s[i]-t); } for(i=0;i<n;i++) { if(c[i]<min) { min=c[i]; j=i+1; } } System.out.println(j); } }
Java
["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"]
1 second
["1", "3", "1"]
NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not.
Java 11
standard input
[ "brute force", "math" ]
71be4cccd3b8c494ad7cc2d8a00cf5ed
The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$) — the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$) — the time when the first bus of this route arrives and the interval between two buses of this route.
1,000
Print one number — what bus route Serval will use. If there are several possible answers, you can print any of them.
standard output
PASSED
2a3a517b40b41f755bcd9334c9f7ea72
train_000.jsonl
1555164300
It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them.
256 megabytes
import java.io.*; import java.util.*; public class Q3 { public static void main(String[] args) { InputReader in = new InputReader(); int N = in.nextInt(),t=in.nextInt(); int arr[][] = new int[N][2]; int pos=-1; for(int i=0;i<N;i++) { arr[i][0] = in.nextInt(); arr[i][1]=in.nextInt(); if(arr[i][0]==t) pos=i; } if(pos!=-1){ System.out.println(pos+1); return; } int ans=1,min=Integer.MAX_VALUE; for(int i=0;i<N;i++){ if(arr[i][0]>t){ if(min>arr[i][0]){ min=arr[i][0]; ans=i+1; } }else { int val = (t - arr[i][0]+arr[i][1]-1) / arr[i][1]; int tem = arr[i][1] * val + arr[i][0]; if (min > tem) { min = tem; ans = i + 1; } } } System.out.println(ans); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public int[] shuffle(int[] arr) { Random r = new Random(); for (int i = 1, j; i < arr.length; i++) { j = r.nextInt(i); arr[i] = arr[i] ^ arr[j]; arr[j] = arr[i] ^ arr[j]; arr[i] = arr[i] ^ arr[j]; } return arr; } public InputReader() { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } public InputReader(InputStream stream) { 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 char nextChar() { return next().charAt(0); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public int[] nextIntArr(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = this.nextInt(); } return arr; } public Integer[] nextIntegerArr(int n) { Integer[] arr = new Integer[n]; for (int i = 0; i < n; i++) arr[i] = new Integer(this.nextInt()); return arr; } public int[][] next2DIntArr(int n, int m) { int[][] arr = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { arr[i][j] = this.nextInt(); } } return arr; } public int[] nextSortedIntArr(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = this.nextInt(); } Arrays.sort(arr); return arr; } public long[] nextLongArr(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = this.nextLong(); } return arr; } public char[] nextCharArr(int n) { char[] arr = new char[n]; for (int i = 0; i < n; i++) { arr[i] = this.nextChar(); } return arr; } public static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } public static int[] uwiSieve(int n) { if (n <= 32) { int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31}; for (int i = 0; i < primes.length; i++) { if (n < primes[i]) { return Arrays.copyOf(primes, i); } } return primes; } int u = n + 32; double lu = Math.log(u); int[] ret = new int[(int) (u / lu + u / lu / lu * 1.5)]; ret[0] = 2; int pos = 1; int[] isp = new int[(n + 1) / 32 / 2 + 1]; int sup = (n + 1) / 32 / 2 + 1; int[] tprimes = {3, 5, 7, 11, 13, 17, 19, 23, 29, 31}; for (int tp : tprimes) { ret[pos++] = tp; int[] ptn = new int[tp]; for (int i = (tp - 3) / 2; i < tp << 5; i += tp) ptn[i >> 5] |= 1 << (i & 31); for (int i = 0; i < tp; i++) { for (int j = i; j < sup; j += tp) isp[j] |= ptn[i]; } } // 3,5,7 // 2x+3=n int[] magic = {0, 1, 23, 2, 29, 24, 19, 3, 30, 27, 25, 11, 20, 8, 4, 13, 31, 22, 28, 18, 26, 10, 7, 12, 21, 17, 9, 6, 16, 5, 15, 14}; int h = n / 2; for (int i = 0; i < sup; i++) { for (int j = ~isp[i]; j != 0; j &= j - 1) { int pp = i << 5 | magic[(j & -j) * 0x076be629 >>> 27]; int p = 2 * pp + 3; if (p > n) break; ret[pos++] = p; for (int q = pp; q <= h; q += p) isp[q >> 5] |= 1 << (q & 31); } } return Arrays.copyOf(ret, pos); } public static int[] radixSort(int[] f) { return radixSort(f, f.length); } public static int[] radixSort(int[] f, int n) { int[] to = new int[n]; { int[] b = new int[65537]; for (int i = 0; i < n; i++) b[1 + (f[i] & 0xffff)]++; for (int i = 1; i <= 65536; i++) b[i] += b[i - 1]; for (int i = 0; i < n; i++) to[b[f[i] & 0xffff]++] = f[i]; int[] d = f; f = to; to = d; } { int[] b = new int[65537]; for (int i = 0; i < n; i++) b[1 + (f[i] >>> 16)]++; for (int i = 1; i <= 65536; i++) b[i] += b[i - 1]; for (int i = 0; i < n; i++) to[b[f[i] >>> 16]++] = f[i]; int[] d = f; f = to; to = d; } return f; } } public static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } }
Java
["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"]
1 second
["1", "3", "1"]
NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not.
Java 11
standard input
[ "brute force", "math" ]
71be4cccd3b8c494ad7cc2d8a00cf5ed
The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$) — the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$) — the time when the first bus of this route arrives and the interval between two buses of this route.
1,000
Print one number — what bus route Serval will use. If there are several possible answers, you can print any of them.
standard output
PASSED
92264f03aec1309ae4f4db5d6397df77
train_000.jsonl
1555164300
It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them.
256 megabytes
import java.util.*; public class ServalAndBus { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int nbuses = scanner.nextInt(); int time = scanner.nextInt(); int min = 999999999; int index = 0; for(int i = 1; i <= nbuses;i++) { // empezamos en uno por que el primer bus cuenta como el primero int busArrival = scanner.nextInt(); int repetition = scanner.nextInt(); while(busArrival < time) { // si el bus llega antes que llegue el nino sumamos la repeticion hasta que el bus llegue despues busArrival = busArrival + repetition; } if(min > busArrival) { min = busArrival; index = i; } } System.out.println(index); } }
Java
["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"]
1 second
["1", "3", "1"]
NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not.
Java 11
standard input
[ "brute force", "math" ]
71be4cccd3b8c494ad7cc2d8a00cf5ed
The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$) — the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$) — the time when the first bus of this route arrives and the interval between two buses of this route.
1,000
Print one number — what bus route Serval will use. If there are several possible answers, you can print any of them.
standard output
PASSED
d787d29d03c53f8d94ac51dae5b83fef
train_000.jsonl
1555164300
It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); long n = sc.nextLong(); long t = sc.nextLong(); long ans = 1000000000,fans = 0; for(int i=0;i<n;i++){ long s = sc.nextLong(); long d = sc.nextLong(); long temp; if(s>=t){ temp = s; } else{ temp = 1; if((t-s)%d==0){ temp += (t-s)/d; } else{ temp += (t-s)/d; temp++; } temp = s + (temp-1)*d; } if(ans>temp){ ans = temp; fans = i+1; } } System.out.println(fans); } }
Java
["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"]
1 second
["1", "3", "1"]
NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not.
Java 11
standard input
[ "brute force", "math" ]
71be4cccd3b8c494ad7cc2d8a00cf5ed
The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$) — the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$) — the time when the first bus of this route arrives and the interval between two buses of this route.
1,000
Print one number — what bus route Serval will use. If there are several possible answers, you can print any of them.
standard output
PASSED
5e6480d13cf2f4234b1ed256fda35fd3
train_000.jsonl
1555164300
It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Jaynil */ 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); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int t = in.nextInt(); int ans = Integer.MAX_VALUE; int aval = 0; for (int i = 0; i < n; i++) { int s = in.nextInt(); int d = in.nextInt(); while (s < t) { s += d; } if (s < ans) { ans = s; aval = i; } } out.println(aval + 1); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"]
1 second
["1", "3", "1"]
NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not.
Java 11
standard input
[ "brute force", "math" ]
71be4cccd3b8c494ad7cc2d8a00cf5ed
The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$) — the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$) — the time when the first bus of this route arrives and the interval between two buses of this route.
1,000
Print one number — what bus route Serval will use. If there are several possible answers, you can print any of them.
standard output
PASSED
740f50484656b5af1d03dbb2cfa5194e
train_000.jsonl
1555164300
It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them.
256 megabytes
/* package whatever; // don't place package name! */ import java.util.Scanner; 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 Ideone { public static void main (String[] args) { Scanner sc = new Scanner(System.in); int n,t,s,d; n = sc.nextInt(); t = sc.nextInt(); int a[] = new int[n]; int b[] = new int[n]; int ans = 0,diff = 100000000; for(int i=0;i<n;i++) { s = sc.nextInt(); d = sc.nextInt(); int dd ; if(t <= s) dd = s-t; else { int k = t-s; int kk = k/d; kk*=d; if(kk < k) kk+=d; kk += s; dd = kk-t; } if(diff > dd) { diff = dd; ans = i+1; } } System.out.println(ans); } }
Java
["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"]
1 second
["1", "3", "1"]
NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not.
Java 11
standard input
[ "brute force", "math" ]
71be4cccd3b8c494ad7cc2d8a00cf5ed
The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$) — the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$) — the time when the first bus of this route arrives and the interval between two buses of this route.
1,000
Print one number — what bus route Serval will use. If there are several possible answers, you can print any of them.
standard output
PASSED
b5c7f86aee088ec169616fec2580ae5a
train_000.jsonl
1555164300
It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Main{ static final FastReader in = new FastReader(); static final FastWriter out = new FastWriter(); public static void main(String[] args) throws IOException{ int n = in.nextInt(); int t = in.nextInt(); int[][] a = new int[n][2]; for (int i = 0; i < n; i++){ a[i][0] = in.nextInt(); a[i][1] = in.nextInt(); } // minimum time that he will go on the bus in each of the bus routes, then the minimum time out of all that is the answer. int[] minTime = new int[n]; for (int i = 0; i < n; i++){ if (a[i][0] >= t) minTime[i] = a[i][0]; else{ while (a[i][0] < t) a[i][0]+=a[i][1]; minTime[i] = a[i][0]; } } int mini = (int) 1e9; int ans = 0; for (int i = 0; i < n; i++){ if (minTime[i] < mini){ mini = minTime[i]; ans = i+1; } } out.pl(ans); out.close(); } } class FastReader{ BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next(){ while (st == null || !st.hasMoreElements()) { try{ st = new StringTokenizer(br.readLine()); }catch (IOException e){ e.printStackTrace(); } } return st.nextToken(); } int nextInt(){ return Integer.parseInt(next()); } long nextLong(){ return Long.parseLong(next()); } double nextDouble(){ return Double.parseDouble(next()); } String nextLine(){ String str = ""; try{ str = br.readLine(); } catch (IOException e){ e.printStackTrace(); } return str; } } class FastWriter{ PrintWriter out; FastWriter(){ out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); out.flush(); } void pl(Object o){ out.write(o.toString()); out.write("\n"); out.flush(); } void pl(){ out.write("\n"); } void p(Object o){ out.write(o.toString()); } void close(){ out.flush(); out.close(); } }
Java
["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"]
1 second
["1", "3", "1"]
NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not.
Java 11
standard input
[ "brute force", "math" ]
71be4cccd3b8c494ad7cc2d8a00cf5ed
The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$) — the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$) — the time when the first bus of this route arrives and the interval between two buses of this route.
1,000
Print one number — what bus route Serval will use. If there are several possible answers, you can print any of them.
standard output
PASSED
e1cfd4637de9d91ffe7ff7696b4e9be9
train_000.jsonl
1555164300
It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them.
256 megabytes
import java.io.*; import java.util.*; public class A{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n=sc.nextInt(), t=sc.nextInt(); int min=Integer.MAX_VALUE; int route=-1; for(int i=0; i<n; ++i){ int x, y; x=sc.nextInt(); y=sc.nextInt(); int s=x; while(true){ if(s>=t){ if(s<=min){ min=s; route=i+1; } break; } s+=y; } } System.out.println(route); sc.close(); } }
Java
["2 2\n6 4\n9 5", "5 5\n3 3\n2 5\n5 6\n4 9\n6 1", "3 7\n2 2\n2 3\n2 4"]
1 second
["1", "3", "1"]
NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not.
Java 11
standard input
[ "brute force", "math" ]
71be4cccd3b8c494ad7cc2d8a00cf5ed
The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$) — the number of bus routes and the time Serval goes to the station. Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$) — the time when the first bus of this route arrives and the interval between two buses of this route.
1,000
Print one number — what bus route Serval will use. If there are several possible answers, you can print any of them.
standard output
PASSED
258be72b8c489f20edf78bbbc222f444
train_000.jsonl
1489851300
A tree is an undirected connected graph without cycles. The distance between two vertices is the number of edges in a simple path between them.Limak is a little polar bear. He lives in a tree that consists of n vertices, numbered 1 through n.Limak recently learned how to jump. He can jump from a vertex to any vertex within distance at most k.For a pair of vertices (s, t) we define f(s, t) as the minimum number of jumps Limak needs to get from s to t. Your task is to find the sum of f(s, t) over all pairs of vertices (s, t) such that s &lt; t.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class cf771c { public static void main(String[] args) throws IOException { int n = rni(), k = ni(); long dp[][] = new long[n][k + 1]; Graph g = tree(n); dfs(g, 0, -1, dp, k); /* for (int[] row : dp) { prln(row); } */ prln(reroot(g, 0, -1, dp, k) / 2); close(); } static long reroot(Graph g, int i, int p, long[][] dp, int k) { long ans = 0; for (int j = 1; j <= k; ++j) { ans += dp[i][j]; } // prln(i, ans); // prln(dp[i]); for (int j : g.get(i)) { if (j != p) { for (int x = 1; x <= k; ++x) { dp[i][x] -= dp[j][x - 1]; } dp[i][k] -= dp[j][k]; dp[i][0] -= dp[j][k - 1]; for (int x = 1; x <= k; ++x) { dp[j][x] += dp[i][x - 1]; } dp[j][k] += dp[i][k]; dp[j][0] += dp[i][k - 1]; ans += reroot(g, j, i, dp, k); for (int x = 1; x <= k; ++x) { dp[j][x] -= dp[i][x - 1]; } dp[j][k] -= dp[i][k]; dp[j][0] -= dp[i][k - 1]; for (int x = 1; x <= k; ++x) { dp[i][x] += dp[j][x - 1]; } dp[i][k] += dp[j][k]; dp[i][0] += dp[j][k - 1]; } } return ans; } static void dfs(Graph g, int i, int p, long[][] dp, int k) { dp[i][0] = 1; for (int j : g.get(i)) { if (j != p) { dfs(g, j, i, dp, k); for (int x = 1; x <= k; ++x) { dp[i][x] += dp[j][x - 1]; } dp[i][k] += dp[j][k]; dp[i][0] += dp[j][k - 1]; } } } static Graph graph(int n) { Graph g = new Graph(); for (int i = 0; i < n; ++i) { g.add(new ArrayList<>()); } return g; } static Graph graph(int n, int m) throws IOException { Graph g = graph(n); for (int i = 0; i < m; ++i) { g.c(rni() - 1, ni() - 1); } return g; } static Graph tree(int n) throws IOException { return graph(n, n - 1); } static class Graph extends ArrayList<List<Integer>> { void cto(int u, int v) { get(u).add(v); } void c(int u, int v) { cto(u, v); cto(v, u); } boolean is_leaf(int i) { return get(i).size() == 1; } } static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out)); static StringTokenizer input; static Random __rand = new Random(); // references // IBIG = 1e9 + 7 // IMAX ~= 2e9 // LMAX ~= 9e18 // constants static final int IBIG = 1000000007; static final int IMAX = 2147483647; static final int IMIN = -2147483648; static final long LMAX = 9223372036854775807L; static final long LMIN = -9223372036854775808L; // math util static int minof(int a, int b, int c) {return min(a, min(b, c));} static int minof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;} static long minof(long a, long b, long c) {return min(a, min(b, c));} static long minof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;} static int maxof(int a, int b, int c) {return max(a, max(b, c));} static int maxof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;} static long maxof(long a, long b, long c) {return max(a, max(b, c));} static long maxof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;} static int powi(int a, int b) {if (a == 0) return 0; int ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static long powl(long a, int b) {if (a == 0) return 0; long ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static int fli(double d) {return (int) d;} static int cei(double d) {return (int) ceil(d);} static long fll(double d) {return (long) d;} static long cel(double d) {return (long) ceil(d);} static int gcf(int a, int b) {return b == 0 ? a : gcf(b, a % b);} static long gcf(long a, long b) {return b == 0 ? a : gcf(b, a % b);} static int lcm(int a, int b) {return a * b / gcf(a, b);} static long lcm(long a, long b) {return a * b / gcf(a, b);} static int randInt(int min, int max) {return __rand.nextInt(max - min + 1) + min;} static long mix(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);} // array util static void reverse(int[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(long[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(double[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(char[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void shuffle(int[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(long[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(double[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void rsort(int[] a) {shuffle(a); sort(a);} static void rsort(long[] a) {shuffle(a); sort(a);} static void rsort(double[] a) {shuffle(a); sort(a);} static int[] copy(int[] a) {int[] ans = new int[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static long[] copy(long[] a) {long[] ans = new long[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static double[] copy(double[] a) {double[] ans = new double[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static char[] copy(char[] a) {char[] ans = new char[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} // input static void r() throws IOException {input = new StringTokenizer(rline());} static int ri() throws IOException {return Integer.parseInt(rline());} static long rl() throws IOException {return Long.parseLong(rline());} static double rd() throws IOException {return Double.parseDouble(rline());} static int[] ria(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni(); return a;} static int[] riam1(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni() - 1; return a;} static long[] rla(int n) throws IOException {long[] a = new long[n]; r(); for (int i = 0; i < n; ++i) a[i] = nl(); return a;} static double[] rda(int n) throws IOException {double[] a = new double[n]; r(); for (int i = 0; i < n; ++i) a[i] = nd(); return a;} static char[] rcha() throws IOException {return rline().toCharArray();} static String rline() throws IOException {return __in.readLine();} static String n() {return input.nextToken();} static int rni() throws IOException {r(); return ni();} static int ni() {return Integer.parseInt(n());} static long rnl() throws IOException {r(); return nl();} static long nl() {return Long.parseLong(n());} static double rnd() throws IOException {r(); return nd();} static double nd() {return Double.parseDouble(n());} // output static void pr(int i) {__out.print(i);} static void prln(int i) {__out.println(i);} static void pr(long l) {__out.print(l);} static void prln(long l) {__out.println(l);} static void pr(double d) {__out.print(d);} static void prln(double d) {__out.println(d);} static void pr(char c) {__out.print(c);} static void prln(char c) {__out.println(c);} static void pr(char[] s) {__out.print(new String(s));} static void prln(char[] s) {__out.println(new String(s));} static void pr(String s) {__out.print(s);} static void prln(String s) {__out.println(s);} static void pr(Object o) {__out.print(o);} static void prln(Object o) {__out.println(o);} static void prln() {__out.println();} static void pryes() {prln("yes");} static void pry() {prln("Yes");} static void prY() {prln("YES");} static void prno() {prln("no");} static void prn() {prln("No");} static void prN() {prln("NO");} static boolean pryesno(boolean b) {prln(b ? "yes" : "no"); return b;}; static boolean pryn(boolean b) {prln(b ? "Yes" : "No"); return b;} static boolean prYN(boolean b) {prln(b ? "YES" : "NO"); return b;} static void prln(int... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static void prln(long... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static void prln(double... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for (int i = 0; i < n; pr(iter.next()), pr(' '), ++i); if (n >= 0) prln(iter.next()); else prln();} static void h() {prln("hlfd"); flush();} static void flush() {__out.flush();} static void close() {__out.close();} }
Java
["6 2\n1 2\n1 3\n2 4\n2 5\n4 6", "13 3\n1 2\n3 2\n4 2\n5 2\n3 6\n10 6\n6 7\n6 13\n5 8\n5 9\n9 11\n11 12", "3 5\n2 1\n3 1"]
2 seconds
["20", "114", "3"]
NoteIn the first sample, the given tree has 6 vertices and it's displayed on the drawing below. Limak can jump to any vertex within distance at most 2. For example, from the vertex 5 he can jump to any of vertices: 1, 2 and 4 (well, he can also jump to the vertex 5 itself). There are pairs of vertices (s, t) such that s &lt; t. For 5 of those pairs Limak would need two jumps: (1, 6), (3, 4), (3, 5), (3, 6), (5, 6). For other 10 pairs one jump is enough. So, the answer is 5·2 + 10·1 = 20.In the third sample, Limak can jump between every two vertices directly. There are 3 pairs of vertices (s &lt; t), so the answer is 3·1 = 3.
Java 11
standard input
[ "dp", "dfs and similar", "trees" ]
0b4362204bb9f0e95eaf7e2949315c8f
The first line of the input contains two integers n and k (2 ≤ n ≤ 200 000, 1 ≤ k ≤ 5) — the number of vertices in the tree and the maximum allowed jump distance respectively. The next n - 1 lines describe edges in the tree. The i-th of those lines contains two integers ai and bi (1 ≤ ai, bi ≤ n) — the indices on vertices connected with i-th edge. It's guaranteed that the given edges form a tree.
2,100
Print one integer, denoting the sum of f(s, t) over all pairs of vertices (s, t) such that s &lt; t.
standard output
PASSED
bd80891160f64ec7372f6171ae0b7bc7
train_000.jsonl
1330536600
Dr. Moriarty is about to send a message to Sherlock Holmes. He has a string s. String p is called a substring of string s if you can read it starting from some position in the string s. For example, string "aba" has six substrings: "a", "b", "a", "ab", "ba", "aba".Dr. Moriarty plans to take string s and cut out some substring from it, let's call it t. Then he needs to change the substring t zero or more times. As a result, he should obtain a fixed string u (which is the string that should be sent to Sherlock Holmes). One change is defined as making one of the following actions: Insert one letter to any end of the string. Delete one letter from any end of the string. Change one letter into any other one. Moriarty is very smart and after he chooses some substring t, he always makes the minimal number of changes to obtain u. Help Moriarty choose the best substring t from all substrings of the string s. The substring t should minimize the number of changes Moriarty should make to obtain the string u from it.
256 megabytes
//===========================================================================// // Author: Zakhar_Voit // Module: main // Description: // Creation date: 08.03.2012 17:33:29 // Remarks: //===========================================================================// import java.io.*; import java.util.*; import static java.lang.Math.*; public class main { public static void main(String[] args) { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); String s = in.next(); String u = in.next(); String t = ""; int ans = 10000; for (int i = 0; i < 3000; i++) t += "#"; s = t + s + t; char [] ss = s.toCharArray(), uu = u.toCharArray(); for (int i = 0; i < s.length() - u.length(); i++) { int cnt = 0; for (int j = 0; j < u.length(); j++) { if (uu[j] != ss[i + j]) cnt++; } if (cnt < ans) ans = cnt; } out.print(ans); out.close(); } }
Java
["aaaaa\naaa", "abcabc\nbcd", "abcdef\nklmnopq"]
2 seconds
["0", "1", "7"]
NoteIn the first sample Moriarty can take any substring of length 3, and it will be equal to the required message u, so Moriarty won't have to make any changes.In the second sample you should take a substring consisting of characters from second to fourth ("bca") or from fifth to sixth ("bc"). Then you will only have to make one change: to change or to add the last character.In the third sample the initial string s doesn't contain any character that the message should contain, so, whatever string you choose, you will have to make at least 7 changes to obtain the required message.
Java 7
standard input
[ "dp", "brute force", "strings" ]
430486b13b2f3be12cf47fac105056ae
The first line contains a non-empty string s, consisting of lowercase Latin letters. The second line contains a non-empty string u, consisting of lowercase Latin letters. The lengths of both strings are in the range from 1 to 2000, inclusive.
1,700
Print the only integer — the minimum number of changes that Dr. Moriarty has to make with the string that you choose.
standard output
PASSED
de874605547e6ee525f27b011dc4f441
train_000.jsonl
1330536600
Dr. Moriarty is about to send a message to Sherlock Holmes. He has a string s. String p is called a substring of string s if you can read it starting from some position in the string s. For example, string "aba" has six substrings: "a", "b", "a", "ab", "ba", "aba".Dr. Moriarty plans to take string s and cut out some substring from it, let's call it t. Then he needs to change the substring t zero or more times. As a result, he should obtain a fixed string u (which is the string that should be sent to Sherlock Holmes). One change is defined as making one of the following actions: Insert one letter to any end of the string. Delete one letter from any end of the string. Change one letter into any other one. Moriarty is very smart and after he chooses some substring t, he always makes the minimal number of changes to obtain u. Help Moriarty choose the best substring t from all substrings of the string s. The substring t should minimize the number of changes Moriarty should make to obtain the string u from it.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.Stack; import java.util.StringTokenizer; public class Coder{ static class FastScanner{ BufferedReader s; StringTokenizer st; public FastScanner(){ st = new StringTokenizer(""); s = new BufferedReader(new InputStreamReader(System.in)); } public FastScanner(File f) throws FileNotFoundException{ st = new StringTokenizer(""); s = new BufferedReader (new FileReader(f)); } public int nextInt() throws IOException{ if(st.hasMoreTokens()) return Integer.parseInt(st.nextToken()); else{ st = new StringTokenizer(s.readLine()); return nextInt(); } } public String nextString() throws IOException{ if(st.hasMoreTokens()) return st.nextToken(); else{ st = new StringTokenizer(s.readLine()); return nextString(); } } public String readLine() throws IOException{ return s.readLine(); } public void close() throws IOException{ s.close(); } } public static int match(String src, String dsc){ int len1 = src.length(); int len2 = dsc.length(); int[][] dp = new int[len1+1][len2+1]; for(int i=1;i<=len2;i++) dp[0][i] = i; for(int i=1;i<=len1;i++) dp[i][0] = i; for(int i=1;i<=len1;i++){ for(int j=1;j<=len2;j++){ if(src.charAt(i-1) == dsc.charAt(j-1)) dp[i][j] = Math.min(dp[i-1][j-1], Math.min(dp[i-1][j]+1,dp[i][j-1]+1)); else dp[i][j] = Math.min(dp[i-1][j-1]+1, Math.min(dp[i-1][j]+1,dp[i][j-1]+1)); } } return dp[len1][len2]; } public static void main(String[] args) throws IOException{ /* FastScanner s = new FastScanner(new File("input.txt")); PrintWriter ww = new PrintWriter(new FileWriter("output.txt")); */ FastScanner s = new FastScanner(); PrintWriter ww = new PrintWriter(new OutputStreamWriter(System.out)); char[] ss = s.nextString().toCharArray(); int n = ss.length; char[] u = s.nextString().toCharArray(); int m = u.length; int ans = Integer.MAX_VALUE; int[][] dp = new int[n+1][m+1]; for(int i=0;i<=n;i++){ dp[i][0]=0; } for(int i=0;i<=m;i++){ dp[0][i]=i; } for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ dp[i][j]=dp[i-1][j-1]; if(ss[i-1]!=u[j-1]) dp[i][j]++; ans= Math.min(ans,m-j+dp[i][j]); } } ww.println(ans); s.close(); ww.close(); } }
Java
["aaaaa\naaa", "abcabc\nbcd", "abcdef\nklmnopq"]
2 seconds
["0", "1", "7"]
NoteIn the first sample Moriarty can take any substring of length 3, and it will be equal to the required message u, so Moriarty won't have to make any changes.In the second sample you should take a substring consisting of characters from second to fourth ("bca") or from fifth to sixth ("bc"). Then you will only have to make one change: to change or to add the last character.In the third sample the initial string s doesn't contain any character that the message should contain, so, whatever string you choose, you will have to make at least 7 changes to obtain the required message.
Java 7
standard input
[ "dp", "brute force", "strings" ]
430486b13b2f3be12cf47fac105056ae
The first line contains a non-empty string s, consisting of lowercase Latin letters. The second line contains a non-empty string u, consisting of lowercase Latin letters. The lengths of both strings are in the range from 1 to 2000, inclusive.
1,700
Print the only integer — the minimum number of changes that Dr. Moriarty has to make with the string that you choose.
standard output
PASSED
2272626ab8bc21205e1ac896e68f3143
train_000.jsonl
1330536600
Dr. Moriarty is about to send a message to Sherlock Holmes. He has a string s. String p is called a substring of string s if you can read it starting from some position in the string s. For example, string "aba" has six substrings: "a", "b", "a", "ab", "ba", "aba".Dr. Moriarty plans to take string s and cut out some substring from it, let's call it t. Then he needs to change the substring t zero or more times. As a result, he should obtain a fixed string u (which is the string that should be sent to Sherlock Holmes). One change is defined as making one of the following actions: Insert one letter to any end of the string. Delete one letter from any end of the string. Change one letter into any other one. Moriarty is very smart and after he chooses some substring t, he always makes the minimal number of changes to obtain u. Help Moriarty choose the best substring t from all substrings of the string s. The substring t should minimize the number of changes Moriarty should make to obtain the string u from it.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.Scanner; public class MessageProblem { public static BufferedReader openReader(String inputFile) throws IOException { FileInputStream fis = new FileInputStream(inputFile); return new BufferedReader( new InputStreamReader(fis, "UTF-8") ); } public static BufferedWriter openWriter(String outputFile) throws IOException { FileOutputStream fos = new FileOutputStream(outputFile); return new BufferedWriter( new OutputStreamWriter(fos, "UTF-8") ); } public static Scanner openScanner(BufferedReader reader) throws IOException { return new Scanner(reader); } public void process() throws IOException { try ( BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)) ) { String str1 = reader.readLine(); String str2 = reader.readLine(); System.out.println(distance(str1, str2)); } } public int distance(String str1, String str2) { int n = str1.length(); int m = str2.length(); int minCost = Integer.MAX_VALUE; for (int i = -m; i < n + m; i++) { int cost = 0; for (int j = 0; j < m; j++) { if (i + j < 0) { cost++; } else if (i + j >= n) { cost++; } else if (str1.charAt(i + j) != str2.charAt(j)) { cost++; } } if (cost < minCost) { minCost = cost; } } return minCost; } public static void main(String[] args) throws IOException { MessageProblem problem = new MessageProblem(); problem.process(); } }
Java
["aaaaa\naaa", "abcabc\nbcd", "abcdef\nklmnopq"]
2 seconds
["0", "1", "7"]
NoteIn the first sample Moriarty can take any substring of length 3, and it will be equal to the required message u, so Moriarty won't have to make any changes.In the second sample you should take a substring consisting of characters from second to fourth ("bca") or from fifth to sixth ("bc"). Then you will only have to make one change: to change or to add the last character.In the third sample the initial string s doesn't contain any character that the message should contain, so, whatever string you choose, you will have to make at least 7 changes to obtain the required message.
Java 7
standard input
[ "dp", "brute force", "strings" ]
430486b13b2f3be12cf47fac105056ae
The first line contains a non-empty string s, consisting of lowercase Latin letters. The second line contains a non-empty string u, consisting of lowercase Latin letters. The lengths of both strings are in the range from 1 to 2000, inclusive.
1,700
Print the only integer — the minimum number of changes that Dr. Moriarty has to make with the string that you choose.
standard output
PASSED
4230077e68731e236d34a75fc7ba593d
train_000.jsonl
1330536600
Dr. Moriarty is about to send a message to Sherlock Holmes. He has a string s. String p is called a substring of string s if you can read it starting from some position in the string s. For example, string "aba" has six substrings: "a", "b", "a", "ab", "ba", "aba".Dr. Moriarty plans to take string s and cut out some substring from it, let's call it t. Then he needs to change the substring t zero or more times. As a result, he should obtain a fixed string u (which is the string that should be sent to Sherlock Holmes). One change is defined as making one of the following actions: Insert one letter to any end of the string. Delete one letter from any end of the string. Change one letter into any other one. Moriarty is very smart and after he chooses some substring t, he always makes the minimal number of changes to obtain u. Help Moriarty choose the best substring t from all substrings of the string s. The substring t should minimize the number of changes Moriarty should make to obtain the string u from it.
256 megabytes
import java.util.*; import java.io.*; public class Main{ BufferedReader in; StringTokenizer str = null; PrintWriter out; private String next() throws Exception{ while (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); char []a = next().toCharArray(); char []b = next().toCharArray(); StringBuilder sb = new StringBuilder(); for(int i = 0; i < 2000; ++i) { sb.append("#"); } for(int i = 0; i < a.length; ++i) { sb.append(a[i]); } for(int i = 0; i < 2000; ++i) { sb.append("#"); } a = sb.toString().toCharArray(); int l = 0, r = b.length-1, ret = Integer.MAX_VALUE/2; while(r < a.length) { int c = 0; for(int i = l, j = 0; i <= r; ++i, ++j) { if (a[i] != b[j]) { ++c; } } r++; l++; ret = Math.min(ret, c); } out.println(ret); out.close(); } public static void main(String args[]) throws Exception{ new Main().run(); } }
Java
["aaaaa\naaa", "abcabc\nbcd", "abcdef\nklmnopq"]
2 seconds
["0", "1", "7"]
NoteIn the first sample Moriarty can take any substring of length 3, and it will be equal to the required message u, so Moriarty won't have to make any changes.In the second sample you should take a substring consisting of characters from second to fourth ("bca") or from fifth to sixth ("bc"). Then you will only have to make one change: to change or to add the last character.In the third sample the initial string s doesn't contain any character that the message should contain, so, whatever string you choose, you will have to make at least 7 changes to obtain the required message.
Java 7
standard input
[ "dp", "brute force", "strings" ]
430486b13b2f3be12cf47fac105056ae
The first line contains a non-empty string s, consisting of lowercase Latin letters. The second line contains a non-empty string u, consisting of lowercase Latin letters. The lengths of both strings are in the range from 1 to 2000, inclusive.
1,700
Print the only integer — the minimum number of changes that Dr. Moriarty has to make with the string that you choose.
standard output
PASSED
1183e41e10ad8708192e088f28c08ae2
train_000.jsonl
1330536600
Dr. Moriarty is about to send a message to Sherlock Holmes. He has a string s. String p is called a substring of string s if you can read it starting from some position in the string s. For example, string "aba" has six substrings: "a", "b", "a", "ab", "ba", "aba".Dr. Moriarty plans to take string s and cut out some substring from it, let's call it t. Then he needs to change the substring t zero or more times. As a result, he should obtain a fixed string u (which is the string that should be sent to Sherlock Holmes). One change is defined as making one of the following actions: Insert one letter to any end of the string. Delete one letter from any end of the string. Change one letter into any other one. Moriarty is very smart and after he chooses some substring t, he always makes the minimal number of changes to obtain u. Help Moriarty choose the best substring t from all substrings of the string s. The substring t should minimize the number of changes Moriarty should make to obtain the string u from it.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.LinkedList; import java.util.List; /** * Author: Vasiliy Homutov - [email protected] * Date: 02.05.12 * See: http://codeforces.ru/problemset/problem/157/C */ public class Message { public static class MessageHelper { private static String iterateChar(char c, int num) { StringBuilder result = new StringBuilder(); for (int index = 0; index < num; index++) { result.append(c); } return result.toString(); } public int findMinChanges(String s, String u) { String extension = iterateChar('*', u.length()); String extendedS = extension + s + extension; List<Character> subs = new LinkedList<>(); int index = 0; while (index < u.length()) { subs.add(extendedS.charAt(index)); index++; } int result = findChangesNumber(subs, u); while (index < extendedS.length()) { subs.remove(0); subs.add(extendedS.charAt(index)); int changesNumber = findChangesNumber(subs, u); if (result > changesNumber) { result = changesNumber; } index++; } return result; } private static int findChangesNumber(List<Character> s, String u) { int index = 0; int result = 0; for (Character c : s) { if (c != u.charAt(index)) { result++; } index++; } return result; } } public static void process(InputStream input, OutputStream output) throws IOException { int minChangesNumber; try (BufferedReader reader = new BufferedReader(new InputStreamReader(input))) { MessageHelper messageHelper = new MessageHelper(); String s = reader.readLine(); String u = reader.readLine(); minChangesNumber = messageHelper.findMinChanges(s, u); } try (PrintWriter writer = new PrintWriter(output)) { writer.print(minChangesNumber); } } public static void main(String[] args) throws IOException { process(System.in, System.out); } }
Java
["aaaaa\naaa", "abcabc\nbcd", "abcdef\nklmnopq"]
2 seconds
["0", "1", "7"]
NoteIn the first sample Moriarty can take any substring of length 3, and it will be equal to the required message u, so Moriarty won't have to make any changes.In the second sample you should take a substring consisting of characters from second to fourth ("bca") or from fifth to sixth ("bc"). Then you will only have to make one change: to change or to add the last character.In the third sample the initial string s doesn't contain any character that the message should contain, so, whatever string you choose, you will have to make at least 7 changes to obtain the required message.
Java 7
standard input
[ "dp", "brute force", "strings" ]
430486b13b2f3be12cf47fac105056ae
The first line contains a non-empty string s, consisting of lowercase Latin letters. The second line contains a non-empty string u, consisting of lowercase Latin letters. The lengths of both strings are in the range from 1 to 2000, inclusive.
1,700
Print the only integer — the minimum number of changes that Dr. Moriarty has to make with the string that you choose.
standard output
PASSED
5bc909c45857fc896d904d10137bb69f
train_000.jsonl
1330536600
Dr. Moriarty is about to send a message to Sherlock Holmes. He has a string s. String p is called a substring of string s if you can read it starting from some position in the string s. For example, string "aba" has six substrings: "a", "b", "a", "ab", "ba", "aba".Dr. Moriarty plans to take string s and cut out some substring from it, let's call it t. Then he needs to change the substring t zero or more times. As a result, he should obtain a fixed string u (which is the string that should be sent to Sherlock Holmes). One change is defined as making one of the following actions: Insert one letter to any end of the string. Delete one letter from any end of the string. Change one letter into any other one. Moriarty is very smart and after he chooses some substring t, he always makes the minimal number of changes to obtain u. Help Moriarty choose the best substring t from all substrings of the string s. The substring t should minimize the number of changes Moriarty should make to obtain the string u from it.
256 megabytes
import java.io.*; import java.util.LinkedList; import java.util.List; /** * Author: Vasiliy Homutov - [email protected] * Date: 02.05.12 * See: http://codeforces.ru/problemset/problem/157/C */ public class Message { public static class MessageHelper { private static String iterateChar(char c, int num) { StringBuilder result = new StringBuilder(); for (int index = 0; index < num; index++) { result.append(c); } return result.toString(); } public int findMinChanges(String s, String u) { String extension = iterateChar('*', u.length()); String extendedS = extension + s + extension; List<Character> subs = new LinkedList<>(); int index = 0; while (index < u.length()) { subs.add(extendedS.charAt(index)); index++; } int result = findChangesNumber(subs, u); while (index < extendedS.length()) { subs.remove(0); subs.add(extendedS.charAt(index)); int changesNumber = findChangesNumber(subs, u); if (result > changesNumber) { result = changesNumber; } index++; } return result; } private static int findChangesNumber(List<Character> s, String u) { int index = 0; int result = 0; for (Character c : s) { if (c != u.charAt(index)) { result++; } index++; } return result; } } public static void process(InputStream input, OutputStream output) throws IOException { int minChangesNumber; try (BufferedReader reader = new BufferedReader(new InputStreamReader(input))) { MessageHelper messageHelper = new MessageHelper(); String s = reader.readLine(); String u = reader.readLine(); minChangesNumber = messageHelper.findMinChanges(s, u); } try (PrintWriter writer = new PrintWriter(output)) { writer.print(minChangesNumber); } } public static void main(String[] args) throws IOException { process(System.in, System.out); } }
Java
["aaaaa\naaa", "abcabc\nbcd", "abcdef\nklmnopq"]
2 seconds
["0", "1", "7"]
NoteIn the first sample Moriarty can take any substring of length 3, and it will be equal to the required message u, so Moriarty won't have to make any changes.In the second sample you should take a substring consisting of characters from second to fourth ("bca") or from fifth to sixth ("bc"). Then you will only have to make one change: to change or to add the last character.In the third sample the initial string s doesn't contain any character that the message should contain, so, whatever string you choose, you will have to make at least 7 changes to obtain the required message.
Java 7
standard input
[ "dp", "brute force", "strings" ]
430486b13b2f3be12cf47fac105056ae
The first line contains a non-empty string s, consisting of lowercase Latin letters. The second line contains a non-empty string u, consisting of lowercase Latin letters. The lengths of both strings are in the range from 1 to 2000, inclusive.
1,700
Print the only integer — the minimum number of changes that Dr. Moriarty has to make with the string that you choose.
standard output
PASSED
d0e91bcdee24cbace4aa59a877a80280
train_000.jsonl
1330536600
Dr. Moriarty is about to send a message to Sherlock Holmes. He has a string s. String p is called a substring of string s if you can read it starting from some position in the string s. For example, string "aba" has six substrings: "a", "b", "a", "ab", "ba", "aba".Dr. Moriarty plans to take string s and cut out some substring from it, let's call it t. Then he needs to change the substring t zero or more times. As a result, he should obtain a fixed string u (which is the string that should be sent to Sherlock Holmes). One change is defined as making one of the following actions: Insert one letter to any end of the string. Delete one letter from any end of the string. Change one letter into any other one. Moriarty is very smart and after he chooses some substring t, he always makes the minimal number of changes to obtain u. Help Moriarty choose the best substring t from all substrings of the string s. The substring t should minimize the number of changes Moriarty should make to obtain the string u from it.
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.awt.Point; 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 Maxim Gladkikh */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { char[] text = in.next().toCharArray(); char[] pattern = in.next().toCharArray(); int answer = Integer.MAX_VALUE; for (int startPosition = -pattern.length; startPosition < text.length; ++startPosition) { int currentChanges = Math.max(-startPosition, 0) + Math.max(startPosition + pattern.length - text.length, 0); for (int position = Math.max(-startPosition, 0); position < pattern.length && startPosition + position < text.length; ++position) { currentChanges += text[startPosition + position] != pattern[position] ? 1 : 0; } answer = Math.min(answer, currentChanges); } out.println(answer); } } class InputReader { private StringTokenizer tokenizer; private BufferedReader reader; public InputReader(InputStream inputStream) { reader = new BufferedReader(new InputStreamReader(inputStream)); } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { e.printStackTrace(); throw new UnknownError(); } } return tokenizer.nextToken(); } }
Java
["aaaaa\naaa", "abcabc\nbcd", "abcdef\nklmnopq"]
2 seconds
["0", "1", "7"]
NoteIn the first sample Moriarty can take any substring of length 3, and it will be equal to the required message u, so Moriarty won't have to make any changes.In the second sample you should take a substring consisting of characters from second to fourth ("bca") or from fifth to sixth ("bc"). Then you will only have to make one change: to change or to add the last character.In the third sample the initial string s doesn't contain any character that the message should contain, so, whatever string you choose, you will have to make at least 7 changes to obtain the required message.
Java 7
standard input
[ "dp", "brute force", "strings" ]
430486b13b2f3be12cf47fac105056ae
The first line contains a non-empty string s, consisting of lowercase Latin letters. The second line contains a non-empty string u, consisting of lowercase Latin letters. The lengths of both strings are in the range from 1 to 2000, inclusive.
1,700
Print the only integer — the minimum number of changes that Dr. Moriarty has to make with the string that you choose.
standard output
PASSED
4e4bc7fcd68b52a92a9893853baec53f
train_000.jsonl
1330536600
Dr. Moriarty is about to send a message to Sherlock Holmes. He has a string s. String p is called a substring of string s if you can read it starting from some position in the string s. For example, string "aba" has six substrings: "a", "b", "a", "ab", "ba", "aba".Dr. Moriarty plans to take string s and cut out some substring from it, let's call it t. Then he needs to change the substring t zero or more times. As a result, he should obtain a fixed string u (which is the string that should be sent to Sherlock Holmes). One change is defined as making one of the following actions: Insert one letter to any end of the string. Delete one letter from any end of the string. Change one letter into any other one. Moriarty is very smart and after he chooses some substring t, he always makes the minimal number of changes to obtain u. Help Moriarty choose the best substring t from all substrings of the string s. The substring t should minimize the number of changes Moriarty should make to obtain the string u from it.
256 megabytes
import java.util.*; public class C { public static void main(String[] args){ Scanner sc = new Scanner(System.in); String s = sc.nextLine(); String u = sc.nextLine(); int sLen = s.length(); int uLen = u.length(); int minChanges = uLen; for (int i = -uLen; i < sLen; i++){ int neededChanges = 0; for (int j = i; j < i+uLen; j++){ if (j < 0 || j >= sLen) { neededChanges++; } else { if (s.charAt(j) != u.charAt(j-i)) { neededChanges++; } } } if (neededChanges < minChanges) minChanges = neededChanges; } System.out.println(minChanges); } }
Java
["aaaaa\naaa", "abcabc\nbcd", "abcdef\nklmnopq"]
2 seconds
["0", "1", "7"]
NoteIn the first sample Moriarty can take any substring of length 3, and it will be equal to the required message u, so Moriarty won't have to make any changes.In the second sample you should take a substring consisting of characters from second to fourth ("bca") or from fifth to sixth ("bc"). Then you will only have to make one change: to change or to add the last character.In the third sample the initial string s doesn't contain any character that the message should contain, so, whatever string you choose, you will have to make at least 7 changes to obtain the required message.
Java 7
standard input
[ "dp", "brute force", "strings" ]
430486b13b2f3be12cf47fac105056ae
The first line contains a non-empty string s, consisting of lowercase Latin letters. The second line contains a non-empty string u, consisting of lowercase Latin letters. The lengths of both strings are in the range from 1 to 2000, inclusive.
1,700
Print the only integer — the minimum number of changes that Dr. Moriarty has to make with the string that you choose.
standard output
PASSED
64958efddf115f24d9bea35aa4f24ab7
train_000.jsonl
1330536600
Dr. Moriarty is about to send a message to Sherlock Holmes. He has a string s. String p is called a substring of string s if you can read it starting from some position in the string s. For example, string "aba" has six substrings: "a", "b", "a", "ab", "ba", "aba".Dr. Moriarty plans to take string s and cut out some substring from it, let's call it t. Then he needs to change the substring t zero or more times. As a result, he should obtain a fixed string u (which is the string that should be sent to Sherlock Holmes). One change is defined as making one of the following actions: Insert one letter to any end of the string. Delete one letter from any end of the string. Change one letter into any other one. Moriarty is very smart and after he chooses some substring t, he always makes the minimal number of changes to obtain u. Help Moriarty choose the best substring t from all substrings of the string s. The substring t should minimize the number of changes Moriarty should make to obtain the string u from it.
256 megabytes
import java.util.Arrays; import java.util.Scanner; /** * Alexandra Mikhaylova [email protected] */ public class E { private final static int MAX_MSG_SIZE = 2000; private static String BAD_SYMBOLS = getBadSymbols(); private static String getBadSymbols() { char[] badSymbols = new char[MAX_MSG_SIZE]; Arrays.fill(badSymbols, '*'); return new String(badSymbols); } private static int calculateDiff(final String s1, final String s2) { int result = 0; for (int i = 0; i < s1.length(); i ++) { if (s1.charAt(i) != s2.charAt(i)) { result ++; } } return result; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String source = BAD_SYMBOLS + scanner.nextLine() + BAD_SYMBOLS; String msg = scanner.nextLine(); int min = Integer.MAX_VALUE; String substring; for (int i = 0; i <= source.length() - msg.length(); i ++) { substring = source.substring(i, i + msg.length()); min = Math.min(min, calculateDiff(substring, msg)); } System.out.println(min); } }
Java
["aaaaa\naaa", "abcabc\nbcd", "abcdef\nklmnopq"]
2 seconds
["0", "1", "7"]
NoteIn the first sample Moriarty can take any substring of length 3, and it will be equal to the required message u, so Moriarty won't have to make any changes.In the second sample you should take a substring consisting of characters from second to fourth ("bca") or from fifth to sixth ("bc"). Then you will only have to make one change: to change or to add the last character.In the third sample the initial string s doesn't contain any character that the message should contain, so, whatever string you choose, you will have to make at least 7 changes to obtain the required message.
Java 7
standard input
[ "dp", "brute force", "strings" ]
430486b13b2f3be12cf47fac105056ae
The first line contains a non-empty string s, consisting of lowercase Latin letters. The second line contains a non-empty string u, consisting of lowercase Latin letters. The lengths of both strings are in the range from 1 to 2000, inclusive.
1,700
Print the only integer — the minimum number of changes that Dr. Moriarty has to make with the string that you choose.
standard output
PASSED
9d1959cb114a9e803e08f3dff7371482
train_000.jsonl
1330536600
Dr. Moriarty is about to send a message to Sherlock Holmes. He has a string s. String p is called a substring of string s if you can read it starting from some position in the string s. For example, string "aba" has six substrings: "a", "b", "a", "ab", "ba", "aba".Dr. Moriarty plans to take string s and cut out some substring from it, let's call it t. Then he needs to change the substring t zero or more times. As a result, he should obtain a fixed string u (which is the string that should be sent to Sherlock Holmes). One change is defined as making one of the following actions: Insert one letter to any end of the string. Delete one letter from any end of the string. Change one letter into any other one. Moriarty is very smart and after he chooses some substring t, he always makes the minimal number of changes to obtain u. Help Moriarty choose the best substring t from all substrings of the string s. The substring t should minimize the number of changes Moriarty should make to obtain the string u from it.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; public class C { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); solve(in, out); out.close(); } private static void solve(BufferedReader in, PrintWriter out) throws IOException { String s = in.readLine(); String t = in.readLine(); s =rep('@', t.length() + 4)+ s + rep('@', t.length() + 4); int ret = t.length(); for (int i = 0; i + t.length() < s.length(); i++) { String sub = s.substring(i, i + t.length()); int aux = 0; for (int j = 0; j < t.length(); j++) { if (sub.charAt(j) != t.charAt(j)) aux++; } ret = Math.min(ret, aux); } out.println(ret); } private static String rep(char c, int n) { StringBuilder str = new StringBuilder(); for (int i = 0; i < n; i++) str.append(c); return str.toString(); } }
Java
["aaaaa\naaa", "abcabc\nbcd", "abcdef\nklmnopq"]
2 seconds
["0", "1", "7"]
NoteIn the first sample Moriarty can take any substring of length 3, and it will be equal to the required message u, so Moriarty won't have to make any changes.In the second sample you should take a substring consisting of characters from second to fourth ("bca") or from fifth to sixth ("bc"). Then you will only have to make one change: to change or to add the last character.In the third sample the initial string s doesn't contain any character that the message should contain, so, whatever string you choose, you will have to make at least 7 changes to obtain the required message.
Java 7
standard input
[ "dp", "brute force", "strings" ]
430486b13b2f3be12cf47fac105056ae
The first line contains a non-empty string s, consisting of lowercase Latin letters. The second line contains a non-empty string u, consisting of lowercase Latin letters. The lengths of both strings are in the range from 1 to 2000, inclusive.
1,700
Print the only integer — the minimum number of changes that Dr. Moriarty has to make with the string that you choose.
standard output
PASSED
4bc71d412967398edd657a8d649e43e4
train_000.jsonl
1330536600
Dr. Moriarty is about to send a message to Sherlock Holmes. He has a string s. String p is called a substring of string s if you can read it starting from some position in the string s. For example, string "aba" has six substrings: "a", "b", "a", "ab", "ba", "aba".Dr. Moriarty plans to take string s and cut out some substring from it, let's call it t. Then he needs to change the substring t zero or more times. As a result, he should obtain a fixed string u (which is the string that should be sent to Sherlock Holmes). One change is defined as making one of the following actions: Insert one letter to any end of the string. Delete one letter from any end of the string. Change one letter into any other one. Moriarty is very smart and after he chooses some substring t, he always makes the minimal number of changes to obtain u. Help Moriarty choose the best substring t from all substrings of the string s. The substring t should minimize the number of changes Moriarty should make to obtain the string u from it.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Message { public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); sc = new StringTokenizer(br.readLine()); char[] s = nxtCharArr(); char[] t = nxtCharArr(); int ans = Integer.MAX_VALUE; for (int i = 0; i < s.length; i++) { int tmp = 0; int j = 0; for (j = 0; j < t.length && i + j < s.length; j++) if (s[i + j] != t[j]) tmp++; tmp += t.length - j; ans = Math.min(ans, tmp); } for (int i = 0; i < t.length; i++) { int tmp = i; int j = 0; for (j = 0; j < s.length && i + j < t.length; j++) if (t[i + j] != s[j]) tmp++; tmp += t.length - (i + j); ans = Math.min(ans, tmp); } out.println(ans); br.close(); out.close(); } static BufferedReader br; static StringTokenizer sc; static String nxtTok() throws IOException { while (!sc.hasMoreTokens()) { String s = br.readLine(); if (s == null) return null; sc = new StringTokenizer(s.trim()); } return sc.nextToken(); } static int nxtInt() throws IOException { return Integer.parseInt(nxtTok()); } static long nxtLng() throws IOException { return Long.parseLong(nxtTok()); } static double nxtDbl() throws IOException { return Double.parseDouble(nxtTok()); } static int[] nxtIntArr(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nxtInt(); return a; } static long[] nxtLngArr(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nxtLng(); return a; } static char[] nxtCharArr() throws IOException { return nxtTok().toCharArray(); } }
Java
["aaaaa\naaa", "abcabc\nbcd", "abcdef\nklmnopq"]
2 seconds
["0", "1", "7"]
NoteIn the first sample Moriarty can take any substring of length 3, and it will be equal to the required message u, so Moriarty won't have to make any changes.In the second sample you should take a substring consisting of characters from second to fourth ("bca") or from fifth to sixth ("bc"). Then you will only have to make one change: to change or to add the last character.In the third sample the initial string s doesn't contain any character that the message should contain, so, whatever string you choose, you will have to make at least 7 changes to obtain the required message.
Java 7
standard input
[ "dp", "brute force", "strings" ]
430486b13b2f3be12cf47fac105056ae
The first line contains a non-empty string s, consisting of lowercase Latin letters. The second line contains a non-empty string u, consisting of lowercase Latin letters. The lengths of both strings are in the range from 1 to 2000, inclusive.
1,700
Print the only integer — the minimum number of changes that Dr. Moriarty has to make with the string that you choose.
standard output
PASSED
d6903db93442a0810a3538c1e3208138
train_000.jsonl
1330536600
Dr. Moriarty is about to send a message to Sherlock Holmes. He has a string s. String p is called a substring of string s if you can read it starting from some position in the string s. For example, string "aba" has six substrings: "a", "b", "a", "ab", "ba", "aba".Dr. Moriarty plans to take string s and cut out some substring from it, let's call it t. Then he needs to change the substring t zero or more times. As a result, he should obtain a fixed string u (which is the string that should be sent to Sherlock Holmes). One change is defined as making one of the following actions: Insert one letter to any end of the string. Delete one letter from any end of the string. Change one letter into any other one. Moriarty is very smart and after he chooses some substring t, he always makes the minimal number of changes to obtain u. Help Moriarty choose the best substring t from all substrings of the string s. The substring t should minimize the number of changes Moriarty should make to obtain the string u from it.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Message { public static void main(String args[]) throws IOException { BufferedReader br; br = new BufferedReader(new InputStreamReader(System.in)); StringBuffer read = new StringBuffer(br.readLine()); StringBuffer write = new StringBuffer(br.readLine()); int w = write.length()-1; for(int i=0; i<w; i++) { StringBuffer ww = new StringBuffer("0"); read.append(ww); read = ww.append(read); } int max = 0; for(int i=0; i<read.length()-write.length()+1; i++) { int res = match(read.substring(i, i+write.length()),write.substring(0, write.length())); max = Math.max(max, res); } System.out.println( w+1-max); } public static int match(String a, String b) { int c=0; char[] aa = a.toCharArray(); char[] bb = b.toCharArray(); for(int i=0; i<a.length(); i++) { if(aa[i]==bb[i]) c++; } return c; } }
Java
["aaaaa\naaa", "abcabc\nbcd", "abcdef\nklmnopq"]
2 seconds
["0", "1", "7"]
NoteIn the first sample Moriarty can take any substring of length 3, and it will be equal to the required message u, so Moriarty won't have to make any changes.In the second sample you should take a substring consisting of characters from second to fourth ("bca") or from fifth to sixth ("bc"). Then you will only have to make one change: to change or to add the last character.In the third sample the initial string s doesn't contain any character that the message should contain, so, whatever string you choose, you will have to make at least 7 changes to obtain the required message.
Java 7
standard input
[ "dp", "brute force", "strings" ]
430486b13b2f3be12cf47fac105056ae
The first line contains a non-empty string s, consisting of lowercase Latin letters. The second line contains a non-empty string u, consisting of lowercase Latin letters. The lengths of both strings are in the range from 1 to 2000, inclusive.
1,700
Print the only integer — the minimum number of changes that Dr. Moriarty has to make with the string that you choose.
standard output
PASSED
6c4f8c9cd5911402328b7c91514b7152
train_000.jsonl
1330536600
Dr. Moriarty is about to send a message to Sherlock Holmes. He has a string s. String p is called a substring of string s if you can read it starting from some position in the string s. For example, string "aba" has six substrings: "a", "b", "a", "ab", "ba", "aba".Dr. Moriarty plans to take string s and cut out some substring from it, let's call it t. Then he needs to change the substring t zero or more times. As a result, he should obtain a fixed string u (which is the string that should be sent to Sherlock Holmes). One change is defined as making one of the following actions: Insert one letter to any end of the string. Delete one letter from any end of the string. Change one letter into any other one. Moriarty is very smart and after he chooses some substring t, he always makes the minimal number of changes to obtain u. Help Moriarty choose the best substring t from all substrings of the string s. The substring t should minimize the number of changes Moriarty should make to obtain the string u from it.
256 megabytes
import java.io.PrintWriter; import java.util.Scanner; public class Main{ public static void go(Scanner in, PrintWriter out) { String s = in.nextLine(); String u = in.nextLine(); int ans = u.length(); for (int start = -u.length()+1; start < s.length(); start++) { // start..start+u.length()-1 int count = 0; for (int i = start; i < start+u.length(); i++) { if (i < 0 || i >= s.length()) { count++; } else { if (s.charAt(i) != u.charAt(i-start)) { count++; } } } ans = Math.min(ans, count); } out.println(ans); } public static void main(String[] args) { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); go(in, out); out.flush(); } }
Java
["aaaaa\naaa", "abcabc\nbcd", "abcdef\nklmnopq"]
2 seconds
["0", "1", "7"]
NoteIn the first sample Moriarty can take any substring of length 3, and it will be equal to the required message u, so Moriarty won't have to make any changes.In the second sample you should take a substring consisting of characters from second to fourth ("bca") or from fifth to sixth ("bc"). Then you will only have to make one change: to change or to add the last character.In the third sample the initial string s doesn't contain any character that the message should contain, so, whatever string you choose, you will have to make at least 7 changes to obtain the required message.
Java 7
standard input
[ "dp", "brute force", "strings" ]
430486b13b2f3be12cf47fac105056ae
The first line contains a non-empty string s, consisting of lowercase Latin letters. The second line contains a non-empty string u, consisting of lowercase Latin letters. The lengths of both strings are in the range from 1 to 2000, inclusive.
1,700
Print the only integer — the minimum number of changes that Dr. Moriarty has to make with the string that you choose.
standard output
PASSED
97a0ba757dca204565c7d12d9c35c60e
train_000.jsonl
1596119700
Uncle Bogdan is in captain Flint's crew for a long time and sometimes gets nostalgic for his homeland. Today he told you how his country introduced a happiness index.There are $$$n$$$ cities and $$$n−1$$$ undirected roads connecting pairs of cities. Citizens of any city can reach any other city traveling by these roads. Cities are numbered from $$$1$$$ to $$$n$$$ and the city $$$1$$$ is a capital. In other words, the country has a tree structure.There are $$$m$$$ citizens living in the country. A $$$p_i$$$ people live in the $$$i$$$-th city but all of them are working in the capital. At evening all citizens return to their home cities using the shortest paths. Every person has its own mood: somebody leaves his workplace in good mood but somebody are already in bad mood. Moreover any person can ruin his mood on the way to the hometown. If person is in bad mood he won't improve it.Happiness detectors are installed in each city to monitor the happiness of each person who visits the city. The detector in the $$$i$$$-th city calculates a happiness index $$$h_i$$$ as the number of people in good mood minus the number of people in bad mood. Let's say for the simplicity that mood of a person doesn't change inside the city.Happiness detector is still in development, so there is a probability of a mistake in judging a person's happiness. One late evening, when all citizens successfully returned home, the government asked uncle Bogdan (the best programmer of the country) to check the correctness of the collected happiness indexes.Uncle Bogdan successfully solved the problem. Can you do the same?More formally, You need to check: "Is it possible that, after all people return home, for each city $$$i$$$ the happiness index will be equal exactly to $$$h_i$$$".
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.util.*; public class Main { public static boolean f(ArrayList<ArrayList<Integer>> tree, long[] h, long[] good, long[] bad, long[] sums, int v, boolean[] used) { if (used[v]) return true; used[v] = true; boolean result = true; for (Integer c : tree.get(v)) { if (used[c]) continue; // goodC + badC = sums[c]; goodC = sums[c] - badC // goodC - badC = h[c]; sums[c] - 2*badC = h[c]; badC = (sums[c] - h[c]) / 2 if (((sums[c] - h[c]) % 2 != 0) || (sums[c] < h[c])) { return false; } long badC = (sums[c] - h[c]) / 2; long goodC = sums[c] - badC; if (goodC < 0) { return false; } good[c] = goodC; bad[c] = badC; long goodV = good[v], badV = bad[v]; bad[v] = Math.max(0, badV - badC); badC = Math.max(0, badC - badV); good[v] = Math.max(0, goodV - badC); badC = Math.max(0, badC - goodV); good[v] = Math.max(0, goodV - goodC); goodC = Math.max(0, goodC - goodV); if (goodC > 0 || badC > 0) { return false; } result &= f(tree, h, good, bad, sums, c, used); } return result; } public static void sumTree(ArrayList<ArrayList<Integer>> tree, long[] p, long[] sums, int v, boolean[] used) { if (used[v]) return; used[v] = true; long currentSum = p[v]; for (Integer c : tree.get(v)) { sumTree(tree, p, sums, c, used); currentSum += sums[c]; } sums[v] = currentSum; } public static void main(String[] args) throws IOException { // BufferedReader br = new BufferedReader( // new InputStreamReader(System.in)); // BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out)); // log.flush(); Scanner sc = new Scanner(System.in); int test = sc.nextInt(); for (int t = 0; t < test; t++) { int n = sc.nextInt(); long m = sc.nextLong(); long[] p = new long[n]; for (int i = 0; i < n; i++) { p[i] = sc.nextInt(); } long[] h = new long[n]; for (int i = 0; i < n; i++) { h[i] = sc.nextInt(); } ArrayList<ArrayList<Integer>> tree = new ArrayList<>(); for (int i = 0; i < n; i++) { tree.add(new ArrayList<>()); } for (int i = 0; i < n - 1; i++) { int a = sc.nextInt() - 1, b = sc.nextInt() - 1; tree.get(a).add(b); tree.get(b).add(a); } // System.out.println(tree); long[] good = new long[n], bad = new long[n], sums = new long[n]; sumTree(tree, p, sums, 0, new boolean[n]); if (((sums[0] - h[0]) % 2 != 0) || sums[0] < h[0]) { System.out.println("NO"); continue; } bad[0] = (sums[0] - h[0]) / 2; good[0] = sums[0] - bad[0]; if (good[0] < 0) { System.out.println("NO"); continue; } if (sums[0] != m) { System.out.println(sums[0] + " " + m); System.out.println(tree); for (int i = 0; i < n; i++) { System.out.print(p[i] + " "); } System.out.println(); for (int i = 0; i < n; i++) { System.out.print(h[i] + " "); } System.out.println("NO"); continue; } if (f(tree, h, good, bad, sums, 0, new boolean[n])) { System.out.println("YES"); } else { System.out.println("NO"); } } } }
Java
["2\n7 4\n1 0 1 1 0 1 0\n4 0 0 -1 0 -1 0\n1 2\n1 3\n1 4\n3 5\n3 6\n3 7\n5 11\n1 2 5 2 1\n-11 -2 -6 -2 -1\n1 2\n1 3\n1 4\n3 5", "2\n4 4\n1 1 1 1\n4 1 -3 -1\n1 2\n1 3\n1 4\n3 13\n3 3 7\n13 1 4\n1 2\n1 3"]
2 seconds
["YES\nYES", "NO\nNO"]
NoteLet's look at the first test case of the first sample: At first, all citizens are in the capital. Let's describe one of possible scenarios: a person from city $$$1$$$: he lives in the capital and is in good mood; a person from city $$$4$$$: he visited cities $$$1$$$ and $$$4$$$, his mood was ruined between cities $$$1$$$ and $$$4$$$; a person from city $$$3$$$: he visited cities $$$1$$$ and $$$3$$$ in good mood; a person from city $$$6$$$: he visited cities $$$1$$$, $$$3$$$ and $$$6$$$, his mood was ruined between cities $$$1$$$ and $$$3$$$; In total, $$$h_1 = 4 - 0 = 4$$$, $$$h_2 = 0$$$, $$$h_3 = 1 - 1 = 0$$$, $$$h_4 = 0 - 1 = -1$$$, $$$h_5 = 0$$$, $$$h_6 = 0 - 1 = -1$$$, $$$h_7 = 0$$$. The second case of the first test: All people have already started in bad mood in the capital — this is the only possible scenario.The first case of the second test: The second case of the second test: It can be proven that there is no way to achieve given happiness indexes in both cases of the second test.
Java 11
standard input
[ "greedy", "dfs and similar", "trees", "math" ]
0369c070f4ac9aba4887bae32ad8b85b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^5$$$; $$$0 \le m \le 10^9$$$) — the number of cities and citizens. The second line of each test case contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_{n}$$$ ($$$0 \le p_i \le m$$$; $$$p_1 + p_2 + \ldots + p_{n} = m$$$), where $$$p_i$$$ is the number of people living in the $$$i$$$-th city. The third line contains $$$n$$$ integers $$$h_1, h_2, \ldots, h_{n}$$$ ($$$-10^9 \le h_i \le 10^9$$$), where $$$h_i$$$ is the calculated happiness index of the $$$i$$$-th city. Next $$$n − 1$$$ lines contain description of the roads, one per line. Each line contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$; $$$x_i \neq y_i$$$), where $$$x_i$$$ and $$$y_i$$$ are cities connected by the $$$i$$$-th road. It's guaranteed that the sum of $$$n$$$ from all test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,800
For each test case, print YES, if the collected data is correct, or NO — otherwise. You can print characters in YES or NO in any case.
standard output
PASSED
f305ce6295debb9795002c46ecc70c5c
train_000.jsonl
1596119700
Uncle Bogdan is in captain Flint's crew for a long time and sometimes gets nostalgic for his homeland. Today he told you how his country introduced a happiness index.There are $$$n$$$ cities and $$$n−1$$$ undirected roads connecting pairs of cities. Citizens of any city can reach any other city traveling by these roads. Cities are numbered from $$$1$$$ to $$$n$$$ and the city $$$1$$$ is a capital. In other words, the country has a tree structure.There are $$$m$$$ citizens living in the country. A $$$p_i$$$ people live in the $$$i$$$-th city but all of them are working in the capital. At evening all citizens return to their home cities using the shortest paths. Every person has its own mood: somebody leaves his workplace in good mood but somebody are already in bad mood. Moreover any person can ruin his mood on the way to the hometown. If person is in bad mood he won't improve it.Happiness detectors are installed in each city to monitor the happiness of each person who visits the city. The detector in the $$$i$$$-th city calculates a happiness index $$$h_i$$$ as the number of people in good mood minus the number of people in bad mood. Let's say for the simplicity that mood of a person doesn't change inside the city.Happiness detector is still in development, so there is a probability of a mistake in judging a person's happiness. One late evening, when all citizens successfully returned home, the government asked uncle Bogdan (the best programmer of the country) to check the correctness of the collected happiness indexes.Uncle Bogdan successfully solved the problem. Can you do the same?More formally, You need to check: "Is it possible that, after all people return home, for each city $$$i$$$ the happiness index will be equal exactly to $$$h_i$$$".
256 megabytes
//package Codeforces.Round660Div2.C_UncleBogdanAndCountryHappiness; import java.util.*; public class C_UncleBogdanAndCountryHappiness { static class City { int id; long pop; long hi; long happy; long unhappy; long totalpop; boolean isVisited; City parent; ArrayList<City> adjacentcity = new ArrayList<>(); City(int id) { this.id = id; this.isVisited = false; this.parent = null; } } static class Country { ArrayList<City> citylist; Country(int n) { this.citylist = new ArrayList<>(n); for(int i=0;i<n;i++) { citylist.add(new City(i)); } } public void addRoad(int xi, int yi) { City u = citylist.get(xi); City v = citylist.get(yi); u.adjacentcity.add(v); v.adjacentcity.add(u); } public String dfs(int m) { City source = citylist.get(0); Stack<City> stk = new Stack<>(); Stack<Integer> ptrstk = new Stack<>(); stk.push(source); ptrstk.push(-1); source.isVisited = true; while (!stk.isEmpty()) { City cur = stk.pop(); int ptr = ptrstk.pop(); if(ptr<cur.adjacentcity.size()-1) { ptr++; stk.push(cur); ptrstk.push(ptr); City next = cur.adjacentcity.get(ptr); if(!next.isVisited) { next.parent = cur; stk.push(next); ptrstk.push(-1); next.isVisited = true; next.totalpop = next.pop; if(next.adjacentcity.size()==1) { long happy, unhappy; if(Math.abs(next.hi%2)==0 && next.totalpop%2==0) { happy = (next.totalpop/2+next.hi/2); unhappy = (next.totalpop-happy); } else if(Math.abs(next.hi%2)==1 && next.totalpop%2==1) { if(next.hi<0) { happy = (next.totalpop/2)-(next.hi/2); } else { happy = (next.totalpop/2)+(next.hi/2+1); } unhappy = (next.totalpop-happy); } else { /*for(City c: cur.adjacentcity) if(c!=cur.parent) { System.out.println(c.totalpop); }*/ //System.out.println("test "+next.id+" "+next.hi+" "+next.totalpop); return "NO"; } next.happy = happy; next.unhappy = unhappy; } } } else { long totalpop = cur.pop; long totalhappy = 0; long totalunhappy = 0; for(City c: cur.adjacentcity) if(c!=cur.parent) { totalpop += c.totalpop; totalhappy += c.happy; totalunhappy += c.unhappy; } long happy, unhappy; if(Math.abs(cur.hi%2)==0 && totalpop%2==0) { happy = (totalpop/2+cur.hi/2); unhappy = (totalpop-happy); } else if(Math.abs(cur.hi%2)==1 && totalpop%2==1) { if(cur.hi<0) { happy = (totalpop/2)-Math.abs(cur.hi/2); } else { happy = (totalpop/2)+(cur.hi/2+1); } unhappy = (totalpop-happy); } else { return "NO"; } long happyhere = happy-totalhappy; long unhappyhere = unhappy-totalunhappy; if(happy<totalhappy) { return "NO"; } else if(happy+unhappy!=cur.pop+totalhappy+totalunhappy) { return "NO"; } else if(happy+unhappy!=totalpop) { return "NO"; } else if(happyhere<0 || happyhere+unhappyhere!=cur.pop) { //System.out.println(cur.id+" "+(happyhere+unhappyhere)); return "NO"; } else if(Math.abs(cur.hi)>totalpop) { return "NO"; } cur.totalpop = totalpop; cur.happy = happy; cur.unhappy = unhappy; } } if(m!=source.totalpop) return "NO"; return "YES"; } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while (t-->0) { int n = sc.nextInt(); int m = sc.nextInt(); Country country = new Country(n); for(int i=0;i<n;i++) { country.citylist.get(i).pop = sc.nextLong(); } for(int i=0;i<n;i++) { country.citylist.get(i).hi = sc.nextLong(); } for(int i=0;i<n-1;i++) { int xi = sc.nextInt()-1; int yi = sc.nextInt()-1; country.addRoad(xi, yi); } System.out.println(country.dfs(m)); } } }
Java
["2\n7 4\n1 0 1 1 0 1 0\n4 0 0 -1 0 -1 0\n1 2\n1 3\n1 4\n3 5\n3 6\n3 7\n5 11\n1 2 5 2 1\n-11 -2 -6 -2 -1\n1 2\n1 3\n1 4\n3 5", "2\n4 4\n1 1 1 1\n4 1 -3 -1\n1 2\n1 3\n1 4\n3 13\n3 3 7\n13 1 4\n1 2\n1 3"]
2 seconds
["YES\nYES", "NO\nNO"]
NoteLet's look at the first test case of the first sample: At first, all citizens are in the capital. Let's describe one of possible scenarios: a person from city $$$1$$$: he lives in the capital and is in good mood; a person from city $$$4$$$: he visited cities $$$1$$$ and $$$4$$$, his mood was ruined between cities $$$1$$$ and $$$4$$$; a person from city $$$3$$$: he visited cities $$$1$$$ and $$$3$$$ in good mood; a person from city $$$6$$$: he visited cities $$$1$$$, $$$3$$$ and $$$6$$$, his mood was ruined between cities $$$1$$$ and $$$3$$$; In total, $$$h_1 = 4 - 0 = 4$$$, $$$h_2 = 0$$$, $$$h_3 = 1 - 1 = 0$$$, $$$h_4 = 0 - 1 = -1$$$, $$$h_5 = 0$$$, $$$h_6 = 0 - 1 = -1$$$, $$$h_7 = 0$$$. The second case of the first test: All people have already started in bad mood in the capital — this is the only possible scenario.The first case of the second test: The second case of the second test: It can be proven that there is no way to achieve given happiness indexes in both cases of the second test.
Java 11
standard input
[ "greedy", "dfs and similar", "trees", "math" ]
0369c070f4ac9aba4887bae32ad8b85b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^5$$$; $$$0 \le m \le 10^9$$$) — the number of cities and citizens. The second line of each test case contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_{n}$$$ ($$$0 \le p_i \le m$$$; $$$p_1 + p_2 + \ldots + p_{n} = m$$$), where $$$p_i$$$ is the number of people living in the $$$i$$$-th city. The third line contains $$$n$$$ integers $$$h_1, h_2, \ldots, h_{n}$$$ ($$$-10^9 \le h_i \le 10^9$$$), where $$$h_i$$$ is the calculated happiness index of the $$$i$$$-th city. Next $$$n − 1$$$ lines contain description of the roads, one per line. Each line contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$; $$$x_i \neq y_i$$$), where $$$x_i$$$ and $$$y_i$$$ are cities connected by the $$$i$$$-th road. It's guaranteed that the sum of $$$n$$$ from all test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,800
For each test case, print YES, if the collected data is correct, or NO — otherwise. You can print characters in YES or NO in any case.
standard output
PASSED
9ff87a18dea725290cdccfabf37813f9
train_000.jsonl
1596119700
Uncle Bogdan is in captain Flint's crew for a long time and sometimes gets nostalgic for his homeland. Today he told you how his country introduced a happiness index.There are $$$n$$$ cities and $$$n−1$$$ undirected roads connecting pairs of cities. Citizens of any city can reach any other city traveling by these roads. Cities are numbered from $$$1$$$ to $$$n$$$ and the city $$$1$$$ is a capital. In other words, the country has a tree structure.There are $$$m$$$ citizens living in the country. A $$$p_i$$$ people live in the $$$i$$$-th city but all of them are working in the capital. At evening all citizens return to their home cities using the shortest paths. Every person has its own mood: somebody leaves his workplace in good mood but somebody are already in bad mood. Moreover any person can ruin his mood on the way to the hometown. If person is in bad mood he won't improve it.Happiness detectors are installed in each city to monitor the happiness of each person who visits the city. The detector in the $$$i$$$-th city calculates a happiness index $$$h_i$$$ as the number of people in good mood minus the number of people in bad mood. Let's say for the simplicity that mood of a person doesn't change inside the city.Happiness detector is still in development, so there is a probability of a mistake in judging a person's happiness. One late evening, when all citizens successfully returned home, the government asked uncle Bogdan (the best programmer of the country) to check the correctness of the collected happiness indexes.Uncle Bogdan successfully solved the problem. Can you do the same?More formally, You need to check: "Is it possible that, after all people return home, for each city $$$i$$$ the happiness index will be equal exactly to $$$h_i$$$".
256 megabytes
import java.io.*; import java.util.*; import java.util.stream.Collectors; public class Main { class Node{ int pass; int p; int h; int i; Set<Node> ch; } void remParr(Node node, Node par){ node.ch.remove(par); for (Node ch : node.ch) { remParr(ch, node); } } void calcPass(Node node){ node.pass = node.p; for (Node ch : node.ch) { calcPass(ch); node.pass += ch.pass; } } int calcGood(Node node){ if ((node.h + node.pass)%2!=0){ can = false; } int g = (node.h + node.pass)/2; int sum = 0; for (Node ch : node.ch) { sum += calcGood(ch); } if (g>node.pass){ can = false; } if (sum>g) { can = false; } return Math.min(g, node.pass); } boolean can; int m; void solve() { int n = in.nextInt(); m = in.nextInt(); int[] p = in.nextInts(n); int[] h = in.nextInts(n); Node[] nodes = new Node[n]; for (int i = 0; i < n; i++) { nodes[i] = new Node(); nodes[i].i = i; nodes[i].p = p[i]; nodes[i].h = h[i]; nodes[i].ch = new HashSet<>(); } for (int i = 0; i < n - 1; i++) { int u = in.nextInt()-1; int v = in.nextInt()-1; nodes[u].ch.add(nodes[v]); nodes[v].ch.add(nodes[u]); } remParr(nodes[0], null); calcPass(nodes[0]); can = true; int tmp = calcGood(nodes[0]); if (tmp>m){ can = false; } if (can){ out.println("YES"); }else{ out.println("NO"); } } static final boolean MULTI_TEST = true; // -------------------------------------------------------------------------------------------------------------- // --------------------------------------------------HELPER------------------------------------------------------ // -------------------------------------------------------------------------------------------------------------- void run() { if (MULTI_TEST) { int t = in.nextInt(); for (int i = 0; i < t; i++) { solve(); } } else { solve(); } } // --------------------ALGORITHM------------------------- public void sort(int[] arr) { List<Integer> tmp = Arrays.stream(arr).boxed().sorted().collect(Collectors.toList()); for (int i = 0; i < arr.length; i++) { arr[i] = tmp.get(i); } } // --------------------SCANNER------------------------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner(String fileName) { if (fileName != null) { try { br = new BufferedReader(new FileReader(fileName)); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } else { br = new BufferedReader(new InputStreamReader(System.in)); } } String next() { while (st == null || !st.hasMoreElements()) { st = new StringTokenizer(nextLine()); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] nextInts(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } long nextLong() { return Long.parseLong(next()); } public long[] nextLongs(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { try { String line = br.readLine(); if (line == null) { throw new RuntimeException("empty line"); } return line; } catch (IOException e) { throw new RuntimeException(e); } } } // --------------------WRITER------------------------- public static class MyWriter extends PrintWriter { public static MyWriter of(String fileName) { if (fileName != null) { try { return new MyWriter(new FileWriter(fileName)); } catch (IOException e) { throw new RuntimeException(e); } } else { return new MyWriter(new BufferedOutputStream(System.out)); } } public MyWriter(FileWriter fileWriter) { super(fileWriter); } public MyWriter(OutputStream out) { super(out); } void println(int[] arr) { String line = Arrays.stream(arr).mapToObj(String::valueOf).collect(Collectors.joining(" ")); println(line); } } // --------------------MAIN------------------------- public MyScanner in; public MyWriter out; /** * run as `java Main`, `java Main input.txt' or `java Main input.txt output.txt' * add `-Xss256m` to increase stack size */ public static void main(String[] args) { Main m = new Main(); m.in = new MyScanner(args.length > 0 ? args[0] : null); m.out = MyWriter.of(args.length > 1 ? args[1] : null); m.run(); m.out.close(); } }
Java
["2\n7 4\n1 0 1 1 0 1 0\n4 0 0 -1 0 -1 0\n1 2\n1 3\n1 4\n3 5\n3 6\n3 7\n5 11\n1 2 5 2 1\n-11 -2 -6 -2 -1\n1 2\n1 3\n1 4\n3 5", "2\n4 4\n1 1 1 1\n4 1 -3 -1\n1 2\n1 3\n1 4\n3 13\n3 3 7\n13 1 4\n1 2\n1 3"]
2 seconds
["YES\nYES", "NO\nNO"]
NoteLet's look at the first test case of the first sample: At first, all citizens are in the capital. Let's describe one of possible scenarios: a person from city $$$1$$$: he lives in the capital and is in good mood; a person from city $$$4$$$: he visited cities $$$1$$$ and $$$4$$$, his mood was ruined between cities $$$1$$$ and $$$4$$$; a person from city $$$3$$$: he visited cities $$$1$$$ and $$$3$$$ in good mood; a person from city $$$6$$$: he visited cities $$$1$$$, $$$3$$$ and $$$6$$$, his mood was ruined between cities $$$1$$$ and $$$3$$$; In total, $$$h_1 = 4 - 0 = 4$$$, $$$h_2 = 0$$$, $$$h_3 = 1 - 1 = 0$$$, $$$h_4 = 0 - 1 = -1$$$, $$$h_5 = 0$$$, $$$h_6 = 0 - 1 = -1$$$, $$$h_7 = 0$$$. The second case of the first test: All people have already started in bad mood in the capital — this is the only possible scenario.The first case of the second test: The second case of the second test: It can be proven that there is no way to achieve given happiness indexes in both cases of the second test.
Java 11
standard input
[ "greedy", "dfs and similar", "trees", "math" ]
0369c070f4ac9aba4887bae32ad8b85b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^5$$$; $$$0 \le m \le 10^9$$$) — the number of cities and citizens. The second line of each test case contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_{n}$$$ ($$$0 \le p_i \le m$$$; $$$p_1 + p_2 + \ldots + p_{n} = m$$$), where $$$p_i$$$ is the number of people living in the $$$i$$$-th city. The third line contains $$$n$$$ integers $$$h_1, h_2, \ldots, h_{n}$$$ ($$$-10^9 \le h_i \le 10^9$$$), where $$$h_i$$$ is the calculated happiness index of the $$$i$$$-th city. Next $$$n − 1$$$ lines contain description of the roads, one per line. Each line contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$; $$$x_i \neq y_i$$$), where $$$x_i$$$ and $$$y_i$$$ are cities connected by the $$$i$$$-th road. It's guaranteed that the sum of $$$n$$$ from all test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,800
For each test case, print YES, if the collected data is correct, or NO — otherwise. You can print characters in YES or NO in any case.
standard output
PASSED
4717dbffefb4ac03257d3518e539ca55
train_000.jsonl
1596119700
Uncle Bogdan is in captain Flint's crew for a long time and sometimes gets nostalgic for his homeland. Today he told you how his country introduced a happiness index.There are $$$n$$$ cities and $$$n−1$$$ undirected roads connecting pairs of cities. Citizens of any city can reach any other city traveling by these roads. Cities are numbered from $$$1$$$ to $$$n$$$ and the city $$$1$$$ is a capital. In other words, the country has a tree structure.There are $$$m$$$ citizens living in the country. A $$$p_i$$$ people live in the $$$i$$$-th city but all of them are working in the capital. At evening all citizens return to their home cities using the shortest paths. Every person has its own mood: somebody leaves his workplace in good mood but somebody are already in bad mood. Moreover any person can ruin his mood on the way to the hometown. If person is in bad mood he won't improve it.Happiness detectors are installed in each city to monitor the happiness of each person who visits the city. The detector in the $$$i$$$-th city calculates a happiness index $$$h_i$$$ as the number of people in good mood minus the number of people in bad mood. Let's say for the simplicity that mood of a person doesn't change inside the city.Happiness detector is still in development, so there is a probability of a mistake in judging a person's happiness. One late evening, when all citizens successfully returned home, the government asked uncle Bogdan (the best programmer of the country) to check the correctness of the collected happiness indexes.Uncle Bogdan successfully solved the problem. Can you do the same?More formally, You need to check: "Is it possible that, after all people return home, for each city $$$i$$$ the happiness index will be equal exactly to $$$h_i$$$".
256 megabytes
import java.io.*; import java.util.*; import java.util.stream.Collectors; public class Main { private int[] p; private int[] h; private List<List<Integer>> graph; static class Node { int h; int p; int w; int g; List<Node> children; } Node build(int u, int parent) { Node node = new Node(); node.h = h[u]; node.p = p[u]; node.children = new ArrayList<>(); for (int v : graph.get(u)) { if (v == parent) continue; node.children.add(build(v, u)); } return node; } boolean can(Node node) { int gSum = 0; node.w = node.p; for (Node child : node.children) { if (!can(child)) return false; gSum += child.g; node.w += child.w; } int tmp = node.w + node.h; if (tmp < 0 || tmp % 2 != 0) return false; node.g = tmp / 2; if (node.g > node.w) return false; return gSum <= node.g; } void solve() { int n = in.nextInt(); int m = in.nextInt(); p = in.nextInts(n); h = in.nextInts(n); graph = new ArrayList<>(); for (int i = 0; i <= n; i++) { graph.add(new ArrayList<>()); } for (int i = 0; i < n - 1; i++) { int u = in.nextInt() - 1; int v = in.nextInt() - 1; graph.get(u).add(v); graph.get(v).add(u); } Node root = build(0, -1); if (can(root)) { out.println("YES"); } else { out.println("NO"); } } static final boolean MULTI_TEST = true; // -------------------------------------------------------------------------------------------------------------- // --------------------------------------------------HELPER------------------------------------------------------ // -------------------------------------------------------------------------------------------------------------- void run() { if (MULTI_TEST) { int t = in.nextInt(); for (int i = 0; i < t; i++) { solve(); } } else { solve(); } } // --------------------ALGORITHM------------------------- public void sort(int[] arr) { List<Integer> tmp = Arrays.stream(arr).boxed().sorted().collect(Collectors.toList()); for (int i = 0; i < arr.length; i++) { arr[i] = tmp.get(i); } } // --------------------SCANNER------------------------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner(String fileName) { if (fileName != null) { try { br = new BufferedReader(new FileReader(fileName)); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } else { br = new BufferedReader(new InputStreamReader(System.in)); } } String next() { while (st == null || !st.hasMoreElements()) { st = new StringTokenizer(nextLine()); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] nextInts(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } boolean[] nextLineBools() { String line = nextLine(); int n = line.length(); boolean[] booleans = new boolean[n]; for (int i = 0; i < n; i++) { booleans[i] = line.charAt(i) == '1'; } return booleans; } long nextLong() { return Long.parseLong(next()); } public long[] nextLongs(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { try { String line = br.readLine(); if (line == null) { throw new RuntimeException("empty line"); } return line; } catch (IOException e) { throw new RuntimeException(e); } } } // --------------------WRITER------------------------- public static class MyWriter extends PrintWriter { public static MyWriter of(String fileName) { if (fileName != null) { try { return new MyWriter(new FileWriter(fileName)); } catch (IOException e) { throw new RuntimeException(e); } } else { return new MyWriter(new BufferedOutputStream(System.out)); } } public MyWriter(FileWriter fileWriter) { super(fileWriter); } public MyWriter(OutputStream out) { super(out); } void println(int[] arr) { String line = Arrays.stream(arr).mapToObj(String::valueOf).collect(Collectors.joining(" ")); println(line); } } // --------------------MAIN------------------------- public MyScanner in; public MyWriter out; /** * run as `java Main`, `java Main input.txt' or `java Main input.txt output.txt' * add `-Xss256m` to increase stack size */ public static void main(String[] args) { Main m = new Main(); m.in = new MyScanner(args.length > 0 ? args[0] : null); m.out = MyWriter.of(args.length > 1 ? args[1] : null); m.run(); m.out.close(); } }
Java
["2\n7 4\n1 0 1 1 0 1 0\n4 0 0 -1 0 -1 0\n1 2\n1 3\n1 4\n3 5\n3 6\n3 7\n5 11\n1 2 5 2 1\n-11 -2 -6 -2 -1\n1 2\n1 3\n1 4\n3 5", "2\n4 4\n1 1 1 1\n4 1 -3 -1\n1 2\n1 3\n1 4\n3 13\n3 3 7\n13 1 4\n1 2\n1 3"]
2 seconds
["YES\nYES", "NO\nNO"]
NoteLet's look at the first test case of the first sample: At first, all citizens are in the capital. Let's describe one of possible scenarios: a person from city $$$1$$$: he lives in the capital and is in good mood; a person from city $$$4$$$: he visited cities $$$1$$$ and $$$4$$$, his mood was ruined between cities $$$1$$$ and $$$4$$$; a person from city $$$3$$$: he visited cities $$$1$$$ and $$$3$$$ in good mood; a person from city $$$6$$$: he visited cities $$$1$$$, $$$3$$$ and $$$6$$$, his mood was ruined between cities $$$1$$$ and $$$3$$$; In total, $$$h_1 = 4 - 0 = 4$$$, $$$h_2 = 0$$$, $$$h_3 = 1 - 1 = 0$$$, $$$h_4 = 0 - 1 = -1$$$, $$$h_5 = 0$$$, $$$h_6 = 0 - 1 = -1$$$, $$$h_7 = 0$$$. The second case of the first test: All people have already started in bad mood in the capital — this is the only possible scenario.The first case of the second test: The second case of the second test: It can be proven that there is no way to achieve given happiness indexes in both cases of the second test.
Java 11
standard input
[ "greedy", "dfs and similar", "trees", "math" ]
0369c070f4ac9aba4887bae32ad8b85b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^5$$$; $$$0 \le m \le 10^9$$$) — the number of cities and citizens. The second line of each test case contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_{n}$$$ ($$$0 \le p_i \le m$$$; $$$p_1 + p_2 + \ldots + p_{n} = m$$$), where $$$p_i$$$ is the number of people living in the $$$i$$$-th city. The third line contains $$$n$$$ integers $$$h_1, h_2, \ldots, h_{n}$$$ ($$$-10^9 \le h_i \le 10^9$$$), where $$$h_i$$$ is the calculated happiness index of the $$$i$$$-th city. Next $$$n − 1$$$ lines contain description of the roads, one per line. Each line contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$; $$$x_i \neq y_i$$$), where $$$x_i$$$ and $$$y_i$$$ are cities connected by the $$$i$$$-th road. It's guaranteed that the sum of $$$n$$$ from all test cases doesn't exceed $$$2 \cdot 10^5$$$.
1,800
For each test case, print YES, if the collected data is correct, or NO — otherwise. You can print characters in YES or NO in any case.
standard output