exec_outcome
stringclasses
1 value
code_uid
stringlengths
32
32
file_name
stringclasses
111 values
prob_desc_created_at
stringlengths
10
10
prob_desc_description
stringlengths
63
3.8k
prob_desc_memory_limit
stringclasses
18 values
source_code
stringlengths
117
65.5k
lang_cluster
stringclasses
1 value
prob_desc_sample_inputs
stringlengths
2
802
prob_desc_time_limit
stringclasses
27 values
prob_desc_sample_outputs
stringlengths
2
796
prob_desc_notes
stringlengths
4
3k
lang
stringclasses
5 values
prob_desc_input_from
stringclasses
3 values
tags
listlengths
0
11
src_uid
stringlengths
32
32
prob_desc_input_spec
stringlengths
28
2.37k
difficulty
int64
-1
3.5k
prob_desc_output_spec
stringlengths
17
1.47k
prob_desc_output_to
stringclasses
3 values
hidden_unit_tests
stringclasses
1 value
PASSED
4a648f9a1e12b8cb2d30d1cf3fb72b8a
train_002.jsonl
1533994500
You are looking at the floor plan of the Summer Informatics School's new building. You were tasked with SIS logistics, so you really care about travel time between different locations: it is important to know how long it would take to get from the lecture room to the canteen, or from the gym to the server room.The building consists of n towers, h floors each, where the towers are labeled from 1 to n, the floors are labeled from 1 to h. There is a passage between any two adjacent towers (two towers i and i + 1 for all i: 1 ≤ i ≤ n - 1) on every floor x, where a ≤ x ≤ b. It takes exactly one minute to walk between any two adjacent floors of a tower, as well as between any two adjacent towers, provided that there is a passage on that floor. It is not permitted to leave the building. The picture illustrates the first example. You have given k pairs of locations (ta, fa), (tb, fb): floor fa of tower ta and floor fb of tower tb. For each pair you need to determine the minimum walking time between these locations.
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Problem503A { public static void main(String[] args) { // TODO Auto-generated method stub out=new PrintWriter (new BufferedOutputStream(System.out)); FastReader s=new FastReader (); int n=s.nextInt(); int h=s.nextInt(); int a=s.nextInt(); int b=s.nextInt(); int q=s.nextInt(); while(q>0) { int ta=s.nextInt(); int fa=s.nextInt(); int tb=s.nextInt(); int fb=s.nextInt(); long timetemp=0; if(ta==tb) { timetemp+=Math.abs(fb-fa); out.println(timetemp); q--; continue; } long time=0; if(fa<a || fa>b) { time+=Math.min(Math.abs(fa-a), Math.abs(fa-b)); if(time==Math.abs(fa-a)) { fa=a; }else { fa=b; } } time+=Math.abs(ta-tb); time+=Math.abs(fb-fa); out.println(time); q--; } out.close(); } public static PrintWriter out; public static class FastReader { BufferedReader br; StringTokenizer st; //it reads the data about the specified point and divide the data about it ,it is quite fast //than using direct public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next());//converts string to integer } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (Exception e) { e.printStackTrace(); } return str; } } }
Java
["3 6 2 3 3\n1 2 1 3\n1 4 3 4\n1 2 2 3"]
1 second
["1\n4\n2"]
null
Java 8
standard input
[ "math" ]
bdce4761496c88a3de00aa863ba7308d
The first line of the input contains following integers: n: the number of towers in the building (1 ≤ n ≤ 108), h: the number of floors in each tower (1 ≤ h ≤ 108), a and b: the lowest and highest floor where it's possible to move between adjacent towers (1 ≤ a ≤ b ≤ h), k: total number of queries (1 ≤ k ≤ 104). Next k lines contain description of the queries. Each description consists of four integers ta, fa, tb, fb (1 ≤ ta, tb ≤ n, 1 ≤ fa, fb ≤ h). This corresponds to a query to find the minimum travel time between fa-th floor of the ta-th tower and fb-th floor of the tb-th tower.
1,000
For each query print a single integer: the minimum walking time between the locations in minutes.
standard output
PASSED
1983f014a7b7df332c190a8d51158362
train_002.jsonl
1533994500
You are looking at the floor plan of the Summer Informatics School's new building. You were tasked with SIS logistics, so you really care about travel time between different locations: it is important to know how long it would take to get from the lecture room to the canteen, or from the gym to the server room.The building consists of n towers, h floors each, where the towers are labeled from 1 to n, the floors are labeled from 1 to h. There is a passage between any two adjacent towers (two towers i and i + 1 for all i: 1 ≤ i ≤ n - 1) on every floor x, where a ≤ x ≤ b. It takes exactly one minute to walk between any two adjacent floors of a tower, as well as between any two adjacent towers, provided that there is a passage on that floor. It is not permitted to leave the building. The picture illustrates the first example. You have given k pairs of locations (ta, fa), (tb, fb): floor fa of tower ta and floor fb of tower tb. For each pair you need to determine the minimum walking time between these locations.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class towers { public static void main(String[] args) throws IOException{ InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); String[] s = br.readLine().split(" "); int n = Integer.parseInt(s[0]); int h = Integer.parseInt(s[1]); int a = Integer.parseInt(s[2]); int b = Integer.parseInt(s[3]); int k = Integer.parseInt(s[4]); for(int i = 0; i < k; i++) { s = br.readLine().split(" "); long ans = 0; int ta = Integer.parseInt(s[0]); int fa = Integer.parseInt(s[1]); int tb = Integer.parseInt(s[2]); int fb = Integer.parseInt(s[3]); if(ta == tb) ans = Math.abs(fa-fb); else if(fa >= a && fa <= b) ans = Math.abs(tb-ta) + Math.abs(fb-fa); else if(fa < a) ans = (long)(a-fa) + (long)Math.abs(tb-ta) + (long)Math.abs(a-fb); else ans = (long)(fa-b) + (long)Math.abs(tb-ta) + (long)Math.abs(b-fb); System.out.println(ans); } } } //3 6 2 3 3 //1 2 1 3 //1 4 3 4 //1 2 2 3
Java
["3 6 2 3 3\n1 2 1 3\n1 4 3 4\n1 2 2 3"]
1 second
["1\n4\n2"]
null
Java 8
standard input
[ "math" ]
bdce4761496c88a3de00aa863ba7308d
The first line of the input contains following integers: n: the number of towers in the building (1 ≤ n ≤ 108), h: the number of floors in each tower (1 ≤ h ≤ 108), a and b: the lowest and highest floor where it's possible to move between adjacent towers (1 ≤ a ≤ b ≤ h), k: total number of queries (1 ≤ k ≤ 104). Next k lines contain description of the queries. Each description consists of four integers ta, fa, tb, fb (1 ≤ ta, tb ≤ n, 1 ≤ fa, fb ≤ h). This corresponds to a query to find the minimum travel time between fa-th floor of the ta-th tower and fb-th floor of the tb-th tower.
1,000
For each query print a single integer: the minimum walking time between the locations in minutes.
standard output
PASSED
c1f0e246b7601ab0c387a8ef28b409c6
train_002.jsonl
1533994500
You are looking at the floor plan of the Summer Informatics School's new building. You were tasked with SIS logistics, so you really care about travel time between different locations: it is important to know how long it would take to get from the lecture room to the canteen, or from the gym to the server room.The building consists of n towers, h floors each, where the towers are labeled from 1 to n, the floors are labeled from 1 to h. There is a passage between any two adjacent towers (two towers i and i + 1 for all i: 1 ≤ i ≤ n - 1) on every floor x, where a ≤ x ≤ b. It takes exactly one minute to walk between any two adjacent floors of a tower, as well as between any two adjacent towers, provided that there is a passage on that floor. It is not permitted to leave the building. The picture illustrates the first example. You have given k pairs of locations (ta, fa), (tb, fb): floor fa of tower ta and floor fb of tower tb. For each pair you need to determine the minimum walking time between these locations.
256 megabytes
import java.util.*; import java.io.*; public class C{ public static void main(String[] args) { MyScanner scan = new MyScanner(); PrintWriter pw = new PrintWriter(System.out); int n = scan.nextInt(); int h = scan.nextInt(); int a = scan.nextInt(); int b = scan.nextInt(); int k = scan.nextInt(); while(k-- > 0) { int t1 = scan.nextInt(); int f1 = scan.nextInt(); int t2 = scan.nextInt(); int f2 = scan.nextInt(); if(t1 == t2) { pw.println(Math.abs(f2 - f1)); continue; } long ans = 0; if(f1 <= a) { ans+=(a-f1); ans+=Math.abs(t2 - t1); ans+=Math.abs(f2-a); } else if(f1 >=a && f1 <= b) { ans+=Math.abs(t2 - t1); ans+=Math.abs(f2-f1); } else { ans+=(f1 - b); ans+=Math.abs(t2 - t1); ans+=Math.abs(f2-b); } pw.println(ans); } pw.close(); } } //------------------------------------------------------------------------------------------------------- class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public int mod(long x) { // TODO Auto-generated method stub return (int) x % 1000000007; } public int mod(int x) { return x % 1000000007; } boolean hasNext() { if (st.hasMoreElements()) return true; try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.hasMoreTokens(); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong(){ return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
Java
["3 6 2 3 3\n1 2 1 3\n1 4 3 4\n1 2 2 3"]
1 second
["1\n4\n2"]
null
Java 8
standard input
[ "math" ]
bdce4761496c88a3de00aa863ba7308d
The first line of the input contains following integers: n: the number of towers in the building (1 ≤ n ≤ 108), h: the number of floors in each tower (1 ≤ h ≤ 108), a and b: the lowest and highest floor where it's possible to move between adjacent towers (1 ≤ a ≤ b ≤ h), k: total number of queries (1 ≤ k ≤ 104). Next k lines contain description of the queries. Each description consists of four integers ta, fa, tb, fb (1 ≤ ta, tb ≤ n, 1 ≤ fa, fb ≤ h). This corresponds to a query to find the minimum travel time between fa-th floor of the ta-th tower and fb-th floor of the tb-th tower.
1,000
For each query print a single integer: the minimum walking time between the locations in minutes.
standard output
PASSED
5ce82ae0154104480ac0792082891f84
train_002.jsonl
1533994500
You are looking at the floor plan of the Summer Informatics School's new building. You were tasked with SIS logistics, so you really care about travel time between different locations: it is important to know how long it would take to get from the lecture room to the canteen, or from the gym to the server room.The building consists of n towers, h floors each, where the towers are labeled from 1 to n, the floors are labeled from 1 to h. There is a passage between any two adjacent towers (two towers i and i + 1 for all i: 1 ≤ i ≤ n - 1) on every floor x, where a ≤ x ≤ b. It takes exactly one minute to walk between any two adjacent floors of a tower, as well as between any two adjacent towers, provided that there is a passage on that floor. It is not permitted to leave the building. The picture illustrates the first example. You have given k pairs of locations (ta, fa), (tb, fb): floor fa of tower ta and floor fb of tower tb. For each pair you need to determine the minimum walking time between these locations.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class CF1020A { public static void main(String args[]) throws java.lang.Exception { Scanner in = new Scanner (System.in); int n = in.nextInt(); int h = in.nextInt(); int min = in.nextInt(); int max = in.nextInt(); int k = in.nextInt(); for(int i = 0; i < k; i++){ int cnt = 0; int t1 = in.nextInt(); int f1 = in.nextInt(); int t2 = in.nextInt(); int f2 = in.nextInt(); if(t1 == t2){ System.out.println(Math.abs(f1-f2)); }else{ if(f1 > max){cnt+=Math.abs(f1-max) + Math.abs(max - f2);} else if(f1 < min){cnt+=Math.abs(f1-min) + Math.abs(min - f2);}else{ cnt+=Math.abs(f1 - f2);} cnt = cnt + Math.abs(t1-t2); System.out.println(cnt); } } in.close(); } }
Java
["3 6 2 3 3\n1 2 1 3\n1 4 3 4\n1 2 2 3"]
1 second
["1\n4\n2"]
null
Java 8
standard input
[ "math" ]
bdce4761496c88a3de00aa863ba7308d
The first line of the input contains following integers: n: the number of towers in the building (1 ≤ n ≤ 108), h: the number of floors in each tower (1 ≤ h ≤ 108), a and b: the lowest and highest floor where it's possible to move between adjacent towers (1 ≤ a ≤ b ≤ h), k: total number of queries (1 ≤ k ≤ 104). Next k lines contain description of the queries. Each description consists of four integers ta, fa, tb, fb (1 ≤ ta, tb ≤ n, 1 ≤ fa, fb ≤ h). This corresponds to a query to find the minimum travel time between fa-th floor of the ta-th tower and fb-th floor of the tb-th tower.
1,000
For each query print a single integer: the minimum walking time between the locations in minutes.
standard output
PASSED
c87fb5835b6806c3d4a6fcd186cab4a4
train_002.jsonl
1533994500
You are looking at the floor plan of the Summer Informatics School's new building. You were tasked with SIS logistics, so you really care about travel time between different locations: it is important to know how long it would take to get from the lecture room to the canteen, or from the gym to the server room.The building consists of n towers, h floors each, where the towers are labeled from 1 to n, the floors are labeled from 1 to h. There is a passage between any two adjacent towers (two towers i and i + 1 for all i: 1 ≤ i ≤ n - 1) on every floor x, where a ≤ x ≤ b. It takes exactly one minute to walk between any two adjacent floors of a tower, as well as between any two adjacent towers, provided that there is a passage on that floor. It is not permitted to leave the building. The picture illustrates the first example. You have given k pairs of locations (ta, fa), (tb, fb): floor fa of tower ta and floor fb of tower tb. For each pair you need to determine the minimum walking time between these locations.
256 megabytes
/** * Created by Jack on 11.08.2018. */ import java.util.Scanner; public class A { public static void main(String[] args) { int n , h , a , b , k; Scanner cin = new Scanner(System.in); n = cin.nextInt(); h = cin.nextInt(); a = cin.nextInt(); b = cin.nextInt(); k = cin.nextInt(); int a1 , b1 , a2 , b2; for(int i = 1 ; i <= k;i++) { a1 = cin.nextInt(); b1 = cin.nextInt(); a2 = cin.nextInt(); b2 = cin.nextInt(); if(a1 == a2) { //right System.out.println((Math.abs(b1 - b2))); continue; } if(b1 <= a) { long ans = 0; if(b1 >= a && b1 <= b) { ans += Math.abs(a1 - a2); ans += Math.abs(b1 - b2); System.out.println(ans); continue; } long ans1 = a - b1; ans1 += Math.abs(a1 - a2); ans1 += Math.abs(a - b2); System.out.println(ans1); continue; } if(b1 >= b) { long ans = 0; if(b1 >= a && b1 <= b) { ans += Math.abs(a1 - a2); ans += Math.abs(b1 - b2); System.out.println(ans); continue; } long ans1 = b1 - b; ans1 += Math.abs(a1 - a2); ans1 += Math.abs(b - b2); System.out.println(ans1); continue; } if(b1 >= a && b1 <= b) { long ans = Math.abs(a1 - a2); ans += Math.abs(b1 - b2); System.out.println(ans); continue; } } } }
Java
["3 6 2 3 3\n1 2 1 3\n1 4 3 4\n1 2 2 3"]
1 second
["1\n4\n2"]
null
Java 8
standard input
[ "math" ]
bdce4761496c88a3de00aa863ba7308d
The first line of the input contains following integers: n: the number of towers in the building (1 ≤ n ≤ 108), h: the number of floors in each tower (1 ≤ h ≤ 108), a and b: the lowest and highest floor where it's possible to move between adjacent towers (1 ≤ a ≤ b ≤ h), k: total number of queries (1 ≤ k ≤ 104). Next k lines contain description of the queries. Each description consists of four integers ta, fa, tb, fb (1 ≤ ta, tb ≤ n, 1 ≤ fa, fb ≤ h). This corresponds to a query to find the minimum travel time between fa-th floor of the ta-th tower and fb-th floor of the tb-th tower.
1,000
For each query print a single integer: the minimum walking time between the locations in minutes.
standard output
PASSED
c7131755b77de6695ac953024a79ebbf
train_002.jsonl
1533994500
You are looking at the floor plan of the Summer Informatics School's new building. You were tasked with SIS logistics, so you really care about travel time between different locations: it is important to know how long it would take to get from the lecture room to the canteen, or from the gym to the server room.The building consists of n towers, h floors each, where the towers are labeled from 1 to n, the floors are labeled from 1 to h. There is a passage between any two adjacent towers (two towers i and i + 1 for all i: 1 ≤ i ≤ n - 1) on every floor x, where a ≤ x ≤ b. It takes exactly one minute to walk between any two adjacent floors of a tower, as well as between any two adjacent towers, provided that there is a passage on that floor. It is not permitted to leave the building. The picture illustrates the first example. You have given k pairs of locations (ta, fa), (tb, fb): floor fa of tower ta and floor fb of tower tb. For each pair you need to determine the minimum walking time between these locations.
256 megabytes
import java.util.*; public class building { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int n=sc.nextInt(); int h=sc.nextInt(); int a=sc.nextInt(); int b=sc.nextInt(); int q=sc.nextInt(); for(int i=0;i<q;i++){ int ans=0; int t1=sc.nextInt(); int f1=sc.nextInt(); int t2=sc.nextInt(); int f2=sc.nextInt(); if(t1==t2){ ans+=Math.abs(f1-f2); } else if(f1>=a&&f1<=b){ ans+=Math.abs(t2-t1); ans+=Math.abs(f2-f1); } else if(f1<a){ ans+=a-f1; ans+=Math.abs(t2-t1); ans+=Math.abs(f2-a); } else if(f1>b){ ans+=f1-b; ans+=Math.abs(t2-t1); ans+=Math.abs(b-f2); } System.out.println(ans); } } }
Java
["3 6 2 3 3\n1 2 1 3\n1 4 3 4\n1 2 2 3"]
1 second
["1\n4\n2"]
null
Java 8
standard input
[ "math" ]
bdce4761496c88a3de00aa863ba7308d
The first line of the input contains following integers: n: the number of towers in the building (1 ≤ n ≤ 108), h: the number of floors in each tower (1 ≤ h ≤ 108), a and b: the lowest and highest floor where it's possible to move between adjacent towers (1 ≤ a ≤ b ≤ h), k: total number of queries (1 ≤ k ≤ 104). Next k lines contain description of the queries. Each description consists of four integers ta, fa, tb, fb (1 ≤ ta, tb ≤ n, 1 ≤ fa, fb ≤ h). This corresponds to a query to find the minimum travel time between fa-th floor of the ta-th tower and fb-th floor of the tb-th tower.
1,000
For each query print a single integer: the minimum walking time between the locations in minutes.
standard output
PASSED
33fdf1e963d345fec8009de501e90832
train_002.jsonl
1533994500
You are looking at the floor plan of the Summer Informatics School's new building. You were tasked with SIS logistics, so you really care about travel time between different locations: it is important to know how long it would take to get from the lecture room to the canteen, or from the gym to the server room.The building consists of n towers, h floors each, where the towers are labeled from 1 to n, the floors are labeled from 1 to h. There is a passage between any two adjacent towers (two towers i and i + 1 for all i: 1 ≤ i ≤ n - 1) on every floor x, where a ≤ x ≤ b. It takes exactly one minute to walk between any two adjacent floors of a tower, as well as between any two adjacent towers, provided that there is a passage on that floor. It is not permitted to leave the building. The picture illustrates the first example. You have given k pairs of locations (ta, fa), (tb, fb): floor fa of tower ta and floor fb of tower tb. For each pair you need to determine the minimum walking time between these locations.
256 megabytes
import java.util.Arrays; import java.util.TreeMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Scanner; import java.util.Set; public class practice1 { public static void main (String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int h=sc.nextInt(); int a=sc.nextInt(); int b=sc.nextInt(); int k=sc.nextInt(); int[] sum=new int[k]; for(int i=0;i<k;i++) { int ta=sc.nextInt(); int fa=sc.nextInt(); int tb=sc.nextInt(); int fb=sc.nextInt(); int x=0; int y=0; if(fa>=a&&fa<=b) { x=0; y=Math.abs(fa-fb); } else if(fb>=a&&fb<=b) { y=0; x=Math.abs(fa-fb); } else if(fa>b) { x=Math.abs(fa-b); y=Math.abs(fb-b); } else if(fa<a) { x=Math.abs(fa-a); y=Math.abs(fb-a); } if(ta==tb) { sum[i]=Math.abs(fa-fb); } else { sum[i]=Math.abs(tb-ta)+x+y; } } for(int i=0;i<k;i++) { System.out.println(sum[i]); } } }
Java
["3 6 2 3 3\n1 2 1 3\n1 4 3 4\n1 2 2 3"]
1 second
["1\n4\n2"]
null
Java 8
standard input
[ "math" ]
bdce4761496c88a3de00aa863ba7308d
The first line of the input contains following integers: n: the number of towers in the building (1 ≤ n ≤ 108), h: the number of floors in each tower (1 ≤ h ≤ 108), a and b: the lowest and highest floor where it's possible to move between adjacent towers (1 ≤ a ≤ b ≤ h), k: total number of queries (1 ≤ k ≤ 104). Next k lines contain description of the queries. Each description consists of four integers ta, fa, tb, fb (1 ≤ ta, tb ≤ n, 1 ≤ fa, fb ≤ h). This corresponds to a query to find the minimum travel time between fa-th floor of the ta-th tower and fb-th floor of the tb-th tower.
1,000
For each query print a single integer: the minimum walking time between the locations in minutes.
standard output
PASSED
1f118cbf91033e85c75fe59043ebce04
train_002.jsonl
1533994500
You are looking at the floor plan of the Summer Informatics School's new building. You were tasked with SIS logistics, so you really care about travel time between different locations: it is important to know how long it would take to get from the lecture room to the canteen, or from the gym to the server room.The building consists of n towers, h floors each, where the towers are labeled from 1 to n, the floors are labeled from 1 to h. There is a passage between any two adjacent towers (two towers i and i + 1 for all i: 1 ≤ i ≤ n - 1) on every floor x, where a ≤ x ≤ b. It takes exactly one minute to walk between any two adjacent floors of a tower, as well as between any two adjacent towers, provided that there is a passage on that floor. It is not permitted to leave the building. The picture illustrates the first example. You have given k pairs of locations (ta, fa), (tb, fb): floor fa of tower ta and floor fb of tower tb. For each pair you need to determine the minimum walking time between these locations.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class TestClass { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s = br.readLine(); String[] sa = s.split(" "); long n = Long.parseLong(sa[0]); long h = Long.parseLong(sa[1]); long a = Long.parseLong(sa[2]); long b = Long.parseLong(sa[3]); int k = Integer.parseInt(sa[4]); for(int i = 0 ; i < k; i++){ String ip = br.readLine(); String[] ipa = ip.split(" "); long ta = Long.parseLong(ipa[0]); long fa = Long.parseLong(ipa[1]); long tb = Long.parseLong(ipa[2]); long fb = Long.parseLong(ipa[3]); solve(n, h, a, b, ta, fa, tb, fb); } } private static void solve(long n, long h, long a, long b, long ta, long fa, long tb, long fb) { if(ta == tb){ System.out.println((fa - fb >= 0) ? (fa - fb) : (fb - fa)); return; } long tamin = 0; long tbmin = 0; if(fa > b){ tamin = (fa - b); tbmin = (fb - b) >= 0 ? (fb - b) : (b - fb); } else if(fa <= b && fa >= a) { tamin = 0; tbmin = (fb - fa) >= 0 ? (fb - fa) : (fa - fb); } else { tamin = (a - fa); tbmin = (fb - a) >= 0 ? (fb - a) : (a - fb); } long tgap = (ta - tb) > 0 ? (ta - tb) : (tb - ta); System.out.println(tgap + tamin + tbmin); } }
Java
["3 6 2 3 3\n1 2 1 3\n1 4 3 4\n1 2 2 3"]
1 second
["1\n4\n2"]
null
Java 8
standard input
[ "math" ]
bdce4761496c88a3de00aa863ba7308d
The first line of the input contains following integers: n: the number of towers in the building (1 ≤ n ≤ 108), h: the number of floors in each tower (1 ≤ h ≤ 108), a and b: the lowest and highest floor where it's possible to move between adjacent towers (1 ≤ a ≤ b ≤ h), k: total number of queries (1 ≤ k ≤ 104). Next k lines contain description of the queries. Each description consists of four integers ta, fa, tb, fb (1 ≤ ta, tb ≤ n, 1 ≤ fa, fb ≤ h). This corresponds to a query to find the minimum travel time between fa-th floor of the ta-th tower and fb-th floor of the tb-th tower.
1,000
For each query print a single integer: the minimum walking time between the locations in minutes.
standard output
PASSED
234d49c2832138999a450c2c7b1b7f6d
train_002.jsonl
1533994500
You are looking at the floor plan of the Summer Informatics School's new building. You were tasked with SIS logistics, so you really care about travel time between different locations: it is important to know how long it would take to get from the lecture room to the canteen, or from the gym to the server room.The building consists of n towers, h floors each, where the towers are labeled from 1 to n, the floors are labeled from 1 to h. There is a passage between any two adjacent towers (two towers i and i + 1 for all i: 1 ≤ i ≤ n - 1) on every floor x, where a ≤ x ≤ b. It takes exactly one minute to walk between any two adjacent floors of a tower, as well as between any two adjacent towers, provided that there is a passage on that floor. It is not permitted to leave the building. The picture illustrates the first example. You have given k pairs of locations (ta, fa), (tb, fb): floor fa of tower ta and floor fb of tower tb. For each pair you need to determine the minimum walking time between these locations.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.FilterInputStream; import java.io.BufferedInputStream; import java.io.InputStream; /** * @author khokharnikunj8 */ public class Main { public static void main(String[] args) { new Thread(null, new Runnable() { public void run() { new Main().solve(); } }, "1", 1 << 26).start(); } void solve() { InputStream inputStream = System.in; OutputStream outputStream = System.out; ScanReader in = new ScanReader(inputStream); PrintWriter out = new PrintWriter(outputStream); ANewBuildingForSIS solver = new ANewBuildingForSIS(); solver.solve(1, in, out); out.close(); } static class ANewBuildingForSIS { public void solve(int testNumber, ScanReader in, PrintWriter out) { int n = in.scanInt(); int h = in.scanInt(); int a = in.scanInt(); int b = in.scanInt(); int k = in.scanInt(); while (k-- > 0) { int ta = in.scanInt(); int fa = in.scanInt(); int tb = in.scanInt(); int fb = in.scanInt(); if ((a <= fa && fa <= b) || (a <= fb && fb <= b)) out.println(Math.abs(tb - ta) + Math.abs(fb - fa)); else { if (ta == tb) { out.println(Math.abs(fa - fb)); } else { if (fa < a) { out.println(Math.abs(tb - ta) + Math.abs(fa - a) + Math.abs(fb - a)); } else { out.println(Math.abs(tb - ta) + Math.abs(fb - b) + Math.abs(fa - b)); } } } } } } static class ScanReader { private byte[] buf = new byte[4 * 1024]; private int index; private BufferedInputStream in; private int total; public ScanReader(InputStream inputStream) { in = new BufferedInputStream(inputStream); } private int scan() { if (index >= total) { index = 0; try { total = in.read(buf); } catch (Exception e) { e.printStackTrace(); } if (total <= 0) return -1; } return buf[index++]; } public int scanInt() { int integer = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { integer *= 10; integer += n - '0'; n = scan(); } } return neg * integer; } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; else return false; } } }
Java
["3 6 2 3 3\n1 2 1 3\n1 4 3 4\n1 2 2 3"]
1 second
["1\n4\n2"]
null
Java 8
standard input
[ "math" ]
bdce4761496c88a3de00aa863ba7308d
The first line of the input contains following integers: n: the number of towers in the building (1 ≤ n ≤ 108), h: the number of floors in each tower (1 ≤ h ≤ 108), a and b: the lowest and highest floor where it's possible to move between adjacent towers (1 ≤ a ≤ b ≤ h), k: total number of queries (1 ≤ k ≤ 104). Next k lines contain description of the queries. Each description consists of four integers ta, fa, tb, fb (1 ≤ ta, tb ≤ n, 1 ≤ fa, fb ≤ h). This corresponds to a query to find the minimum travel time between fa-th floor of the ta-th tower and fb-th floor of the tb-th tower.
1,000
For each query print a single integer: the minimum walking time between the locations in minutes.
standard output
PASSED
fe9bc68dfb849cbc958ce8fcedf4dd6a
train_002.jsonl
1533994500
You are looking at the floor plan of the Summer Informatics School's new building. You were tasked with SIS logistics, so you really care about travel time between different locations: it is important to know how long it would take to get from the lecture room to the canteen, or from the gym to the server room.The building consists of n towers, h floors each, where the towers are labeled from 1 to n, the floors are labeled from 1 to h. There is a passage between any two adjacent towers (two towers i and i + 1 for all i: 1 ≤ i ≤ n - 1) on every floor x, where a ≤ x ≤ b. It takes exactly one minute to walk between any two adjacent floors of a tower, as well as between any two adjacent towers, provided that there is a passage on that floor. It is not permitted to leave the building. The picture illustrates the first example. You have given k pairs of locations (ta, fa), (tb, fb): floor fa of tower ta and floor fb of tower tb. For each pair you need to determine the minimum walking time between these locations.
256 megabytes
import java.util.*; import java.io.*; import java.lang.*; public class Sol{ public static void main(String[] args) { FastScanner fi=new FastScanner(); int n,h,a,b,k; n=fi.nextInt(); h=fi.nextInt(); a=fi.nextInt(); b=fi.nextInt(); k=fi.nextInt(); while(k-- > 0){ int ta=fi.nextInt(); int fa=fi.nextInt(); int tb=fi.nextInt(); int fb=fi.nextInt(); int ans=0; if(ta!=tb){ if(fa > b){ ans=ans+fa-b; fa=b; } else if(fa < a){ ans+=a-fa; fa=a; } } ans+=Math.abs(ta-tb); ans+=Math.abs(fa-fb); System.out.println(ans); } } } class FastScanner{ BufferedReader br; StringTokenizer st; FastScanner (){ br=new BufferedReader(new InputStreamReader(System.in)); } public String next(){ while(st==null || !st.hasMoreTokens()){ try{ st=new StringTokenizer(br.readLine()); } catch(IOException e){ e.printStackTrace(); } } return st.nextToken(); } public int nextInt(){ return Integer.parseInt(next()); } public long nextLong(){ return Long.parseLong(next()); } }
Java
["3 6 2 3 3\n1 2 1 3\n1 4 3 4\n1 2 2 3"]
1 second
["1\n4\n2"]
null
Java 8
standard input
[ "math" ]
bdce4761496c88a3de00aa863ba7308d
The first line of the input contains following integers: n: the number of towers in the building (1 ≤ n ≤ 108), h: the number of floors in each tower (1 ≤ h ≤ 108), a and b: the lowest and highest floor where it's possible to move between adjacent towers (1 ≤ a ≤ b ≤ h), k: total number of queries (1 ≤ k ≤ 104). Next k lines contain description of the queries. Each description consists of four integers ta, fa, tb, fb (1 ≤ ta, tb ≤ n, 1 ≤ fa, fb ≤ h). This corresponds to a query to find the minimum travel time between fa-th floor of the ta-th tower and fb-th floor of the tb-th tower.
1,000
For each query print a single integer: the minimum walking time between the locations in minutes.
standard output
PASSED
dde53aba89d36326a23dbda9c833956e
train_002.jsonl
1533994500
You are looking at the floor plan of the Summer Informatics School's new building. You were tasked with SIS logistics, so you really care about travel time between different locations: it is important to know how long it would take to get from the lecture room to the canteen, or from the gym to the server room.The building consists of n towers, h floors each, where the towers are labeled from 1 to n, the floors are labeled from 1 to h. There is a passage between any two adjacent towers (two towers i and i + 1 for all i: 1 ≤ i ≤ n - 1) on every floor x, where a ≤ x ≤ b. It takes exactly one minute to walk between any two adjacent floors of a tower, as well as between any two adjacent towers, provided that there is a passage on that floor. It is not permitted to leave the building. The picture illustrates the first example. You have given k pairs of locations (ta, fa), (tb, fb): floor fa of tower ta and floor fb of tower tb. For each pair you need to determine the minimum walking time between these locations.
256 megabytes
import java.util.Scanner; public class ProblemA { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int h = scan.nextInt(); long a = scan.nextLong(); long b = scan.nextLong(); int k = scan.nextInt(); long ta, fa, tb, fb; long ans[] = new long[k]; for(int i = 0; i < k; i++) { ta = scan.nextInt(); fa = scan.nextInt(); tb = scan.nextInt(); fb = scan.nextInt(); if(ta == tb) { ans[i] = Math.abs(fa - fb); }else { if(a <= fa && fa <= b) { ans[i] = Math.abs(ta - tb) + Math.abs(fa - fb); }else { if(Math.abs(fa - a) < Math.abs(fa - b)) { ans[i] = Math.abs(ta - tb) + Math.abs(fa - a) + Math.abs(fb - a); }else { ans[i] = Math.abs(ta - tb) + Math.abs(fa - b) + Math.abs(fb - b); } } } } scan.close(); for(int i = 0; i < k; i++) { System.out.println(ans[i]); } } }
Java
["3 6 2 3 3\n1 2 1 3\n1 4 3 4\n1 2 2 3"]
1 second
["1\n4\n2"]
null
Java 8
standard input
[ "math" ]
bdce4761496c88a3de00aa863ba7308d
The first line of the input contains following integers: n: the number of towers in the building (1 ≤ n ≤ 108), h: the number of floors in each tower (1 ≤ h ≤ 108), a and b: the lowest and highest floor where it's possible to move between adjacent towers (1 ≤ a ≤ b ≤ h), k: total number of queries (1 ≤ k ≤ 104). Next k lines contain description of the queries. Each description consists of four integers ta, fa, tb, fb (1 ≤ ta, tb ≤ n, 1 ≤ fa, fb ≤ h). This corresponds to a query to find the minimum travel time between fa-th floor of the ta-th tower and fb-th floor of the tb-th tower.
1,000
For each query print a single integer: the minimum walking time between the locations in minutes.
standard output
PASSED
17316bffdc1f509bd96ad245a0973d26
train_002.jsonl
1533994500
You are looking at the floor plan of the Summer Informatics School's new building. You were tasked with SIS logistics, so you really care about travel time between different locations: it is important to know how long it would take to get from the lecture room to the canteen, or from the gym to the server room.The building consists of n towers, h floors each, where the towers are labeled from 1 to n, the floors are labeled from 1 to h. There is a passage between any two adjacent towers (two towers i and i + 1 for all i: 1 ≤ i ≤ n - 1) on every floor x, where a ≤ x ≤ b. It takes exactly one minute to walk between any two adjacent floors of a tower, as well as between any two adjacent towers, provided that there is a passage on that floor. It is not permitted to leave the building. The picture illustrates the first example. You have given k pairs of locations (ta, fa), (tb, fb): floor fa of tower ta and floor fb of tower tb. For each pair you need to determine the minimum walking time between these locations.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; public class A_NewBuildingForSIS { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] inputLine = br.readLine().split(" "); int towers = Integer.valueOf(inputLine[0]); int floors = Integer.valueOf(inputLine[1]); int lowestTowerMove = Integer.valueOf(inputLine[2]); int highestTowerMove = Integer.valueOf(inputLine[3]); int queries = Integer.valueOf(inputLine[4]); for (int i = 0; i < queries; i++) { int sum = 0, sum2 = 0; String[] input_line = br.readLine().split(" "); int Ta = Integer.valueOf(input_line[0]); int Fa = Integer.valueOf(input_line[1]); int Tb = Integer.valueOf(input_line[2]); int Fb = Integer.valueOf(input_line[3]); sum += Math.abs(Ta - Tb); sum2 += Math.abs(Ta - Tb); if (Math.abs(Ta - Tb) != 0) { if(Fb <= highestTowerMove && Fb >= lowestTowerMove){ sum += Math.abs(Fa - Fb); sum2 += Math.abs(Fa - Fb); } else{ sum += Math.abs(highestTowerMove - Fa); sum2 += Math.abs(lowestTowerMove - Fa); sum += Math.abs(highestTowerMove - Fb); sum2 += Math.abs(lowestTowerMove - Fb); } } else { sum = Math.abs(Fa - Fb); sum2 = Math.abs(Fa - Fb); } System.out.println(Math.min(sum, sum2)); } } }
Java
["3 6 2 3 3\n1 2 1 3\n1 4 3 4\n1 2 2 3"]
1 second
["1\n4\n2"]
null
Java 8
standard input
[ "math" ]
bdce4761496c88a3de00aa863ba7308d
The first line of the input contains following integers: n: the number of towers in the building (1 ≤ n ≤ 108), h: the number of floors in each tower (1 ≤ h ≤ 108), a and b: the lowest and highest floor where it's possible to move between adjacent towers (1 ≤ a ≤ b ≤ h), k: total number of queries (1 ≤ k ≤ 104). Next k lines contain description of the queries. Each description consists of four integers ta, fa, tb, fb (1 ≤ ta, tb ≤ n, 1 ≤ fa, fb ≤ h). This corresponds to a query to find the minimum travel time between fa-th floor of the ta-th tower and fb-th floor of the tb-th tower.
1,000
For each query print a single integer: the minimum walking time between the locations in minutes.
standard output
PASSED
506c92b7d32dba00b0b5d3c34e09ca07
train_002.jsonl
1533994500
You are looking at the floor plan of the Summer Informatics School's new building. You were tasked with SIS logistics, so you really care about travel time between different locations: it is important to know how long it would take to get from the lecture room to the canteen, or from the gym to the server room.The building consists of n towers, h floors each, where the towers are labeled from 1 to n, the floors are labeled from 1 to h. There is a passage between any two adjacent towers (two towers i and i + 1 for all i: 1 ≤ i ≤ n - 1) on every floor x, where a ≤ x ≤ b. It takes exactly one minute to walk between any two adjacent floors of a tower, as well as between any two adjacent towers, provided that there is a passage on that floor. It is not permitted to leave the building. The picture illustrates the first example. You have given k pairs of locations (ta, fa), (tb, fb): floor fa of tower ta and floor fb of tower tb. For each pair you need to determine the minimum walking time between these locations.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.*; import java.util.*; import java.util.Map.Entry; public class Main { public static void main(String[] args) throws IOException { FastReader in = new FastReader(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int h = in.nextInt(); int min = in.nextInt(); int max = in.nextInt(); int k = in.nextInt(); for (int i = 0; i < k; i++) { int t1 = in.nextInt(); int f1 = in.nextInt(); int t2 = in.nextInt(); int f2 = in.nextInt(); int ans = 0; if (t1 == t2) { ans += Math.abs(f1 - f2); } else { if (f1 >= min && f1 <= max) { ans += Math.abs(f2 - f1); ans += Math.abs(t2 - t1); } else if (f1 < min) { ans += min - f1; ans += Math.abs(t2 - t1); ans += Math.abs(f2 - min); } else if (f1 > max) { ans += f1 - max; ans += Math.abs(t2 - t1); ans += Math.abs(max - f2); } } out.println(ans); } out.flush(); out.close(); } static class FastReader { StringTokenizer st; BufferedReader br; public FastReader(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public FastReader(FileReader fileReader) { br = new BufferedReader(fileReader); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["3 6 2 3 3\n1 2 1 3\n1 4 3 4\n1 2 2 3"]
1 second
["1\n4\n2"]
null
Java 8
standard input
[ "math" ]
bdce4761496c88a3de00aa863ba7308d
The first line of the input contains following integers: n: the number of towers in the building (1 ≤ n ≤ 108), h: the number of floors in each tower (1 ≤ h ≤ 108), a and b: the lowest and highest floor where it's possible to move between adjacent towers (1 ≤ a ≤ b ≤ h), k: total number of queries (1 ≤ k ≤ 104). Next k lines contain description of the queries. Each description consists of four integers ta, fa, tb, fb (1 ≤ ta, tb ≤ n, 1 ≤ fa, fb ≤ h). This corresponds to a query to find the minimum travel time between fa-th floor of the ta-th tower and fb-th floor of the tb-th tower.
1,000
For each query print a single integer: the minimum walking time between the locations in minutes.
standard output
PASSED
c50e10b1bf5fc303fb8004010a271341
train_002.jsonl
1533994500
You are looking at the floor plan of the Summer Informatics School's new building. You were tasked with SIS logistics, so you really care about travel time between different locations: it is important to know how long it would take to get from the lecture room to the canteen, or from the gym to the server room.The building consists of n towers, h floors each, where the towers are labeled from 1 to n, the floors are labeled from 1 to h. There is a passage between any two adjacent towers (two towers i and i + 1 for all i: 1 ≤ i ≤ n - 1) on every floor x, where a ≤ x ≤ b. It takes exactly one minute to walk between any two adjacent floors of a tower, as well as between any two adjacent towers, provided that there is a passage on that floor. It is not permitted to leave the building. The picture illustrates the first example. You have given k pairs of locations (ta, fa), (tb, fb): floor fa of tower ta and floor fb of tower tb. For each pair you need to determine the minimum walking time between these locations.
256 megabytes
import java.util.Scanner; public class A1020 { public static void main(String[] args) { Scanner s = new Scanner(System.in); long n = s.nextLong(); long h = s.nextLong(); long a = s.nextLong(); long b = s.nextLong(); long k = s.nextLong(); for (int i = 0; i < k; i++) { long x = s.nextLong(); long y = s.nextLong(); long o = s.nextLong(); long p = s.nextLong(); long offset = 0; if (x == o) { offset = Math.abs(p - y); } else if (y < a) { offset = a - y; offset += Math.abs(p - a); } else if (y > b) { offset = y - b; offset += Math.abs(p - b); } else { offset = Math.abs(p - y); } long ans = Math.abs(x - o) + offset; System.out.println(ans); } s.close(); } }
Java
["3 6 2 3 3\n1 2 1 3\n1 4 3 4\n1 2 2 3"]
1 second
["1\n4\n2"]
null
Java 8
standard input
[ "math" ]
bdce4761496c88a3de00aa863ba7308d
The first line of the input contains following integers: n: the number of towers in the building (1 ≤ n ≤ 108), h: the number of floors in each tower (1 ≤ h ≤ 108), a and b: the lowest and highest floor where it's possible to move between adjacent towers (1 ≤ a ≤ b ≤ h), k: total number of queries (1 ≤ k ≤ 104). Next k lines contain description of the queries. Each description consists of four integers ta, fa, tb, fb (1 ≤ ta, tb ≤ n, 1 ≤ fa, fb ≤ h). This corresponds to a query to find the minimum travel time between fa-th floor of the ta-th tower and fb-th floor of the tb-th tower.
1,000
For each query print a single integer: the minimum walking time between the locations in minutes.
standard output
PASSED
591880957abe85852499ba68dec739fa
train_002.jsonl
1533994500
You are looking at the floor plan of the Summer Informatics School's new building. You were tasked with SIS logistics, so you really care about travel time between different locations: it is important to know how long it would take to get from the lecture room to the canteen, or from the gym to the server room.The building consists of n towers, h floors each, where the towers are labeled from 1 to n, the floors are labeled from 1 to h. There is a passage between any two adjacent towers (two towers i and i + 1 for all i: 1 ≤ i ≤ n - 1) on every floor x, where a ≤ x ≤ b. It takes exactly one minute to walk between any two adjacent floors of a tower, as well as between any two adjacent towers, provided that there is a passage on that floor. It is not permitted to leave the building. The picture illustrates the first example. You have given k pairs of locations (ta, fa), (tb, fb): floor fa of tower ta and floor fb of tower tb. For each pair you need to determine the minimum walking time between these locations.
256 megabytes
import java.util.Scanner; public class NewBuilding { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int h = in.nextInt(); int a = in.nextInt(); int b = in.nextInt(); int k = in.nextInt(); long[] result = new long[k]; for (int i = 0; i < k; i++) { int x0 = in.nextInt(); int y0 = in.nextInt(); int x1 = in.nextInt(); int y1 = in.nextInt(); boolean y1Inbetween = y1 <= b && y1 >= a; boolean y0Inbetween = y0 <= b && y0 >= a; long deltaX = Math.abs(x1 - x0); int delta = 0; if (!y0Inbetween && x0 != x1) { if (y1Inbetween) { delta = Math.abs(y0 - y1); } else if (y1 > b) { delta = Math.abs(y0 - b) + (y1 - b); } else if (y1 < a) { delta = Math.abs(y0 - a) + (a - y1); } } else { delta = Math.abs(y1 - y0); } result[i] = deltaX + delta; } for (int i = 0; i < k; i++) { System.out.println(result[i]); } } }
Java
["3 6 2 3 3\n1 2 1 3\n1 4 3 4\n1 2 2 3"]
1 second
["1\n4\n2"]
null
Java 8
standard input
[ "math" ]
bdce4761496c88a3de00aa863ba7308d
The first line of the input contains following integers: n: the number of towers in the building (1 ≤ n ≤ 108), h: the number of floors in each tower (1 ≤ h ≤ 108), a and b: the lowest and highest floor where it's possible to move between adjacent towers (1 ≤ a ≤ b ≤ h), k: total number of queries (1 ≤ k ≤ 104). Next k lines contain description of the queries. Each description consists of four integers ta, fa, tb, fb (1 ≤ ta, tb ≤ n, 1 ≤ fa, fb ≤ h). This corresponds to a query to find the minimum travel time between fa-th floor of the ta-th tower and fb-th floor of the tb-th tower.
1,000
For each query print a single integer: the minimum walking time between the locations in minutes.
standard output
PASSED
d9bd6e4cebe0e16bc3e52c274f860fda
train_002.jsonl
1380295800
One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other n - 1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want?
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Random; import java.util.StringTokenizer; public class Solution { public static void main(String[] args) { try (PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out))) { _Scanner sc = new _Scanner(System.in); int n = sc.nextInt(); int max = 0; long sum = 0; for (int i = 0; i < n; i++) { int v = sc.nextInt(); max = Math.max(max, v); sum += v; } out.println(Math.max(max, (sum + n - 2) / (n - 1))); } } static class _Scanner { InputStream is; _Scanner(InputStream is) { this.is = is; } byte[] bb = new byte[1 << 15]; int k, l; byte getc() { try { if (k >= l) { k = 0; l = is.read(bb); if (l < 0) return -1; } return bb[k++]; } catch (IOException e) { throw new RuntimeException(e); } } byte skip() { byte b; while ((b = getc()) <= 32) ; return b; } int nextInt() { int n = 0; int sig = 1; for (byte b = skip(); b > 32; b = getc()) { if (b == '-') { sig = -1; } else { n = n * 10 + b - '0'; } } return sig * n; } long nextLong() { long n = 0; long sig = 1; for (byte b = skip(); b > 32; b = getc()) { if (b == '-') { sig = -1; } else { n = n * 10 + b - '0'; } } return sig * n; } public String next() { StringBuilder sb = new StringBuilder(); for (int b = skip(); b > 32; b = getc()) { sb.append(((char) b)); } return sb.toString(); } } private static void shuffle(int[] ar) { Random rnd = new Random(); for (int i = 0; i < ar.length; i++) { int j = i + rnd.nextInt(ar.length - i); swap(ar, i, j); } } private static void shuffle(Object[] ar) { Random rnd = new Random(); for (int i = 0; i < ar.length; i++) { int j = i + rnd.nextInt(ar.length - i); swap(ar, i, j); } } private static void swap(int[] ar, int i, int j) { int t = ar[i]; ar[i] = ar[j]; ar[j] = t; } private static void swap(Object[] ar, int i, int j) { Object t = ar[i]; ar[i] = ar[j]; ar[j] = t; } private static class MyScanner { private final BufferedReader reader; private StringTokenizer tokenizer; public MyScanner(BufferedReader reader) { this.reader = reader; } public int nextInt() { reload(); if (tokenizer.hasMoreTokens()) { return Integer.parseInt(tokenizer.nextToken()); } throw new RuntimeException("eof"); } private void reload() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(readline()); } } private String readline() { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } public String next() { reload(); return tokenizer.nextToken(); } } }
Java
["3\n3 2 2", "4\n2 2 2 2"]
2 seconds
["4", "3"]
NoteYou don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game).
Java 11
standard input
[ "binary search", "sortings", "math" ]
09f5623c3717c9d360334500b198d8e0
The first line contains integer n (3 ≤ n ≤ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the i-th number in the list is the number of rounds the i-th person wants to play.
1,600
In a single line print a single integer — the minimum number of game rounds the friends need to let the i-th person play at least ai rounds. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
854245ce03afd45df013af65072808ce
train_002.jsonl
1380295800
One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other n - 1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want?
256 megabytes
import java.util.*; public class Mafia { static Scanner in = new Scanner(System.in); public static void main(String[] args) { int n = in.nextInt(); int ans = 0; double k = 0; for(int i = 0; i < n; i++) { int v = in.nextInt(); ans = Math.max(ans, v); k += v; } System.out.println((int)Math.max(ans, ((k+n-2)/(n-1)))); } }
Java
["3\n3 2 2", "4\n2 2 2 2"]
2 seconds
["4", "3"]
NoteYou don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game).
Java 11
standard input
[ "binary search", "sortings", "math" ]
09f5623c3717c9d360334500b198d8e0
The first line contains integer n (3 ≤ n ≤ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the i-th number in the list is the number of rounds the i-th person wants to play.
1,600
In a single line print a single integer — the minimum number of game rounds the friends need to let the i-th person play at least ai rounds. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
0231e9fab12194d433e94ecf930e55d1
train_002.jsonl
1380295800
One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other n - 1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want?
256 megabytes
import java.util.*; public class Solution { public static void main(String []args) { Scanner sc = new Scanner(System.in); long n = sc.nextLong(); long sum = 0; long max = 0; for(int i = 0 ; i < n ; i++) { long term = sc.nextLong(); sum = sum + term; if(term > max) max = term; } long test = 0; if(sum % (n - 1) == 0) test = (sum/(n - 1)); else test = (sum/(n - 1) + 1); if(test >= max) System.out.println(test); else System.out.println(max); } }
Java
["3\n3 2 2", "4\n2 2 2 2"]
2 seconds
["4", "3"]
NoteYou don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game).
Java 11
standard input
[ "binary search", "sortings", "math" ]
09f5623c3717c9d360334500b198d8e0
The first line contains integer n (3 ≤ n ≤ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the i-th number in the list is the number of rounds the i-th person wants to play.
1,600
In a single line print a single integer — the minimum number of game rounds the friends need to let the i-th person play at least ai rounds. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
7f78daaa3e3b78dc89c9d3a22129bd23
train_002.jsonl
1380295800
One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other n - 1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want?
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.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author unknown */ 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); AMafia solver = new AMafia(); solver.solve(1, in, out); out.close(); } static class AMafia { int IINF = (int) 1e9 + 331; public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); long sum = 0; int max = -IINF; for (int i = 0; i < n; i++) { int x = in.nextInt(); sum += x; max = _F.max(max, x); } out.println(getRounds(sum, n, max)); } long getRounds(long sum, int n, int max) { long l = max; long r = (long) (1e12 + 10); while (l <= r) { long mid = l + (r - l + 1) / 2; if (mid * (n - 1) < sum) { l = mid + 1; } else { r = mid - 1; } } return l; } } static class _F { public static <T extends Comparable<T>> T max(T... list) { T candidate = list[0]; for (T i : list) { if (candidate.compareTo(i) < 0) { candidate = i; } } return candidate; } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public 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 close() { writer.close(); } public void println(long i) { writer.println(i); } } }
Java
["3\n3 2 2", "4\n2 2 2 2"]
2 seconds
["4", "3"]
NoteYou don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game).
Java 11
standard input
[ "binary search", "sortings", "math" ]
09f5623c3717c9d360334500b198d8e0
The first line contains integer n (3 ≤ n ≤ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the i-th number in the list is the number of rounds the i-th person wants to play.
1,600
In a single line print a single integer — the minimum number of game rounds the friends need to let the i-th person play at least ai rounds. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
2821ef8eb6b732046b5374a0484a4743
train_002.jsonl
1380295800
One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other n - 1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want?
256 megabytes
import java.io.*; import java.util.*; public class Mafia { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { // TODO Auto-generated method stub FastReader t = new FastReader(); PrintWriter o = new PrintWriter(System.out); int n = t.nextInt(); long x; long max = 0; long sum = 0; for (int i = 0; i < n; ++i) { x = t.nextLong(); max = Math.max(x, max); sum += x; } x = (sum + n - 2) / (n - 1); o.println(Math.max(x, max)); o.flush(); o.close(); } }
Java
["3\n3 2 2", "4\n2 2 2 2"]
2 seconds
["4", "3"]
NoteYou don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game).
Java 11
standard input
[ "binary search", "sortings", "math" ]
09f5623c3717c9d360334500b198d8e0
The first line contains integer n (3 ≤ n ≤ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the i-th number in the list is the number of rounds the i-th person wants to play.
1,600
In a single line print a single integer — the minimum number of game rounds the friends need to let the i-th person play at least ai rounds. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
4c4d6872fe6be7e6589ffab978bfaae1
train_002.jsonl
1380295800
One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other n - 1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want?
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class test { public static void main(String[] args) { // int t=fs.nextInt();while(t>0) // int test = fs.nextInt(); int test = 1; for (int cases = 0; cases < test; cases++) { int n=fs.nextInt(); long sum=0; long max=0; for(int i=0;i<n;i++) { long z=fs.nextLong(); if(max<z) { max=z; } sum+=z; } long ans=(long)Math.ceil((double)sum/(n-1)); if(ans<max) op.print(max); else op.print(ans); op.flush(); } } static int countDifferentBits(int a, int b) { int count = 0; for (int i = 0; i < 32; i++) { if (((a >> i) & 1) != ((b >> i) & 1)) { ++count; } } return count; } static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } static void sortMyMapusingValues(HashMap<String, Integer> hm) { List<Map.Entry<String, Integer>> capitalList = new LinkedList<>(hm.entrySet()); Collections.sort(capitalList, new Comparator<Map.Entry<String, Integer>>() { public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { return (o1.getValue()).compareTo(o2.getValue()); } }); HashMap<String, Integer> result = new HashMap<>(); for (Map.Entry<String, Integer> entry : capitalList) { result.put(entry.getKey(), entry.getValue()); } } static boolean ispowerof2(long num) { if ((num & (num - 1)) == 0) return true; return false; } static void primeFactors(int n) { while (n % 2 == 0) { System.out.print(2 + " "); n /= 2; } for (int i = 3; i <= Math.sqrt(n); i += 2) { while (n % i == 0) { System.out.print(i + " "); n /= i; } } if (n > 2) System.out.print(n); } static boolean isPrime(long n) { // Corner cases 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 class Graph { HashMap<Integer, LinkedList<Integer>> hm = new HashMap<Integer, LinkedList<Integer>>(); private void addVertex(int vertex) { hm.put(vertex, new LinkedList<>()); } private void addEdge(int source, int dest, boolean bi) { if (!hm.containsKey(source)) addVertex(source); if (!hm.containsKey(dest)) addVertex(dest); hm.get(source).add(dest); if (bi) { hm.get(dest).add(source); } } private boolean uniCycle(int i, HashSet<Integer> visited, int parent) { visited.add(i); LinkedList<Integer> list = hm.get(i); Iterator<Integer> it = list.iterator(); while (it.hasNext()) { Integer integer = (Integer) it.next(); if (!visited.contains(integer)) { if (uniCycle(integer, visited, i)) return true; } else if (integer != parent) { return true; } } return false; } private boolean uniCyclic() { HashSet<Integer> visited = new HashSet<Integer>(); Set<Integer> set = hm.keySet(); for (Integer integer : set) { if (!visited.contains(integer)) { if (uniCycle(integer, visited, -1)) { return true; } } } return false; } private boolean isbiCycle(int i, HashSet<Integer> visited, HashSet<Integer> countered) { if (countered.contains(i)) return true; if (visited.contains(i)) return false; visited.add(i); countered.add(i); LinkedList<Integer> list = hm.get(i); Iterator<Integer> it = list.iterator(); while (it.hasNext()) { Integer integer = (Integer) it.next(); if (isbiCycle(integer, visited, countered)) { return true; } } countered.remove(i); return false; } private boolean isbiCyclic() { HashSet<Integer> visited = new HashSet<Integer>(); HashSet<Integer> countered = new HashSet<Integer>(); Set<Integer> set = hm.keySet(); for (Integer integer : set) { if (isbiCycle(integer, visited, countered)) { return true; } } return false; } } static class Node { Node left, right; int data; public Node(int data) { this.data = data; } public void insert(int val) { if (val <= data) { if (left == null) { left = new Node(val); } else { left.insert(val); } } else { if (right == null) { right = new Node(val); } else { right.insert(val); } } } public boolean contains(int val) { if (data == val) { return true; } else if (val < data) { if (left == null) { return false; } else { return left.contains(val); } } else { if (right == null) { return false; } else { return right.contains(val); } } } public void inorder() { if (left != null) { left.inorder(); } System.out.print(data + " "); if (right != null) { right.inorder(); } } public int maxDepth() { if (left == null) return 0; if (right == null) return 0; else { int ll = left.maxDepth(); int rr = right.maxDepth(); if (ll > rr) return (ll + 1); else return (rr + 1); } } public int countNodes() { if (left == null) return 1; if (right == null) return 1; else { return left.countNodes() + right.countNodes() + 1; } } public void preorder() { System.out.print(data + " "); if (left != null) { left.inorder(); } if (right != null) { right.inorder(); } } public void postorder() { if (left != null) { left.inorder(); } if (right != null) { right.inorder(); } System.out.print(data + " "); } public void levelorder(Node node) { LinkedList<Node> ll = new LinkedList<Node>(); ll.add(node); getorder(ll); } public void getorder(LinkedList<Node> ll) { while (!ll.isEmpty()) { Node node = ll.poll(); System.out.print(node.data + " "); if (node.left != null) ll.add(node.left); if (node.right != null) ll.add(node.right); } } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static class Pair { int first, second; public Pair(int first, int second) { this.first = first; this.second = second; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } } private static final Scanner sc = new Scanner(System.in); private static final FastReader fs = new FastReader(); private static final OutputWriter op = new OutputWriter(System.out); static int[] getintarray(int n) { int ar[] = new int[n]; for (int i = 0; i < n; i++) { ar[i] = fs.nextInt(); } return ar; } static long[] getlongarray(int n) { long ar[] = new long[n]; for (int i = 0; i < n; i++) { ar[i] = fs.nextLong(); } return ar; } static int[][] get2darray(int n, int m) { int ar[][] = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { ar[i][j] = fs.nextInt(); } } return ar; } static Pair[] getpairarray(int n) { Pair ar[] = new Pair[n]; for (int i = 0; i < n; i++) { ar[i] = new Pair(fs.nextInt(), fs.nextInt()); } return ar; } static void printarray(int ar[]) { for (int i : ar) { op.print(i + " "); } op.flush(); } static int fact(int n) { int fact = 1; for (int i = 2; i <= n; i++) { fact *= i; } return fact; } // // function to find largest prime factor }
Java
["3\n3 2 2", "4\n2 2 2 2"]
2 seconds
["4", "3"]
NoteYou don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game).
Java 11
standard input
[ "binary search", "sortings", "math" ]
09f5623c3717c9d360334500b198d8e0
The first line contains integer n (3 ≤ n ≤ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the i-th number in the list is the number of rounds the i-th person wants to play.
1,600
In a single line print a single integer — the minimum number of game rounds the friends need to let the i-th person play at least ai rounds. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
1762877389e1f836cfc89022c6b1c2ab
train_002.jsonl
1380295800
One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other n - 1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class d { public static void main(String[] args) throws IOException { // Scanner s = new Scanner(System.in); BufferedReader s = new BufferedReader(new InputStreamReader(System.in)); // String[] st=s.readLine().trim().split("\\s+"); // a[i]=Integer.parseInt(st[i]); // Integer.parseInt(s.readLine().trim().split("\\s+"); StringBuilder sb = new StringBuilder(); StringBuilder sbf = new StringBuilder(); // int n=Integer.parseInt(s.readLine().trim().split("\\s+")[0]); /* String[] st=s.readLine().trim().split("\\s+"); int n=Integer.parseInt(st[0]);*/ int n=Integer.parseInt(s.readLine().trim().split("\\s+")[0]); String[] st=s.readLine().trim().split("\\s+"); int[] a=new int[n]; long sum=0;long max=0; for(int i=0;i<n;i++){ a[i]=Integer.parseInt(st[i]); sum+=a[i]; max=Math.max(max,a[i]); } long x=sum/(n-1);if(sum%(n-1)!=0) x++; System.out.println(Math.max(max,x)); } static String lexographicallysmallest(String s) { if (s.length() % 2 == 1) return s; String s1 =lexographicallysmallest(s.substring(0, s.length()/2)); String s2 = lexographicallysmallest(s.substring(s.length()/2, s.length())); if (s1.compareTo(s2)<0) return s1 + s2; else return s2 + s1; } public static int countSetBits(int n) { return (BitsSetTable256[n & 0xff] + BitsSetTable256[(n >> 8) & 0xff] + BitsSetTable256[(n >> 16) & 0xff] + BitsSetTable256[n >> 24]); } static int[] BitsSetTable256 ; public static void initialize(int n) { BitsSetTable256[0] = 0; for (int i = 0; i <=Math.pow(2,n); i++) { BitsSetTable256[i] = (i & 1) + BitsSetTable256[i / 2]; } } static void dfs(int i,int val,ArrayList<Integer>[] adj){ } static void computeLPSArray(String pat, int M, int lps[]) { int len = 0; int i = 1; lps[0] = 0; while (i < M) { if (pat.charAt(i) == pat.charAt(len)) { len++; lps[i] = len; i++; } else { if (len != 0) { len = lps[len - 1]; } else { lps[i] = len; i++; } } } } static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static long powerwithmod(long x, long y, int p) { long res = 1; x = x % p; while (y > 0) { if ((y & 1) == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } static long powerwithoutmod(long x, int y) { long temp; if( y == 0) return 1; temp = powerwithoutmod(x, y/2); if (y%2 == 0) return temp*temp; else { if(y > 0) return x * temp * temp; else return (temp * temp) / x; } } static void fracion(double x) { String a = "" + x; String spilts[] = a.split("\\."); // split using decimal int b = spilts[1].length(); // find the decimal length int denominator = (int) Math.pow(10, b); // calculate the denominator int numerator = (int) (x * denominator); // calculate the nerumrator Ex // 1.2*10 = 12 int gcd = (int) gcd((long) numerator, denominator); // Find the greatest common // divisor bw them String fraction = "" + numerator / gcd + "/" + denominator / gcd; // System.out.println((denominator/gcd)); long x1 = modInverse(denominator / gcd, 998244353); // System.out.println(x1); System.out.println((((numerator / gcd) % 998244353 * (x1 % 998244353)) % 998244353)); } static int bfs(int i1, ArrayList<Integer>[] h, int[] vis, int n,int val1) { Queue<Integer> q = new LinkedList<Integer>(); q.add(i1);Queue<Integer> aq=new LinkedList<Integer>(); aq.add(0); while(!q.isEmpty()){ int i=q.poll(); int val=aq.poll(); if(i==n){ return val; } if(h[i]!=null){ for(Integer j:h[i]){ if(vis[j]==0){ q.add(j);vis[j]=1; aq.add(val+1);} } } }return -1; } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static long modInverse(long a, int m) { return (powerwithmod(a, m - 2, m)); } static int MAXN; static int[] spf; static void sieve() { spf[1] = 1; for (int i=2; i<MAXN; i++) spf[i] = i; for (int i=4; i<MAXN; i+=2) spf[i] = 2; for (int i=3; i*i<MAXN; i++) { if (spf[i] == i) { for (int j=i*i; j<MAXN; j+=i) if (spf[j]==j) spf[j] = i; } } } static ArrayList<Integer> getFactorizationUsingSeive(int x) { ArrayList<Integer> ret = new ArrayList<Integer>(); while (x != 1) { ret.add(spf[x]); x = x / spf[x]; } return ret; } static long[] fac ; static void calculatefac(int mod){ fac[0]=1; for (int i = 1 ;i <= MAXN; i++) fac[i] = fac[i-1] * i % mod; } static long nCrModPFermat(int n, int r, int mod) { if (r == 0) return 1; fac[0] = 1; return (fac[n]* modInverse(fac[r], mod) % mod * modInverse(fac[n-r], mod) % mod) % mod; } } class Student { long l;long r;long x; public Student(long l, long r) { this.l = l; this.r = r; } public String toString() { return this.l+" "; } } class Sortbyroll implements Comparator<Student> { public int compare(Student a, Student b){ if(a.l<b.l) return 1; else if(a.l==b.l){ if(a.r==b.r){ return 0; } if(a.r<b.r) return -1; return 1;} return -1; } }
Java
["3\n3 2 2", "4\n2 2 2 2"]
2 seconds
["4", "3"]
NoteYou don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game).
Java 11
standard input
[ "binary search", "sortings", "math" ]
09f5623c3717c9d360334500b198d8e0
The first line contains integer n (3 ≤ n ≤ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the i-th number in the list is the number of rounds the i-th person wants to play.
1,600
In a single line print a single integer — the minimum number of game rounds the friends need to let the i-th person play at least ai rounds. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
0b8d612893192a16c1f60cee8b4c2e69
train_002.jsonl
1380295800
One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other n - 1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want?
256 megabytes
import java.util.*; import java.io.*; public class hello { public static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public 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 FastReader sc = new FastReader(); public static void take_array(long arr[], int size) { for (int i = 0; i < size; i++) { arr[i] = sc.nextLong(); } } public static void print_arr(long arr[]) { for (long x : arr) System.out.print(x + " "); } public static String[] convert_String_to_arr(String s) { String arr[] = new String[s.length()]; for (int i = 0; i < s.length(); i++) { arr[i] = String.valueOf(s.charAt(i)); } return arr; } public static void take_prefix_array(long arr[], int size, long []prefix) { long temp = 0; for (int i = 0; i < size; i++) { temp += arr[i]; prefix[i] = temp; } } public static void print(Object c, int a) { if (a == -1) System.out.print(c + " "); else System.out.println(c); } public static void space() { System.out.println(); } public static long sum_array(long arr[]) { long sum = 0; for (long x : arr) sum += x; return sum; } public static void swap(int a, int b) { int temp = a; a = b; b = temp; } public static boolean checkTosatisfy(long arr[], long mid) { long sum = 0; for (long x : arr) sum += (mid - x); return sum >= mid; } public static void minval(long []arr, int size) { long low = arr[size - 1], right = sum_array(arr); long result = right; while (low <= right) { long mid = (low + right) / 2; if (checkTosatisfy(arr, mid)) { result = mid; right = mid - 1; } else low = mid + 1; } print(result, 0); } public static void main(String []args) { int size = sc.nextInt(); long arr[] = new long[size]; take_array(arr, size); Arrays.sort(arr); minval(arr, size); } }
Java
["3\n3 2 2", "4\n2 2 2 2"]
2 seconds
["4", "3"]
NoteYou don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game).
Java 11
standard input
[ "binary search", "sortings", "math" ]
09f5623c3717c9d360334500b198d8e0
The first line contains integer n (3 ≤ n ≤ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the i-th number in the list is the number of rounds the i-th person wants to play.
1,600
In a single line print a single integer — the minimum number of game rounds the friends need to let the i-th person play at least ai rounds. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
08be338e863697db0e93728e9972b9a1
train_002.jsonl
1380295800
One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other n - 1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want?
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class cf348a { public static void main(String[] args) throws IOException { int n = ri(), a[] = ria(n); long l = maxof(a), r = 100000000000L, ans = r; while(l <= r) { long m = l + (r - l) / 2, sum = 0; for(int i = 0; i < n; ++i) { sum += m - a[i]; } if(sum >= m) { ans = m; r = m - 1; } else { l = m + 1; } } prln(ans); close(); } static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out)); static StringTokenizer input; static Random rand = new Random(); // references // IBIG = 1e9 + 7 // IRAND ~= 3e8 // IMAX ~= 2e10 // LMAX ~= 9e18 // constants static final int IBIG = 1000000007; static final int IRAND = 327859546; static final int IMAX = 2147483647; static final int IMIN = -2147483648; static final long LMAX = 9223372036854775807L; static final long LMIN = -9223372036854775808L; // util static int minof(int a, int b, int c) {return min(a, min(b, c));} static int minof(int... x) {return x.length == 1 ? x[0] : x.length == 2 ? min(x[0], x[1]) : min(x[0], minstarting(1, x));} static int minstarting(int offset, int... x) {assert x.length > 2; return offset == x.length - 2 ? min(x[offset], x[offset + 1]) : min(x[offset], minstarting(offset + 1, x));} static long minof(long a, long b, long c) {return min(a, min(b, c));} static long minof(long... x) {return x.length == 1 ? x[0] : x.length == 2 ? min(x[0], x[1]) : min(x[0], minstarting(1, x));} static long minstarting(int offset, long... x) {assert x.length > 2; return offset == x.length - 2 ? min(x[offset], x[offset + 1]) : min(x[offset], minstarting(offset + 1, x));} static int maxof(int a, int b, int c) {return max(a, max(b, c));} static int maxof(int... x) {return x.length == 1 ? x[0] : x.length == 2 ? max(x[0], x[1]) : max(x[0], maxstarting(1, x));} static int maxstarting(int offset, int... x) {assert x.length > 2; return offset == x.length - 2 ? max(x[offset], x[offset + 1]) : max(x[offset], maxstarting(offset + 1, x));} static long maxof(long a, long b, long c) {return max(a, max(b, c));} static long maxof(long... x) {return x.length == 1 ? x[0] : x.length == 2 ? max(x[0], x[1]) : max(x[0], maxstarting(1, x));} static long maxstarting(int offset, long... x) {assert x.length > 2; return offset == x.length - 2 ? max(x[offset], x[offset + 1]) : max(x[offset], maxstarting(offset + 1, x));} static int powi(int a, int b) {if(a == 0) return 0; int ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static long powl(long a, int b) {if(a == 0) return 0; long ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static int floori(double d) {return (int)d;} static int ceili(double d) {return (int)ceil(d);} static long floorl(double d) {return (long)d;} static long ceill(double d) {return (long)ceil(d);} static void shuffle(int[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(long[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(double[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static <T> void shuffle(T[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); T swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void sort(int[] a) {shuffle(a); Arrays.sort(a);} static void sort(long[] a) {shuffle(a); Arrays.sort(a);} static void sort(double[] a) {shuffle(a); Arrays.sort(a);} static void qsort(int[] a) {Arrays.sort(a);} static void qsort(long[] a) {Arrays.sort(a);} static void qsort(double[] a) {Arrays.sort(a);} static int randInt(int min, int max) {return rand.nextInt(max - min + 1) + min;} // input static void r() throws IOException {input = new StringTokenizer(__in.readLine());} static int ri() throws IOException {return Integer.parseInt(__in.readLine());} static long rl() throws IOException {return Long.parseLong(__in.readLine());} static int[] ria(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()); return a;} static long[] rla(int n) throws IOException {long[] a = new long[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Long.parseLong(input.nextToken()); return a;} static char[] rcha() throws IOException {return __in.readLine().toCharArray();} static String rline() throws IOException {return __in.readLine();} static int rni() throws IOException {input = new StringTokenizer(__in.readLine()); return Integer.parseInt(input.nextToken());} static int ni() {return Integer.parseInt(input.nextToken());} static long rnl() throws IOException {input = new StringTokenizer(__in.readLine()); return Long.parseLong(input.nextToken());} static long nl() {return Long.parseLong(input.nextToken());} // output static void pr(int i) {__out.print(i);} static void prln(int i) {__out.println(i);} static void pr(long l) {__out.print(l);} static void prln(long l) {__out.println(l);} static void pr(double d) {__out.print(d);} static void prln(double d) {__out.println(d);} static void pr(char c) {__out.print(c);} static void prln(char c) {__out.println(c);} static void pr(char[] s) {__out.print(new String(s));} static void prln(char[] s) {__out.println(new String(s));} static void pr(String s) {__out.print(s);} static void prln(String s) {__out.println(s);} static void pr(Object o) {__out.print(o);} static void prln(Object o) {__out.println(o);} static void prln() {__out.println();} static void pryes() {__out.println("yes");} static void pry() {__out.println("Yes");} static void prY() {__out.println("YES");} static void prno() {__out.println("no");} static void prn() {__out.println("No");} static void prN() {__out.println("NO");} static void pryesno(boolean b) {__out.println(b ? "yes" : "no");}; static void pryn(boolean b) {__out.println(b ? "Yes" : "No");} static void prYN(boolean b) {__out.println(b ? "YES" : "NO");} static void prln(int... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static void prln(long... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for(int i = 0; i < n; __out.print(iter.next()), __out.print(' '), ++i); if(n >= 0) __out.println(iter.next());} static void h() {__out.println("hlfd");} static void flush() {__out.flush();} static void close() {__out.close();} }
Java
["3\n3 2 2", "4\n2 2 2 2"]
2 seconds
["4", "3"]
NoteYou don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game).
Java 11
standard input
[ "binary search", "sortings", "math" ]
09f5623c3717c9d360334500b198d8e0
The first line contains integer n (3 ≤ n ≤ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the i-th number in the list is the number of rounds the i-th person wants to play.
1,600
In a single line print a single integer — the minimum number of game rounds the friends need to let the i-th person play at least ai rounds. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
0b014832a781b2f28cd12419fecfe8e4
train_002.jsonl
1380295800
One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other n - 1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want?
256 megabytes
import java.io.*; import java.util.*; public class Test { public static void main(String[] args) throws IOException{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int n=Integer.parseInt(br.readLine()); String[] ss=br.readLine().split(" "); int[] a=new int[n]; long sum=0;int max=0; for(int i=0;i<n;i++) { a[i]=Integer.parseInt(ss[i]); max=Math.max(a[i],max); sum+=(long)a[i]; } long ans=max; if(ans<(long)(Math.ceil(((double)(sum)/(n-1))))) ans=(long)(Math.ceil(((double)(sum)/(n-1)))); System.out.println(ans); } }
Java
["3\n3 2 2", "4\n2 2 2 2"]
2 seconds
["4", "3"]
NoteYou don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game).
Java 11
standard input
[ "binary search", "sortings", "math" ]
09f5623c3717c9d360334500b198d8e0
The first line contains integer n (3 ≤ n ≤ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the i-th number in the list is the number of rounds the i-th person wants to play.
1,600
In a single line print a single integer — the minimum number of game rounds the friends need to let the i-th person play at least ai rounds. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
50987b697a07f5cc883fda038f6907b1
train_002.jsonl
1380295800
One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other n - 1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want?
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main{ public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out)); public static void main(String sp[])throws IOException{ //Scanner sc = new Scanner(System.in); FastReader sc = new FastReader(); int n = sc.nextInt(); long arr[] = new long[n+1]; long l = 1l; long r = (long)2e9; for(int i=1;i<=n;i++){ arr[i] = sc.nextLong(); } long ans = Long.MAX_VALUE; while(l<=r){ long mid = (l+r)/2; if(check(mid, arr, n)==true){ ans = Math.min(ans, mid); r = mid-1; }else{ l = mid+1; } } System.out.println(ans); } public static boolean check(long mid , long arr[],int n){ long sum = 0; for(int i=1;i<=n;i++){ if(arr[i]>mid){ return false; } sum+=(mid-arr[i]); } if(sum<mid) return false; return true; } public static class pair{ long bal; long wt; long diff; } public static class comp implements Comparator<pair>{ public int compare(pair o1, pair o2){ return Long.valueOf(o1.diff).compareTo(Long.valueOf(o2.diff)); } } static class FastReader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public FastReader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public FastReader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } }
Java
["3\n3 2 2", "4\n2 2 2 2"]
2 seconds
["4", "3"]
NoteYou don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game).
Java 11
standard input
[ "binary search", "sortings", "math" ]
09f5623c3717c9d360334500b198d8e0
The first line contains integer n (3 ≤ n ≤ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the i-th number in the list is the number of rounds the i-th person wants to play.
1,600
In a single line print a single integer — the minimum number of game rounds the friends need to let the i-th person play at least ai rounds. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
280e73f61315ce8f32e214045a1db16f
train_002.jsonl
1380295800
One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other n - 1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Mafia { public static void main(String[] args) { Reader1 s1=new Reader1(); int n=s1.nextInt(); long total=0; long max=0; for(int i=0;i<n;i++){ int temp=s1.nextInt(); total+=temp; if(temp>max){ max=temp; } }if((long)Math.ceil(((double)total)/(n-1))>max){ System.out.println((long)Math.ceil(((double)total)/(n-1))); }else { System.out.println(max); } } } class Reader1 { BufferedReader br; StringTokenizer st; public Reader1() { 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(); } public int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
Java
["3\n3 2 2", "4\n2 2 2 2"]
2 seconds
["4", "3"]
NoteYou don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game).
Java 11
standard input
[ "binary search", "sortings", "math" ]
09f5623c3717c9d360334500b198d8e0
The first line contains integer n (3 ≤ n ≤ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the i-th number in the list is the number of rounds the i-th person wants to play.
1,600
In a single line print a single integer — the minimum number of game rounds the friends need to let the i-th person play at least ai rounds. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
efb17e7663693b9182cbbf54f9045b3f
train_002.jsonl
1380295800
One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other n - 1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want?
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main { public static void process(int test_number)throws IOException { long n = ni(), mx = 0l; long sum = 0l; for(int i = 1; i <= n; i++){ long x = nl(); mx = Math.max(mx, x); sum += x; } long res = sum / (n - 1l) + (sum % (n - 1l) == 0 ? 0 : 1l); res = Math.max(res, mx); pn(res); } static final long mod = (long)1e9+7l; 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(); for(int i = 1; i <= t; i++) process(i); out.flush(); System.err.println(System.currentTimeMillis()-s+"ms"); } static void trace(Object... o){ System.err.println(Arrays.deepToString(o)); }; 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 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
["3\n3 2 2", "4\n2 2 2 2"]
2 seconds
["4", "3"]
NoteYou don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game).
Java 11
standard input
[ "binary search", "sortings", "math" ]
09f5623c3717c9d360334500b198d8e0
The first line contains integer n (3 ≤ n ≤ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the i-th number in the list is the number of rounds the i-th person wants to play.
1,600
In a single line print a single integer — the minimum number of game rounds the friends need to let the i-th person play at least ai rounds. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
4ae3b73dec1a0df16c81fc97ee503cd7
train_002.jsonl
1380295800
One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other n - 1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want?
256 megabytes
//package random_practiceQuestions; import java.util.Scanner; public class A348 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner s = new Scanner(System.in); int a=s.nextInt(); s.nextLine(); String[] l=s.nextLine().split(" "); long[] list=new long[a]; for (int i=0;i<list.length;i++){ list[i]=Long.parseLong(l[i]); } long sum=0; long max=0; for (long i:list){ sum=sum+i; max=Math.max(i,max); } long d=sum/(a-1); if (d*(a-1)==sum){ System.out.println(Math.max(d,max)); } else{ System.out.println(Math.max(d+1,max)); } } }
Java
["3\n3 2 2", "4\n2 2 2 2"]
2 seconds
["4", "3"]
NoteYou don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game).
Java 11
standard input
[ "binary search", "sortings", "math" ]
09f5623c3717c9d360334500b198d8e0
The first line contains integer n (3 ≤ n ≤ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the i-th number in the list is the number of rounds the i-th person wants to play.
1,600
In a single line print a single integer — the minimum number of game rounds the friends need to let the i-th person play at least ai rounds. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
41a418b9bfe403632698a048dd0946c7
train_002.jsonl
1380295800
One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other n - 1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want?
256 megabytes
import java.util.*; import java.io.*; public class A { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); long[] a = new long[n]; long sum = 0; long max = 0; for(int i = 0; i < n; i++) { a[i] = sc.nextLong(); sum += a[i]; max = Math.max(max, a[i]); } System.out.println(Math.max((long) (sum + n - 2) / (long) (n-1), max)); } }
Java
["3\n3 2 2", "4\n2 2 2 2"]
2 seconds
["4", "3"]
NoteYou don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game).
Java 11
standard input
[ "binary search", "sortings", "math" ]
09f5623c3717c9d360334500b198d8e0
The first line contains integer n (3 ≤ n ≤ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the i-th number in the list is the number of rounds the i-th person wants to play.
1,600
In a single line print a single integer — the minimum number of game rounds the friends need to let the i-th person play at least ai rounds. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
261192daf2107e41d7b58a5b29e19e31
train_002.jsonl
1380295800
One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other n - 1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want?
256 megabytes
import java.util.*; import java.io.*; public class File { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); long total = 0; long max = 0; for (int i = 0; i < n; i++) { long num = sc.nextLong(); total += num; max = Math.max(max, num); } // The answer is x games. // In x games, each player, A, is supervisor for at most // x-A games. // this is because, for the player A to reduce to 0, // there must be A games the player is not the supervisor. /* (x - a1) + (x - a2) + ... + (x - an) = x*n - S(a) This must be >= x. x <= n*x - S(a) S(a) <= x (n - 1) x = ceil(S(a) / (n-1)) */ long x = (long)Math.ceil((double)(total) / (double)(n-1)); System.out.println(Math.max(x, max)); } }
Java
["3\n3 2 2", "4\n2 2 2 2"]
2 seconds
["4", "3"]
NoteYou don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game).
Java 11
standard input
[ "binary search", "sortings", "math" ]
09f5623c3717c9d360334500b198d8e0
The first line contains integer n (3 ≤ n ≤ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the i-th number in the list is the number of rounds the i-th person wants to play.
1,600
In a single line print a single integer — the minimum number of game rounds the friends need to let the i-th person play at least ai rounds. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
ff2d239553bb1035317203bce21d6fb3
train_002.jsonl
1380295800
One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other n - 1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want?
256 megabytes
import java.util.*; import java.io.*; public class File { public static void main(String[] args) { Scanner sc = new Scanner(System.in); /* There is some number of games that is our answer, x. We know that for each person, Ai, x - Ai games can have person Ai as the supervisor. Number of games that each can be supervisor is: (x - A1) + (x - A2) + ... + (x - An) = x*n - S(A) This is the number of games players can be supervisor each. This might be more than needed, >= x. x <= x*n - S(A) = S(A) <= x*n - x = S(A) <= x(n-1) S(A) / (n-1) <= x The min answer = ceil(S(A) / (n-1)) However, this might be less than the max element. Must be Math.max(answer, max) */ int n = sc.nextInt(); long total = 0; long max = 0; for (int i = 0; i < n; i++) { long val = sc.nextLong(); total += val; max = Math.max(max, val); } long result = (long)Math.ceil((double)(total) / (double)(n-1)); System.out.println(Math.max(result, max)); } }
Java
["3\n3 2 2", "4\n2 2 2 2"]
2 seconds
["4", "3"]
NoteYou don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game).
Java 11
standard input
[ "binary search", "sortings", "math" ]
09f5623c3717c9d360334500b198d8e0
The first line contains integer n (3 ≤ n ≤ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the i-th number in the list is the number of rounds the i-th person wants to play.
1,600
In a single line print a single integer — the minimum number of game rounds the friends need to let the i-th person play at least ai rounds. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
77fb7597f4778b9a096d992e51d33caf
train_002.jsonl
1380295800
One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other n - 1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class code { public static void main(String[] args)throws IOException { FastReader sc = new FastReader(); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(); long arr[] = new long[n]; long sum = 0; long max = 0; for (int i = 0; i < n; i++) { arr[i] = sc.nextLong(); sum += arr[i]; max = Math.max(max, arr[i]); } long a = (long)Math.ceil(sum * 1.0 / (n - 1) * 1.0); long b = max; //System.out.println(sum + " " + (n - 1)); System.out.println(Math.max(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; } }
Java
["3\n3 2 2", "4\n2 2 2 2"]
2 seconds
["4", "3"]
NoteYou don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game).
Java 11
standard input
[ "binary search", "sortings", "math" ]
09f5623c3717c9d360334500b198d8e0
The first line contains integer n (3 ≤ n ≤ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the i-th number in the list is the number of rounds the i-th person wants to play.
1,600
In a single line print a single integer — the minimum number of game rounds the friends need to let the i-th person play at least ai rounds. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
f9133a8fae9063505a46af1fd1798c4a
train_002.jsonl
1380295800
One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other n - 1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want?
256 megabytes
import java.io.*; import java.util.*; public class Main { private static FastReader f = new FastReader(); public static void main(String[] args) { int n = f.nextInt(); long sum = 0; long max = 0; for(int i=0;i<n;i++) { long loc = f.nextInt(); max = Math.max(max, loc); sum += loc; } if(sum % (n-1) != 0) { sum = (sum/(n-1))+1; } else { sum = (sum/(n-1)); } System.out.println(Math.max(sum, max)); } //fast input reader static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n3 2 2", "4\n2 2 2 2"]
2 seconds
["4", "3"]
NoteYou don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game).
Java 11
standard input
[ "binary search", "sortings", "math" ]
09f5623c3717c9d360334500b198d8e0
The first line contains integer n (3 ≤ n ≤ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the i-th number in the list is the number of rounds the i-th person wants to play.
1,600
In a single line print a single integer — the minimum number of game rounds the friends need to let the i-th person play at least ai rounds. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
b52b4a70ed73c6a9ec27d6c5836e39bd
train_002.jsonl
1380295800
One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other n - 1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want?
256 megabytes
// #pragma GCC optimize("Ofast") // #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") import java.io.*; import java.util.*; import static java.lang.Math.*; public class Main { static int infi = Integer.MAX_VALUE / 2, mod = (int) (1e9 + 7), maxn = (int) 1e5; static long infl = Long.MAX_VALUE / 2; public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); int n = nextInt(); int[] a = new int[n]; long sum = 0; long max = 0; for (int i = 0; i < n; i++) { a[i] = nextInt(); sum += a[i]; max = max(max, a[i]); } out.print(max(sum / (n - 1) + (sum % (n - 1) == 0 ? 0 : 1), max)); out.close(); } static BufferedReader br; static StringTokenizer st = new StringTokenizer(""); static PrintWriter out; static String next() throws IOException { while (!st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } } class f { int x, y; public f(int x, int y) { this.x = x; this.y = y; } }
Java
["3\n3 2 2", "4\n2 2 2 2"]
2 seconds
["4", "3"]
NoteYou don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game).
Java 11
standard input
[ "binary search", "sortings", "math" ]
09f5623c3717c9d360334500b198d8e0
The first line contains integer n (3 ≤ n ≤ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the i-th number in the list is the number of rounds the i-th person wants to play.
1,600
In a single line print a single integer — the minimum number of game rounds the friends need to let the i-th person play at least ai rounds. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
da5e8e8368097c6b77f02a73fe6514fd
train_002.jsonl
1380295800
One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other n - 1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want?
256 megabytes
import java.util.*;import java.io.*;import java.math.*; public class Main { public static void process()throws IOException { long n=nl(); long sum=0l,mx=0l,inp=0l; for(int i=1;i<=n;i++){sum+=(inp=nl()); mx=Math.max(mx,inp);} long x=0l;//no. of supervision >= no. of games long l=mx,r=(long)1e10,mid=0l; while(l<=r){ mid=l+(r-l)/2l; if(n*mid-sum>=mid){ x=mid; r=mid-1; } else l=mid+1; } pn(x); } static AnotherReader sc; static PrintWriter out; public static void main(String[]args)throws IOException { out = new PrintWriter(System.out); sc=new AnotherReader(); boolean oj = true; oj = System.getProperty("ONLINE_JUDGE") != null; if(!oj) sc=new AnotherReader(100); long s = System.currentTimeMillis(); int t=1; while(t-->0) process(); out.flush(); if(!oj) System.out.println(System.currentTimeMillis()-s+"ms"); System.out.close(); } static void pn(Object o){out.println(o);} static void p(Object o){out.print(o);} static void pni(Object o){out.println(o);System.out.flush();} static int ni()throws IOException{return sc.nextInt();} static long nl()throws IOException{return sc.nextLong();} static double nd()throws IOException{return sc.nextDouble();} static String nln()throws IOException{return sc.nextLine();} static long gcd(long a, long b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int gcd(int a, int b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int bit(long n)throws IOException{return (n==0)?0:(1+bit(n&(n-1)));} static boolean multipleTC=false; ///////////////////////////////////////////////////////////////////////////////////////////////////////// static class AnotherReader{BufferedReader br; StringTokenizer st; AnotherReader()throws FileNotFoundException{ br=new BufferedReader(new InputStreamReader(System.in));} AnotherReader(int a)throws FileNotFoundException{ br = new BufferedReader(new FileReader("input.txt"));} String next()throws IOException{ while (st == null || !st.hasMoreElements()) {try{ st = new StringTokenizer(br.readLine());} catch (IOException e){ e.printStackTrace(); }} return st.nextToken(); } int nextInt() throws IOException{ return Integer.parseInt(next());} long nextLong() throws IOException {return Long.parseLong(next());} double nextDouble()throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException{ String str = ""; try{ str = br.readLine();} catch (IOException e){ e.printStackTrace();} return str;}} ///////////////////////////////////////////////////////////////////////////////////////////////////////////// }
Java
["3\n3 2 2", "4\n2 2 2 2"]
2 seconds
["4", "3"]
NoteYou don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game).
Java 11
standard input
[ "binary search", "sortings", "math" ]
09f5623c3717c9d360334500b198d8e0
The first line contains integer n (3 ≤ n ≤ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the i-th number in the list is the number of rounds the i-th person wants to play.
1,600
In a single line print a single integer — the minimum number of game rounds the friends need to let the i-th person play at least ai rounds. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
a226eab12db348e70414bf6d99112ba1
train_002.jsonl
1567175700
The only difference between easy and hard versions is the number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. In one move you can choose any $$$a_i$$$ and divide it by $$$2$$$ rounding down (in other words, in one move you can set $$$a_i := \lfloor\frac{a_i}{2}\rfloor$$$).You can perform such an operation any (possibly, zero) number of times with any $$$a_i$$$.Your task is to calculate the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.Don't forget that it is possible to have $$$a_i = 0$$$ after some operations, thus the answer always exists.
256 megabytes
import java.util.*; public class main{ static int MAX = 100010; static long mod = 998244353; static ArrayList<Integer>[] amp, bmp; static boolean b[]; static Scanner sc = new Scanner(System.in); public static void main(String[] args){ int n = sc.nextInt(), k = sc.nextInt(); int arr[] = new int[n]; for(int i = 0; i< n; i++){ arr[i] = sc.nextInt(); } int[] fq = new int[4*100000+1000]; for(int i : arr) fq[i]++; int fa = 1000000000; int prefix[] = new int[4*100000+1000]; for(int i = 1; i<prefix.length; i++){ prefix[i] = prefix[i-1]+fq[i]; } int pow[] = new int[25]; pow[0] = 1; for(int i =1; i<=24; i++) pow[i] = pow[i-1]*2; for(int i = 1; i<=2*100000; i++){ int val = fq[i], temp = i, cnt = i, j = 0, ans = 0, prev = i-1, prev_val = 0; while(val < k && cnt < 200010){ ans += (prefix[cnt] - prefix[temp-1])*j; prev_val = val; j++; temp = i*pow[j]; cnt = temp + pow[j]-1; val += (prefix[cnt] - prefix[temp-1]); } if(val >= k){ ans += (k - prev_val)*j; fa = Math.min(fa,ans); } //System.out.println(val +" "+ans+" "+j); } System.out.println(fa); } static long ncp(int k, int x){ if(k<x) return 0; if(k==x) return 1; long ans = 1; for(int i = k; i>(k-x); i--){ ans *= i; ans %= mod; } return ans; } static int dfs(int x){ b[x] = true; int ans = 1; for(int i : amp[x]){ if(!b[i]){ ans += dfs(i); } } return ans; } static void buildGraph(int n){ for(int i=0; i<n; i++){ int x = sc.nextInt(), y = sc.nextInt(), c = sc.nextInt(); if (c == 1) { bmp[x].add(y); bmp[y].add(x); } else{ amp[x].add(y); amp[y].add(x); } } } static long pow(long x, int y, long mod){ long ans = 1; while(y>0){ if(y%2==0){ x *= x; x %= mod; y/=2; } else{ y-=1; ans *= x; ans %= mod; } } return ans; } static class Pair implements Comparable<Pair>{ int x, y; Pair(int a, int b){ x = a; y = b; } public int compareTo(Pair p){ return -Integer.compare(this.y, p.y); } } 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; } }
Java
["5 3\n1 2 2 4 5", "5 3\n1 2 3 4 5", "5 3\n1 2 3 3 3"]
2 seconds
["1", "2", "0"]
null
Java 8
standard input
[ "sortings", "brute force", "math" ]
ed1a2ae733121af6486568e528fe2d84
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 50$$$) — the number of elements in the array and the number of equal numbers required. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,600
Print one integer — the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.
standard output
PASSED
4a3729dcd6d55b0f76f225060f3fb1ce
train_002.jsonl
1567175700
The only difference between easy and hard versions is the number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. In one move you can choose any $$$a_i$$$ and divide it by $$$2$$$ rounding down (in other words, in one move you can set $$$a_i := \lfloor\frac{a_i}{2}\rfloor$$$).You can perform such an operation any (possibly, zero) number of times with any $$$a_i$$$.Your task is to calculate the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.Don't forget that it is possible to have $$$a_i = 0$$$ after some operations, thus the answer always exists.
256 megabytes
import java.util.*; import java.io.*; public class Main { static long mod = 1000000007; static long INF = 1000000000000L; public static void main(String[] args){ FastScanner scanner = new FastScanner(); int n = scanner.nextInt(); int k = scanner.nextInt(); int[] a = new int[n]; for(int i = 0; i < n; i++){ a[i] = scanner.nextInt(); } //list[i]:=a[0]~a[n-1]の数をそれぞれ2で割って整数iにするために必要な操作の回数のリスト ArrayList<Integer>[] list = new ArrayList[200010]; for(int i = 0; i < 200010; i++){ list[i] = new ArrayList<Integer>(); } for(int i = 0; i < n; i++){ int x = a[i]; int cnt = 0; while(x > 0){ list[x].add(cnt); x /= 2; cnt++; } } long min = INF; for(int i = 0; i <= 200*1000; i++){ Collections.sort(list[i]); if(list[i].size() < k) continue; long sum = 0; for(int j = 0; j < k; j++){ sum += list[i].get(j); } min = Math.min(min,sum); } System.out.println(min); } static class Pair implements Comparable<Pair>{ int first, second; Pair(int a, int b){ first = a; second = b; } @Override public boolean equals(Object o){ if (this == o) return true; if (!(o instanceof Pair)) return false; Pair p = (Pair) o; return first == p.first && second == p.second; } @Override public int compareTo(Pair p){ //return first == p.first ? second - p.second : first - p.first; //firstで昇順にソート //return (first == p.first ? second - p.second : first - p.first) * -1; //firstで降順にソート //return second == p.second ? first - p.first : second - p.second;//secondで昇順にソート //return (second == p.second ? first - p.first : second - p.second)*-1;//secondで降順にソート //return first * 1.0 / second > p.first * 1.0 / p.second ? 1 : -1; // first/secondの昇順にソート //return first * 1.0 / second < p.first * 1.0 / p.second ? 1 : -1; // first/secondの降順にソート //return second * 1.0 / first > p.second * 1.0 / p.first ? 1 : -1; // second/firstの昇順にソート //return second * 1.0 / first < p.second * 1.0 / p.first ? 1 : -1; // second/firstの降順にソート //return Math.atan2(second, first) > Math.atan2(p.second, p.first) ? 1 : -1; // second/firstの昇順にソート //return first + second > p.first + p.second ? 1 : -1; //first+secondの昇順にソート //return first + second < p.first + p.second ? 1 : -1; //first+secondの降順にソート return first - second < p.first - p.second ? 1 : -1; //first-secondの降順にソート } } private static class FastScanner { private final InputStream in = System.in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; private boolean hasNextByte() { if (ptr < buflen) { return true; }else{ ptr = 0; try { buflen = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;} private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;} public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte();} public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while(isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public long nextLong() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while(true){ if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; }else if(b == -1 || !isPrintableChar(b)){ return minus ? -n : n; }else{ throw new NumberFormatException(); } b = readByte(); } } public int nextInt() { long nl = nextLong(); if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException(); return (int) nl; } public double nextDouble() { return Double.parseDouble(next());} } }
Java
["5 3\n1 2 2 4 5", "5 3\n1 2 3 4 5", "5 3\n1 2 3 3 3"]
2 seconds
["1", "2", "0"]
null
Java 8
standard input
[ "sortings", "brute force", "math" ]
ed1a2ae733121af6486568e528fe2d84
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 50$$$) — the number of elements in the array and the number of equal numbers required. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,600
Print one integer — the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.
standard output
PASSED
18498429d7c28a0d706d330f8abbb233
train_002.jsonl
1567175700
The only difference between easy and hard versions is the number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. In one move you can choose any $$$a_i$$$ and divide it by $$$2$$$ rounding down (in other words, in one move you can set $$$a_i := \lfloor\frac{a_i}{2}\rfloor$$$).You can perform such an operation any (possibly, zero) number of times with any $$$a_i$$$.Your task is to calculate the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.Don't forget that it is possible to have $$$a_i = 0$$$ after some operations, thus the answer always exists.
256 megabytes
import java.util.*; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; import java.math.BigInteger; import java.util.Scanner; import java.util.StringTokenizer; public class temp { void solve() throws IOException { FastReader sc = new FastReader(); int n = sc.nextInt(); int k = sc.nextInt(); int a[] = new int[n]; for(int i=0;i<n;i++) a[i] = sc.nextInt(); int N = (int)(2e5) + 1; ArrayList<Integer> x[] = new ArrayList[N]; for(int i=0;i<N;i++) x[i] = new ArrayList<Integer>(); for(int i=0;i<n;i++) { int d = a[i] , cost = 0; while(d!=0) { x[d].add(cost); cost++; d/=2; } x[0].add(cost); } int ans = Integer.MAX_VALUE; for(int i=0;i<N;i++) { if(x[i].size() >= k) { x[i].sort(null); int p = 0; for(int j=0;j<k;j++) p += x[i].get(j); ans = Math.min(ans , p); } } System.out.println(ans); } public static void main(String[] args) throws IOException { // TODO Auto-generated method stub new temp().solve(); } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5 3\n1 2 2 4 5", "5 3\n1 2 3 4 5", "5 3\n1 2 3 3 3"]
2 seconds
["1", "2", "0"]
null
Java 8
standard input
[ "sortings", "brute force", "math" ]
ed1a2ae733121af6486568e528fe2d84
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 50$$$) — the number of elements in the array and the number of equal numbers required. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,600
Print one integer — the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.
standard output
PASSED
d6b215cee5edcda4191b6427ad2a301e
train_002.jsonl
1567175700
The only difference between easy and hard versions is the number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. In one move you can choose any $$$a_i$$$ and divide it by $$$2$$$ rounding down (in other words, in one move you can set $$$a_i := \lfloor\frac{a_i}{2}\rfloor$$$).You can perform such an operation any (possibly, zero) number of times with any $$$a_i$$$.Your task is to calculate the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.Don't forget that it is possible to have $$$a_i = 0$$$ after some operations, thus the answer always exists.
256 megabytes
import java.io.*; import java.util.*; import java.text.*; import java.lang.*; import java.math.*; public class Myclass{ static ArrayList[] a=new ArrayList[200001]; public void solve () { InputReader in = new InputReader(System.in); PrintWriter pw = new PrintWriter(System.out); int n=in.nextInt(); int k=in.nextInt(); Long a[]=new Long [n]; for(int i=0;i<n;i++) a[i]=in.nextLong(); Arrays.sort(a); long dp[]=new long [200001]; int cnt[]=new int [200001]; for(int i=0;i<n;i++) { long val=a[i]; int got=0; while(true) { if(cnt[(int) val]>=k) break; cnt[(int)val]++; dp[(int) val]+=got; if(val==0L) break; got++; val/=2L; } } long ans=Long.MAX_VALUE; for(int i=0;i<200001;i++) { if(cnt[i]>=k) { ans=Math.min(ans, dp[i]); } } pw.println(ans); pw.flush(); pw.close(); } public static void main(String[] args) throws Exception { new Thread(null,new Runnable() { public void run() { new Myclass().solve(); } },"1",1<<26).start(); } static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static long mod = 1000000007; public static int d; public static int p; public static int q; public void extended(int a,int b) { if(b==0) { d=a; p=1; q=0; } else { extended(b,a%b); int temp=p; p=q; q=temp-(a/b)*q; } } public static int binaryExponentiation(int x,int n) { int result=1; while(n>0) { if(n % 2 ==1) result=result * x; x=x*x; n=n/2; } return result; } public static long binaryExponentiation(long x,long n) { long result=1; while(n>0) { if(n % 2 ==1) result=result * x; x=x*x; n=n/2; } return result; } public static long[] shuffle(long[] a,Random gen) { int n = a.length; for(int i=0;i<n;i++) { int ind = gen.nextInt(n-i)+i; long temp = a[ind]; a[ind] = a[i]; a[i] = temp; } return a; } public static void swap(int a, int b){ int temp = a; a = b; b = temp; } public static HashSet<Integer> primeFactorization(int n) { HashSet<Integer> a =new HashSet<Integer>(); for(int i=2;i*i<=n;i++) { while(n%i==0) { a.add(i); n/=i; } } if(n!=1) a.add(n); return a; } public static void sieve(boolean[] isPrime,int n) { for(int i=1;i<n;i++) isPrime[i] = true; isPrime[0] = false; isPrime[1] = false; for(int i=2;i*i<n;i++) { if(isPrime[i] == true) { for(int j=(2*i);j<n;j+=i) isPrime[j] = false; } } } public static long GCD(long n,long m) { if(m==0) return n; else return GCD(m,n%m); } static class pair implements Comparable<pair> { Long x,y; pair(long l,long m) { this.x=l; this.y=m; } public int compareTo(pair o) { int result = x.compareTo(o.x); if(result==0) result = y.compareTo(o.y); return result; } public String toString() { return x+" "+y; } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair)o; return p.x.equals(x) && p.y.equals(y) ; } return false; } public int hashCode() { return new Long(x).hashCode()*31 + new Long(y).hashCode(); } } } /*class dsu{ int parent[]; dsu(int n){ parent=new int[n+1]; for(int i=0;i<=n;i++) { parent[i]=i; } } int root(int n) { while(parent[n]!=n) { parent[n]=parent[parent[n]]; n=parent[n]; } return n; } void union(int _a,int _b) { int p_a=root(_a); int p_b=root(_b); parent[p_a]=p_b; } boolean find(int a,int b) { if(root(a)==root(b)) return true; else return false; } }*/ class Segment{ long seg[]; long[] a; int lazy[]; Segment (int n){ seg=new long[4*n]; lazy=new int[4*n]; } public void build(int node,int start,int end) { if(start==end) { seg[node]=0; return ; } int mid=(start+end)/2; build(2*node+1,start,mid); build(2*node+2,mid+1,end); seg[node]=(seg[2*node+1]+seg[2*node+2]); } public void update(int node,int start,int end,int fi,long fi2) { if(start==end) { seg[node]=fi2; return; } int mid=(start+end)/2; if(fi>=start && fi<=mid) { update(2*node+1,start,mid,fi,fi2); } else update(2*node+2,mid+1,end,fi,fi2); seg[node]=seg[2*node+1]+seg[2*node+2]; } public long query(int node,int start,int end,int l,int r) { if(l>end || r<start) return 0; if(start>=l && end<=r) return seg[node]; int mid=(start+end)/2; return (query(2*node+1,start,mid,l,r)+query(2*node+2,mid+1,end,l,r)); } /*public void updateRange(int node,int start,int end,int l,int r,int val) { if(lazy[node]!=0) { if(start!=end) { lazy[2*node+1]+=lazy[node]; lazy[2*node+2]+=lazy[node]; } lazy[node]=0; } if(l>end || r<start) return ; if(start>=l && end<=r) { seg[node]=(end-start+1)*val; if(start!=end) { lazy[2*node+1]+=val; lazy[2*node+2]+=val; } lazy[node]=0; return ; } int mid=(start+end)/2; updateRange(2*node+1,start,mid,l,r,val); updateRange(2*node+2,mid+1,end,l,r,val); seg[node]=seg[2*node+1]+seg[2*node+2]; } public int queryRange(int node,int start,int end,int l,int r) { if(l>end || r<start) return 0; if(lazy[node]!=0) { seg[node]=(end-start+1)*lazy[node]; if(start!=end) { lazy[2*node+1]+=lazy[node]; lazy[2*node+2]+=lazy[node]; } lazy[node]=0; } if(start>=l && end<=r) return seg[node]; int mid=(start+end)/2; return (query(2*node+1,start,mid,l,r)+query(2*node+2,mid+1,end,l,r)); }*/ }
Java
["5 3\n1 2 2 4 5", "5 3\n1 2 3 4 5", "5 3\n1 2 3 3 3"]
2 seconds
["1", "2", "0"]
null
Java 8
standard input
[ "sortings", "brute force", "math" ]
ed1a2ae733121af6486568e528fe2d84
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 50$$$) — the number of elements in the array and the number of equal numbers required. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,600
Print one integer — the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.
standard output
PASSED
1fc718294add218769a844675e32e73c
train_002.jsonl
1567175700
The only difference between easy and hard versions is the number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. In one move you can choose any $$$a_i$$$ and divide it by $$$2$$$ rounding down (in other words, in one move you can set $$$a_i := \lfloor\frac{a_i}{2}\rfloor$$$).You can perform such an operation any (possibly, zero) number of times with any $$$a_i$$$.Your task is to calculate the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.Don't forget that it is possible to have $$$a_i = 0$$$ after some operations, thus the answer always exists.
256 megabytes
import java.util.*; import java.io.*; public class Solution { static ArrayList<Integer> graph[]; static int parent[]; static boolean vis[]; static int seive[]=new int[1000001]; static int dis[]=new int[1000001]; static int subtree[]=new int[1000001]; static int N =1000001; static HashSet<String> hm=new HashSet<>(); static HashSet<String> hm1=new HashSet<>(); static int time=0; public static void main(String[] args) { Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(System.in))); StringBuilder sb=new StringBuilder(); int n=sc.nextInt(); int k=sc.nextInt(); long a[]=new long[n]; for( int i=0;i<n;i++) { a[i]=sc.nextLong(); } PriorityQueue<Long> count[]=new PriorityQueue[200001]; for( int i=0;i<200001;i++) { count[i]=new PriorityQueue<>(Collections.reverseOrder()); } for( int i=0;i<n;i++) { long x=a[i]; long op=0; count[(int)x].add(op); if(count[(int)x].size()>k) { count[(int)x].remove(); } while(x>0) { x/=2; op++; count[(int)x].add(op); if(count[(int)x].size()>k) { count[(int)x].remove(); } } } long min=Integer.MAX_VALUE; for( int x=0;x<200001;x++) { long sum=0; if(count[x].size()<k) continue; else { while(count[x].size()>0) { sum+=count[x].remove(); } } min=Math.min(min, sum); } System.out.println(min); } } class Pair { long x,y; Pair(long x, long y) { this.x=x; this.y=y; } } class myComparator implements Comparator<Pair> { public int compare(Pair a, Pair b) { return Long.compare(b.y, a.y); } }
Java
["5 3\n1 2 2 4 5", "5 3\n1 2 3 4 5", "5 3\n1 2 3 3 3"]
2 seconds
["1", "2", "0"]
null
Java 8
standard input
[ "sortings", "brute force", "math" ]
ed1a2ae733121af6486568e528fe2d84
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 50$$$) — the number of elements in the array and the number of equal numbers required. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,600
Print one integer — the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.
standard output
PASSED
b3c4ecd61d4f1237a0b06bdf76c83a34
train_002.jsonl
1567175700
The only difference between easy and hard versions is the number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. In one move you can choose any $$$a_i$$$ and divide it by $$$2$$$ rounding down (in other words, in one move you can set $$$a_i := \lfloor\frac{a_i}{2}\rfloor$$$).You can perform such an operation any (possibly, zero) number of times with any $$$a_i$$$.Your task is to calculate the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.Don't forget that it is possible to have $$$a_i = 0$$$ after some operations, thus the answer always exists.
256 megabytes
import java.util.*; import java.lang.*; // StringBuilder uses java.lang public class mainClass { public static void main(String[] args) { Scanner sc = new Scanner(System.in); StringBuilder st=new StringBuilder(); int n = sc.nextInt(); int k = sc.nextInt(); ArrayList<Integer> ok = new ArrayList<>(); ArrayList<ArrayList<Integer>> then = new ArrayList<>(); for (int t=0; t<=2*(100000);t++) { ArrayList<Integer> ne = new ArrayList<>(); then.add(ne); } for (int t=0; t<n; t++) { int r = sc.nextInt(); ok.add(r); } Collections.sort(ok); for (int elt:ok) { int l=0; while (elt>0) { then.get(elt).add(l); l++; elt/=2; } then.get(0).add(l); } int ans=1000000000; for (int i=0;i<=2*(100000);i++) { if (then.get(i).size()>=k) { int okthen=0; for (int j=0;j<k;j++) { okthen+=then.get(i).get(j); } ans=Math.min(okthen,ans); } } System.out.println(ans); } }
Java
["5 3\n1 2 2 4 5", "5 3\n1 2 3 4 5", "5 3\n1 2 3 3 3"]
2 seconds
["1", "2", "0"]
null
Java 8
standard input
[ "sortings", "brute force", "math" ]
ed1a2ae733121af6486568e528fe2d84
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 50$$$) — the number of elements in the array and the number of equal numbers required. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,600
Print one integer — the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.
standard output
PASSED
fc7b884b16d553fc5b63b6af8dec6036
train_002.jsonl
1567175700
The only difference between easy and hard versions is the number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. In one move you can choose any $$$a_i$$$ and divide it by $$$2$$$ rounding down (in other words, in one move you can set $$$a_i := \lfloor\frac{a_i}{2}\rfloor$$$).You can perform such an operation any (possibly, zero) number of times with any $$$a_i$$$.Your task is to calculate the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.Don't forget that it is possible to have $$$a_i = 0$$$ after some operations, thus the answer always exists.
256 megabytes
// Change Of Plans BABY.... Change Of Plans // import java.io.*; import java.util.*; import static java.lang.Math.*; public class equalizingbyDivision { static void MainSolution() { n = ni(); k = ni(); int ar[] = new int[n]; for (int i = 0; i < n; i++) ar[i] = ni(); ArrayList<Integer> fac[]=new ArrayList[200006]; for(int i=0;i<=200005;i++)fac[i]=new ArrayList<>(); for(int i=0;i<n;i++){ int c=0; while(ar[i]>0){ fac[ar[i]].add(c); ar[i]/=2; c++; } } int min=Integer.MAX_VALUE; for(int i=0;i<200006;i++){ if(fac[i].size()<k)continue; Collections.sort(fac[i]); int tempc=0; for(int j=0;j<k;j++)tempc += fac[i].get(j); min=min(min,tempc); //pl(min); } pl(min); } /*----------------------------------------------------------------------------------------------------------------*/ //THE DON'T CARE ZONE BEGINS HERE...\\ static int mod9 = 1_000_000_007; static int n, m, l, k, t; static AwesomeInput input = new AwesomeInput(System.in); static PrintWriter pw = new PrintWriter(System.out, true); // The Awesome Input Code is a fast IO method // static class AwesomeInput { private InputStream letsDoIT; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private AwesomeInput(InputStream incoming) { this.letsDoIT = incoming; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = letsDoIT.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } private long ForLong() { 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; } private String ForString() { 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 interface SpaceCharFilter { boolean isSpaceChar(int ch); } } // functions to take input// static int ni() { return (int) input.ForLong(); } static String ns() { return input.ForString(); } static long nl() { return input.ForLong(); } static double nd() throws IOException { return Double.parseDouble(new BufferedReader(new InputStreamReader(System.in)).readLine()); } //functions to give output static void pl() { pw.println(); } static void p(Object o) { pw.print(o + " "); } static void pws(Object o) { pw.print(o + ""); } static void pl(Object o) { pw.println(o); } // Fast Sort is Radix Sort public static int[] fastSort(int[] f) { int n = f.length; 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 void main(String[] args) { //threading has been used to increase the stack size. new Thread(null, null, "Vengeance", 1 << 25) //the last parameter is stack size desired. { public void run() { try { double s = System.currentTimeMillis(); MainSolution(); //pl(("\nExecution Time : " + ((double) System.currentTimeMillis() - s) / 1000) + " s"); pw.flush(); pw.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } }.start(); } }
Java
["5 3\n1 2 2 4 5", "5 3\n1 2 3 4 5", "5 3\n1 2 3 3 3"]
2 seconds
["1", "2", "0"]
null
Java 8
standard input
[ "sortings", "brute force", "math" ]
ed1a2ae733121af6486568e528fe2d84
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 50$$$) — the number of elements in the array and the number of equal numbers required. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,600
Print one integer — the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.
standard output
PASSED
2b2afaaa439ff64cb6aa2d2d6e7d5c94
train_002.jsonl
1567175700
The only difference between easy and hard versions is the number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. In one move you can choose any $$$a_i$$$ and divide it by $$$2$$$ rounding down (in other words, in one move you can set $$$a_i := \lfloor\frac{a_i}{2}\rfloor$$$).You can perform such an operation any (possibly, zero) number of times with any $$$a_i$$$.Your task is to calculate the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.Don't forget that it is possible to have $$$a_i = 0$$$ after some operations, thus the answer always exists.
256 megabytes
/* package whatever; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Ideone { public static void main (String[] args) throws java.lang.Exception { // your code goes here BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n=Integer.parseInt(st.nextToken()),k=Integer.parseInt(st.nextToken()); st = new StringTokenizer(br.readLine()); int[] a=new int[n]; for(int i=0;i<n;i++)a[i]=Integer.parseInt(st.nextToken()); sort(a,0,n-1); // System.out.println(Arrays.toString(a)); int l=0,h=4000000; int ans=h; while(l<=h){ int m=(int)(((long)l+h)/2); if(check(a,k,m)){ans=m;h=m-1;} else l=m+1; // System.out.println(m+" m"); } System.out.println(ans); } public static boolean check(int[] a,int k,int steps){ int[] freq=new int[300000],cost=new int[300000]; for(int i=0;i<a.length;i++){ int t=a[i]; int c=0; while(t>0){ freq[t]++; cost[t]+=c; if(freq[t]==k){ if(cost[t]<=steps)return true; } t/=2; c+=1; } } return false; } static void merge(int arr[], int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ int L[] = new int [n1]; int R[] = new int [n2]; /*Copy data to temp arrays*/ for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } // Main function that sorts arr[l..r] using // merge() static void sort(int arr[], int l, int r) { if (l < r) { // Find the middle point int m = (l+r)/2; // Sort first and second halves sort(arr, l, m); sort(arr , m+1, r); // Merge the sorted halves merge(arr, l, m, r); } } }
Java
["5 3\n1 2 2 4 5", "5 3\n1 2 3 4 5", "5 3\n1 2 3 3 3"]
2 seconds
["1", "2", "0"]
null
Java 8
standard input
[ "sortings", "brute force", "math" ]
ed1a2ae733121af6486568e528fe2d84
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 50$$$) — the number of elements in the array and the number of equal numbers required. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,600
Print one integer — the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.
standard output
PASSED
b140f2d5bc215cbe6d6c7f5552b71e5c
train_002.jsonl
1567175700
The only difference between easy and hard versions is the number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. In one move you can choose any $$$a_i$$$ and divide it by $$$2$$$ rounding down (in other words, in one move you can set $$$a_i := \lfloor\frac{a_i}{2}\rfloor$$$).You can perform such an operation any (possibly, zero) number of times with any $$$a_i$$$.Your task is to calculate the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.Don't forget that it is possible to have $$$a_i = 0$$$ after some operations, thus the answer always exists.
256 megabytes
import java.io.*; import java.util.Random; import java.math.BigInteger; import java.util.*; public class test { public static void main(String[] args) throws IOException { InputStream inputStream = System.in; OutputStream outputStream = System.out; PrintWriter out = new PrintWriter(outputStream); InputReader in = new InputReader(inputStream); // for(int i=4;i<=4;i++) { // InputStream uinputStream = new FileInputStream("leftout.in"); // String f = i+".in"; // InputStream uinputStream = new FileInputStream(f); // InputReader in = new InputReader(uinputStream); // PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("leftout.out"))); Task t = new Task(); t.solve(in, out); out.close(); // } } static class Task { public void solve(InputReader in, PrintWriter out) throws IOException { int n = in.nextInt(); int k = in.nextInt(); TreeMap<Integer,ArrayList<Integer>> mp = new TreeMap<Integer,ArrayList<Integer>>(); int arr[] = new int[n]; for(int i=0;i<n;i++) { int t = in.nextInt(); ArrayList<Integer> tmp = new ArrayList<Integer>(); if(mp.containsKey(t)) tmp = mp.get(t); tmp.add(0); mp.put(t, tmp); arr[i] = t; } int min = Integer.MAX_VALUE; while(!mp.isEmpty()) { int big = mp.lastKey(); ArrayList<Integer> tmp = mp.get(big); if(tmp.size()>=k) { Collections.sort(tmp); int cnt = 0; for(int i=0;i<k;i++) { int v = tmp.get(i); cnt += v; } if(cnt<min) min = cnt; } for(int i=0;i<tmp.size();i++) tmp.set(i, tmp.get(i)+1); if(mp.containsKey(big/2)) { mp.get(big/2).addAll(tmp); }else { mp.put(big/2, tmp); } mp.remove(big); } out.println(min); } int gcd(int a, int b) { if(b==0) return a; else return gcd(b,a%b); } long gcd(long a, long b) { if(b==0) return a; else return gcd(b,a%b); } List<List<Integer>> convert (int arr[][]){ List<List<Integer>> ret = new ArrayList<List<Integer>>(); int n = arr.length; for(int i=0;i<n;i++) { ArrayList<Integer> tmp = new ArrayList<Integer>(); for(int j=0;j<arr[i].length;j++) { tmp.add(arr[i][j]); } ret.add(tmp); } return ret; } public int numPrimeArrangements(int n) { int c = 0; for(int i=1;i<=n;i++) { if(is_prime(i)) c++; } int a = cal(c); int b = cal(n-c); long ret = a; ret*=b; ret%=1000000007; return (int)ret; } int cal(int n) { int x = 1000000007; long s = 1; for(long i=1;i<=n;i++) { s*=i; s%=x; } return (int) s; } boolean is_prime(int a) { if(a==1) return false; if(a==2||a==3) return true; for(int i=2;i<=Math.sqrt(a);i++) { if(a%i==0) return false; } return true; } class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public int GCD(int a, int b) { if (b==0) return a; return GCD(b,a%b); } } static class ArrayUtils { static final long seed = System.nanoTime(); static final Random rand = new Random(seed); public static void sort(int[] a) { shuffle(a); Arrays.sort(a); } public static void shuffle(int[] a) { for (int i = 0; i < a.length; i++) { int j = rand.nextInt(i + 1); int t = a[i]; a[i] = a[j]; a[j] = t; } } public static void sort(long[] a) { shuffle(a); Arrays.sort(a); } public static void shuffle(long[] a) { for (int i = 0; i < a.length; i++) { int j = rand.nextInt(i + 1); long t = a[i]; a[i] = a[j]; a[j] = t; } } } static class BIT{ int arr[]; int n; public BIT(int a) { n=a; arr = new int[n]; } int sum(int p) { int s=0; while(p>0) { s+=arr[p]; p-=p&(-p); } return s; } void add(int p, int v) { while(p<n) { arr[p]+=v; p+=p&(-p); } } } static class DSU{ int[] arr; int[] sz; public DSU(int n) { arr = new int[n]; sz = new int[n]; for(int i=0;i<n;i++) arr[i] = i; Arrays.fill(sz, 1); } public int find(int a) { if(arr[a]!=a) arr[a] = find(arr[a]); return arr[a]; } public void union(int a, int b) { int x = find(a); int y = find(b); if(x==y) return; arr[x] = y; sz[y] += sz[x]; } public int size(int x) { return sz[find(x)]; } } static class MinHeap<Key> implements Iterable<Key> { private int maxN; private int n; private int[] pq; private int[] qp; private Key[] keys; private Comparator<Key> comparator; public MinHeap(int capacity){ if (capacity < 0) throw new IllegalArgumentException(); this.maxN = capacity; n=0; pq = new int[maxN+1]; qp = new int[maxN+1]; keys = (Key[]) new Object[capacity+1]; Arrays.fill(qp, -1); } public MinHeap(int capacity, Comparator<Key> c){ if (capacity < 0) throw new IllegalArgumentException(); this.maxN = capacity; n=0; pq = new int[maxN+1]; qp = new int[maxN+1]; keys = (Key[]) new Object[capacity+1]; Arrays.fill(qp, -1); comparator = c; } public boolean isEmpty() { return n==0; } public int size() { return n; } public boolean contains(int i) { if (i < 0 || i >= maxN) throw new IllegalArgumentException(); return qp[i] != -1; } public int peekIdx() { if (n == 0) throw new NoSuchElementException("Priority queue underflow"); return pq[1]; } public Key peek(){ if(isEmpty()) throw new NoSuchElementException("Priority queue underflow"); return keys[pq[1]]; } public int poll(){ if(isEmpty()) throw new NoSuchElementException("Priority queue underflow"); int min = pq[1]; exch(1,n--); down(1); assert min==pq[n+1]; qp[min] = -1; keys[min] = null; pq[n+1] = -1; return min; } public void update(int i, Key key) { if (i < 0 || i >= maxN) throw new IllegalArgumentException(); if (!contains(i)) { this.add(i, key); }else { keys[i] = key; up(qp[i]); down(qp[i]); } } private void add(int i, Key x){ if (i < 0 || i >= maxN) throw new IllegalArgumentException(); if (contains(i)) throw new IllegalArgumentException("index is already in the priority queue"); n++; qp[i] = n; pq[n] = i; keys[i] = x; up(n); } private void up(int k){ while(k>1&&less(k,k/2)){ exch(k,k/2); k/=2; } } private void down(int k){ while(2*k<=n){ int j=2*k; if(j<n&&less(j+1,j)) j++; if(less(k,j)) break; exch(k,j); k=j; } } public boolean less(int i, int j){ if (comparator == null) { return ((Comparable<Key>) keys[pq[i]]).compareTo(keys[pq[j]]) < 0; } else { return comparator.compare(keys[pq[i]], keys[pq[j]]) < 0; } } public void exch(int i, int j){ int swap = pq[i]; pq[i] = pq[j]; pq[j] = swap; qp[pq[i]] = i; qp[pq[j]] = j; } @Override public Iterator<Key> iterator() { // TODO Auto-generated method stub return null; } } private static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int zcurChar; private int znumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (znumChars == -1) throw new InputMismatchException(); if (zcurChar >= znumChars) { zcurChar = 0; try { znumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (znumChars <= 0) return -1; } return buf[zcurChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public 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 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 nextString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } public int[] readIntArray(int n) { int[] ret = new int[n]; for (int i = 0; i < n; i++) { ret[i] = nextInt(); } return ret; } } static class Dumper { static void print_int_arr(int[] arr) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); System.out.println("---------------------"); } static void print_char_arr(char[] arr) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); System.out.println("---------------------"); } static void print_double_arr(double[] arr) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); System.out.println("---------------------"); } static void print_2d_arr(int[][] arr, int x, int y) { for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { System.out.print(arr[i][j] + " "); } System.out.println(); } System.out.println(); System.out.println("---------------------"); } static void print_2d_arr(boolean[][] arr, int x, int y) { for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { System.out.print(arr[i][j] + " "); } System.out.println(); } System.out.println(); System.out.println("---------------------"); } static void print(Object o) { System.out.println(o.toString()); } static void getc() { System.out.println("here"); } } }
Java
["5 3\n1 2 2 4 5", "5 3\n1 2 3 4 5", "5 3\n1 2 3 3 3"]
2 seconds
["1", "2", "0"]
null
Java 8
standard input
[ "sortings", "brute force", "math" ]
ed1a2ae733121af6486568e528fe2d84
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 50$$$) — the number of elements in the array and the number of equal numbers required. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,600
Print one integer — the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.
standard output
PASSED
38ca7895263bfe24d98f12f75804bcca
train_002.jsonl
1567175700
The only difference between easy and hard versions is the number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. In one move you can choose any $$$a_i$$$ and divide it by $$$2$$$ rounding down (in other words, in one move you can set $$$a_i := \lfloor\frac{a_i}{2}\rfloor$$$).You can perform such an operation any (possibly, zero) number of times with any $$$a_i$$$.Your task is to calculate the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.Don't forget that it is possible to have $$$a_i = 0$$$ after some operations, thus the answer always exists.
256 megabytes
import java.util.*; import java.math.*; public class Main{ private static int max=200*1000+5; public static void main(String args[]){ Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int k=sc.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++){ a[i]=sc.nextInt(); } List<Integer> [] vals=new ArrayList[max]; for(int i=0;i<max;i++){ vals[i]=new ArrayList<Integer>(); } for(int i:a){ int y=i; int cur=0; while(y>0){ vals[y].add(cur); y=y/2; cur++; } } int res=Integer.MAX_VALUE; for(List<Integer> l:vals){ if(l.size()>=k){ Collections.sort(l); int t=0; for(int i=0;i<k;i++){ t+=l.get(i); } res=Math.min(t,res); } } System.out.println(res); } }
Java
["5 3\n1 2 2 4 5", "5 3\n1 2 3 4 5", "5 3\n1 2 3 3 3"]
2 seconds
["1", "2", "0"]
null
Java 8
standard input
[ "sortings", "brute force", "math" ]
ed1a2ae733121af6486568e528fe2d84
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 50$$$) — the number of elements in the array and the number of equal numbers required. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,600
Print one integer — the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.
standard output
PASSED
5f004ab70363ba16ff1ee426d804c5d3
train_002.jsonl
1567175700
The only difference between easy and hard versions is the number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. In one move you can choose any $$$a_i$$$ and divide it by $$$2$$$ rounding down (in other words, in one move you can set $$$a_i := \lfloor\frac{a_i}{2}\rfloor$$$).You can perform such an operation any (possibly, zero) number of times with any $$$a_i$$$.Your task is to calculate the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.Don't forget that it is possible to have $$$a_i = 0$$$ after some operations, thus the answer always exists.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.StringTokenizer; @SuppressWarnings("unchecked") public class Problem_D { static final int INF = Integer.MAX_VALUE / 2; public static void main(String[] args) { InputReader in = new InputReader(); int N = in.nextInt(); int K = in.nextInt(); int[] A = new int[N]; for (int i = 0; i < N; i++) { A[i] = in.nextInt(); } List<Integer>[] list = new List[200001]; for (int i = 0; i < list.length; i++) { list[i] = new ArrayList<>(); } for (int i = 0; i < N; i++) { list[A[i]].add(0); } int ans = INF; for (int i = list.length - 1; i >= 0; i--) { if (list[i].size() >= K) { Collections.sort(list[i]); int cnt = 0; for (int j = 0; j < K; j++) { cnt += list[i].get(j); } ans = Math.min(ans, cnt); } if (i == 0) { break; } for (int j = list[i].size() - 1; j >= 0; j--) { list[i / 2].add(list[i].remove(j) + 1); } } System.out.println(ans); } static class InputReader { public BufferedReader reader; public StringTokenizer st; public InputReader() { reader = new BufferedReader(new InputStreamReader(System.in)); } public String next() { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(nextLine()); } return st.nextToken(); } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { e.printStackTrace(); } return null; } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["5 3\n1 2 2 4 5", "5 3\n1 2 3 4 5", "5 3\n1 2 3 3 3"]
2 seconds
["1", "2", "0"]
null
Java 8
standard input
[ "sortings", "brute force", "math" ]
ed1a2ae733121af6486568e528fe2d84
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 50$$$) — the number of elements in the array and the number of equal numbers required. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,600
Print one integer — the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.
standard output
PASSED
c88a147f32bfc49ab81b10ba0ef6d334
train_002.jsonl
1567175700
The only difference between easy and hard versions is the number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. In one move you can choose any $$$a_i$$$ and divide it by $$$2$$$ rounding down (in other words, in one move you can set $$$a_i := \lfloor\frac{a_i}{2}\rfloor$$$).You can perform such an operation any (possibly, zero) number of times with any $$$a_i$$$.Your task is to calculate the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.Don't forget that it is possible to have $$$a_i = 0$$$ after some operations, thus the answer always exists.
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Collections; import java.util.LinkedList; import java.util.StringTokenizer; public class Round582D2 { public static void main(String[] args) { // TODO Auto-generated method stub out =new PrintWriter(new BufferedOutputStream(System.out)); FastReader s=new FastReader(); int n=s.nextInt(); int k=s.nextInt(); int[] arr=new int[n]; LinkedList<Integer>[] helper=new LinkedList[(int)2e5+10]; for(int i=0;i<helper.length;i++) { helper[i]=new LinkedList<Integer>(); } for(int i=0;i<n;i++) { arr[i]=s.nextInt(); int temp =arr[i]; int count =0; while(temp>0) { helper[temp].add(count++); temp/=2; } } int min =Integer.MAX_VALUE; for(int i=0;i<(int)2e5+10;i++) { if(helper[i].size()>=k) { Collections.sort(helper[i]); int value =0; int count=0; for(Integer x:helper[i]) { if(count<k) { value+=x; }else { break; } count++; } min =Integer.min(value, min); } } out.println(min); out.close(); } public static PrintWriter out; public static class FastReader { BufferedReader br; StringTokenizer st; //it reads the data about the specified point and divide the data about it ,it is quite fast //than using direct public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); //InputStream reads the data and decodes in character stream //It acts as bridge between byte stream and character stream } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next());//converts string to integer } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (Exception e) { e.printStackTrace(); } return str; } } }
Java
["5 3\n1 2 2 4 5", "5 3\n1 2 3 4 5", "5 3\n1 2 3 3 3"]
2 seconds
["1", "2", "0"]
null
Java 8
standard input
[ "sortings", "brute force", "math" ]
ed1a2ae733121af6486568e528fe2d84
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 50$$$) — the number of elements in the array and the number of equal numbers required. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,600
Print one integer — the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.
standard output
PASSED
37eac2eb6768eb959c0c3adfe3cc8357
train_002.jsonl
1567175700
The only difference between easy and hard versions is the number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. In one move you can choose any $$$a_i$$$ and divide it by $$$2$$$ rounding down (in other words, in one move you can set $$$a_i := \lfloor\frac{a_i}{2}\rfloor$$$).You can perform such an operation any (possibly, zero) number of times with any $$$a_i$$$.Your task is to calculate the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.Don't forget that it is possible to have $$$a_i = 0$$$ after some operations, thus the answer always exists.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.lang.management.MemoryType; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.*; import java.util.function.Function; public class Main { static final int INF = Integer.MAX_VALUE; static int mergeSort(int[] a,int [] c, int begin, int end) { int inversion=0; if(begin < end) { inversion=0; int mid = (begin + end) >>1; inversion+= mergeSort(a,c, begin, mid); inversion+=mergeSort(a, c,mid + 1, end); inversion+=merge(a,c, begin, mid, end); } return inversion; } static int merge(int[] a,int[]c, int b, int mid, int e) { int n1 = mid - b + 1; int n2 = e - mid; int[] L = new int[n1+1], R = new int[n2+1]; int[] L1 = new int[n1+1], R1 = new int[n2+1]; //inversion int inversion=0; for(int i = 0; i < n1; i++) { L[i] = a[b + i]; L1[i] = c[b + i]; // L2[i] = w[b + i]; } for(int i = 0; i < n2; i++) { R[i] = a[mid + 1 + i]; R1[i] = c[mid + 1 + i]; //R2[i] = w[mid + 1 + i]; } L[n1] = R[n2] = INF; for(int k = b, i = 0, j = 0; k <= e; k++) if(L[i] <= R[j]){ a[k] = L[i]; c[k] = L1[i]; ++i; // w[k]=L2[i++]; } else { a[k] = R[j]; c[k] = R1[j]; //w[k] = R2[j++]; ++j; inversion=inversion+(n1-i); } return inversion; } public static void main (String[]args) throws IOException { Scanner in = new Scanner(System.in); try(PrintWriter or = new PrintWriter(System.out)) { int n = in.nextInt(),k=in.nextInt(); ArrayList<Integer>[] a= new ArrayList[200005]; for (int i = 0; i < 200005; i++) { a[i]=new ArrayList<>(); } for (int i = 0; i < n; i++) { int x=in.nextInt(),c=0; a[x].add(c++); while (x>0){ x>>=1; a[x].add(c++); } a[x].add(c); } int ans=Integer.MAX_VALUE; for (int i = 0; i < 200005; i++) { if (a[i].size()<k)continue; Collections.sort(a[i]); int c=0; for (int j = 0; j < k; j++) { c+=a[i].get(j); } ans=Math.min(ans,c); } or.println(ans); } } static int getlen(int r,int l,int a){ return (r-l+1+1)/(a+1); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) { if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) { f *= 10; } } } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } } class Pair implements Comparable<Pair> { int first, second; public Pair(int first, int second) { this.first = first; this.second = second; } @Override public int compareTo(Pair o) { return first - o.first; } } class Tempo { int num; int index; public Tempo(int num, int index) { this.num = num; this.index = index; } }
Java
["5 3\n1 2 2 4 5", "5 3\n1 2 3 4 5", "5 3\n1 2 3 3 3"]
2 seconds
["1", "2", "0"]
null
Java 8
standard input
[ "sortings", "brute force", "math" ]
ed1a2ae733121af6486568e528fe2d84
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 50$$$) — the number of elements in the array and the number of equal numbers required. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,600
Print one integer — the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.
standard output
PASSED
e824bb5949b66c99bf0a3fe0e59dcecd
train_002.jsonl
1567175700
The only difference between easy and hard versions is the number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. In one move you can choose any $$$a_i$$$ and divide it by $$$2$$$ rounding down (in other words, in one move you can set $$$a_i := \lfloor\frac{a_i}{2}\rfloor$$$).You can perform such an operation any (possibly, zero) number of times with any $$$a_i$$$.Your task is to calculate the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.Don't forget that it is possible to have $$$a_i = 0$$$ after some operations, thus the answer always exists.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class Main { static final long MOD = 998244353; public static void main(String[] args) throws IOException { FastScanner sc=new FastScanner(); int N = sc.nextInt(); int K = sc.nextInt(); int[] nums = new int[N]; for (int i = 0; i < N; i++) { nums[i] = sc.nextInt(); } mergeSort(nums,nums.length,true); int[] sumToHit = new int[200001]; int[] Kleft = new int[200001]; for (int i = 0; i <= 200000; i++) { Kleft[i] = K; } for (int num: nums) { int key = num; int steps = 0; while (key > 0) { if (Kleft[key] > 0) { sumToHit[key] += steps; Kleft[key] -= 1; } key = key/2; steps++; } if (Kleft[0] > 0) { sumToHit[0] += steps; Kleft[0] -= 1; } } int bestCost = Integer.MAX_VALUE; for (int i = 0; i <= 200000; i++) { if (Kleft[i] == 0) { bestCost = Math.min(bestCost, sumToHit[i]); } } System.out.println(bestCost); } //More efficient than Arrays.sort public static void mergeSort(int[] a, int n, boolean ascending) { if (n < 2) { return; } int mid = n / 2; int[] l = new int[mid]; int[] r = new int[n - mid]; for (int i = 0; i < mid; i++) { l[i] = a[i]; } for (int i = mid; i < n; i++) { r[i - mid] = a[i]; } mergeSort(l, mid, ascending); mergeSort(r, n - mid, ascending); merge(a, l, r, mid, n - mid, ascending); } public static void merge(int[] a, int[] l, int[] r, int left, int right, boolean ascending) { int i = 0, j = 0, k = 0; while (i < left && j < right) { if ((ascending && l[i] <= r[j]) || (!ascending && l[i] >= r[j])) { a[k++] = l[i++]; } else { a[k++] = r[j++]; } } while (i < left) { a[k++] = l[i++]; } while (j < right) { a[k++] = r[j++]; } } //Sort based on which column. public static void mergeSort(int[][] a, int n, int col, boolean ascending) { if (n < 2) { return; } int mid = n / 2; int[][] l = new int[mid][a[0].length]; int[][] r = new int[n - mid][a[0].length]; for (int i = 0; i < mid; i++) { l[i] = a[i]; } for (int i = mid; i < n; i++) { r[i - mid] = a[i]; } mergeSort(l, mid, col, ascending); mergeSort(r, n - mid, col, ascending); merge(a, l, r, mid, n - mid, col, ascending); } public static void merge(int[][] a, int[][] l, int[][] r, int left, int right, int col, boolean ascending) { int i = 0, j = 0, k = 0; while (i < left && j < right) { if ((ascending && l[i][col] <= r[j][col]) || (!ascending && l[i][col] >= r[j][col])) { a[k++] = l[i++]; } else { a[k++] = r[j++]; } } while (i < left) { a[k++] = l[i++]; } while (j < right) { a[k++] = r[j++]; } } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { 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 Node { public int n; public HashSet<Node> children; public Node(int n) { this.n = n; children = new HashSet<Node>(); } public void addChild(Node node) { children.add(node); } } class BinaryIndexedTree { public long[] arr; public BinaryIndexedTree (int N) { arr = new long[N+1]; arr[0] = 0; } //add k to the i-th element. public void add(long k, int i) { int node = i+1; while (node < arr.length) { arr[node] += k; node += node & (-node); } } //sum up the elements from input[s_i] to input[e_i], from [s_i,e_i). public long sum(int s_i, int e_i) { return sum(e_i) - sum(s_i); } public long sum(int i) { long total = 0; int node = i; while (node > 0) { total += arr[node]; node -= node & (-node); } return total; } } class DSU { public int N; public int[] parent; public int[] rank; public int count; public DSU(int numNodes) { N = numNodes; parent = new int[N]; rank = new int[N]; for (int i = 0; i < N; i++) { parent[i] = i; rank[i] = 1; } count = numNodes; } public boolean isConnected(int p, int q) { return root(p) == root(q); } public int root(int p) { while (p != parent[p]) p = parent[p]; return p; } //only connect p and q if they are disjointed. public void connect(int p, int q) { int rootP = root(p); int rootQ = root(q); if (rank[rootP] >= rank[rootQ]) { parent[rootQ] = rootP; rank[rootP] += rank[rootQ]; } else if (rank[rootQ] > rank[rootP]) { parent[rootP] = rootQ; rank[rootQ] += rank[rootP]; } count--; } }
Java
["5 3\n1 2 2 4 5", "5 3\n1 2 3 4 5", "5 3\n1 2 3 3 3"]
2 seconds
["1", "2", "0"]
null
Java 8
standard input
[ "sortings", "brute force", "math" ]
ed1a2ae733121af6486568e528fe2d84
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 50$$$) — the number of elements in the array and the number of equal numbers required. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,600
Print one integer — the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.
standard output
PASSED
24d92c4bfd798be1d57a1f5bdc2b120e
train_002.jsonl
1567175700
The only difference between easy and hard versions is the number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. In one move you can choose any $$$a_i$$$ and divide it by $$$2$$$ rounding down (in other words, in one move you can set $$$a_i := \lfloor\frac{a_i}{2}\rfloor$$$).You can perform such an operation any (possibly, zero) number of times with any $$$a_i$$$.Your task is to calculate the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.Don't forget that it is possible to have $$$a_i = 0$$$ after some operations, thus the answer always exists.
256 megabytes
import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; public class Test2 { static int minOperations(int n, int k, int d, int[] a) { int MAX = 1000000; // Stores the number of moves // required to obtain respective // values from the given array List<Integer>[] v = new ArrayList[MAX]; for (int i = 0; i < v.length; i++) { v[i] = new ArrayList<Integer>(); } for (int i = 0; i < n; i++) { int cnt = 0; v[a[i]].add(0); while (a[i] > 0) { a[i] /= d; cnt++; v[a[i]].add(cnt); } } int ans = Integer.MAX_VALUE; for (int i = 0; i < MAX; i++) { if (v[i].size() >= k) { int move = 0; Collections.sort(v[i]); for (int j = 0; j < k; j++) { move += v[i].get(j); } ans = Math.min(ans, move); } } return ans; } public static void main(String[] args) throws IOException { Scanner bufferedReader = new Scanner(System.in); int arrCount = bufferedReader.nextInt(); int threshold = bufferedReader.nextInt(); int [] a = new int [arrCount]; for (int i = 0; i < arrCount; i++) { a[i] = bufferedReader.nextInt(); } // int d = bufferedReader.nextInt(); int result = minOperations(arrCount, threshold, 2, a); System.out.println(result); bufferedReader.close(); } }
Java
["5 3\n1 2 2 4 5", "5 3\n1 2 3 4 5", "5 3\n1 2 3 3 3"]
2 seconds
["1", "2", "0"]
null
Java 8
standard input
[ "sortings", "brute force", "math" ]
ed1a2ae733121af6486568e528fe2d84
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 50$$$) — the number of elements in the array and the number of equal numbers required. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,600
Print one integer — the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.
standard output
PASSED
f07082de0d755e811cfcc106811acc7b
train_002.jsonl
1567175700
The only difference between easy and hard versions is the number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. In one move you can choose any $$$a_i$$$ and divide it by $$$2$$$ rounding down (in other words, in one move you can set $$$a_i := \lfloor\frac{a_i}{2}\rfloor$$$).You can perform such an operation any (possibly, zero) number of times with any $$$a_i$$$.Your task is to calculate the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.Don't forget that it is possible to have $$$a_i = 0$$$ after some operations, thus the answer always exists.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.FilterInputStream; import java.io.BufferedInputStream; import java.util.Collections; import java.util.ArrayList; import java.io.InputStream; /** * @author khokharnikunj8 */ public class Main { public static void main(String[] args) { new Thread(null, new Runnable() { public void run() { new Main().solve(); } }, "1", 1 << 26).start(); } void solve() { InputStream inputStream = System.in; OutputStream outputStream = System.out; ScanReader in = new ScanReader(inputStream); PrintWriter out = new PrintWriter(outputStream); D2EqualizingByDivisionHardVersion solver = new D2EqualizingByDivisionHardVersion(); solver.solve(1, in, out); out.close(); } static class D2EqualizingByDivisionHardVersion { public void solve(int testNumber, ScanReader in, PrintWriter out) { int n = in.scanInt(); int k = in.scanInt(); ArrayList<Integer>[] arrayLists = new ArrayList[2 * 100005]; for (int i = 0; i < 2 * 100005; i++) arrayLists[i] = new ArrayList<>(); for (int i = 0; i < n; i++) { int tmep = in.scanInt(); int step = 0; while (tmep > 0) { arrayLists[tmep].add(step); step++; tmep >>= 1; } } int answer = Integer.MAX_VALUE; for (int i = 0; i <= 2 * 100000; i++) { if (arrayLists[i].size() >= k) { int ans = 0; Collections.sort(arrayLists[i]); for (int j = 0; j < k; j++) ans += arrayLists[i].get(j); answer = Math.min(answer, ans); } } out.println(answer); } } static class ScanReader { private byte[] buf = new byte[4 * 1024]; private int index; private BufferedInputStream in; private int total; public ScanReader(InputStream inputStream) { in = new BufferedInputStream(inputStream); } private int scan() { if (index >= total) { index = 0; try { total = in.read(buf); } catch (Exception e) { e.printStackTrace(); } if (total <= 0) return -1; } return buf[index++]; } public int scanInt() { int integer = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { integer *= 10; integer += n - '0'; n = scan(); } } return neg * integer; } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; else return false; } } }
Java
["5 3\n1 2 2 4 5", "5 3\n1 2 3 4 5", "5 3\n1 2 3 3 3"]
2 seconds
["1", "2", "0"]
null
Java 8
standard input
[ "sortings", "brute force", "math" ]
ed1a2ae733121af6486568e528fe2d84
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 50$$$) — the number of elements in the array and the number of equal numbers required. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,600
Print one integer — the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.
standard output
PASSED
ebcfc2247812b54e4070606ab8b73341
train_002.jsonl
1567175700
The only difference between easy and hard versions is the number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. In one move you can choose any $$$a_i$$$ and divide it by $$$2$$$ rounding down (in other words, in one move you can set $$$a_i := \lfloor\frac{a_i}{2}\rfloor$$$).You can perform such an operation any (possibly, zero) number of times with any $$$a_i$$$.Your task is to calculate the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.Don't forget that it is possible to have $$$a_i = 0$$$ after some operations, thus the answer always exists.
256 megabytes
import java.io.*; import java.sql.Array; import java.util.*; import java.util.concurrent.ThreadLocalRandom; @SuppressWarnings("Duplicates") public class solveLOL { FastScanner in; PrintWriter out; boolean systemIO = true, multitests = false; int INF = Integer.MAX_VALUE / 2; void solve() { int n = in.nextInt(), k = in.nextInt(); //TreeSet<X> set = new TreeSet<>((o1, o2) -> o1.x != o2.x ? Long.compare(o1.x, o2.x) : (o1.need != o2.need ? Long.compare(o1.need, o2.need) : Long.compare(o1.id, o2.id))); ArrayList<X> set = new ArrayList<>(); for (int i = 0; i < n; i++) { int pp = in.nextInt(), o = 0; while (pp != 1) { set.add(new X(pp, o, i)); pp /= 2; o++; } set.add(new X(pp, o, i)); } Collections.sort(set, (o1, o2) -> o1.x != o2.x ? Long.compare(o1.x, o2.x) : (o1.need != o2.need ? Long.compare(o1.need, o2.need) : Long.compare(o1.id, o2.id))); int min = INF, size = set.size(); for (int i = 0; i < size; i++) { int c = set.get(i).x, kk = k, l = 0; while (kk > 0 && i < size) { if (set.get(i).x != c) { i--; break; } l += set.get(i).need; kk--; i++; } if (kk == 0) { min = Math.min(min, l); i--; } while (i + 1 < size && set.get(i + 1).x == c) { i++; } } out.println(min); } class X { int x, need, id; X(int a, int b, int c) { this.x = a; this.need = b; this.id = c; } } void shuffleArray(long[] ar) { Random rnd = ThreadLocalRandom.current(); for (int i = ar.length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); long a = ar[index]; ar[index] = ar[i]; ar[i] = a; } } void printArray(long[] ar) { for (long k : ar) { System.out.print(k + " "); } System.out.println(); } void reverseArray(long[] ar) { for (int i = 0, j = ar.length - 1; i < j; i++, j--) { long a = ar[i]; ar[i] = ar[j]; ar[j] = a; } } private void run() throws IOException { if (systemIO) { in = new solveLOL.FastScanner(System.in); out = new PrintWriter(System.out); } else { in = new solveLOL.FastScanner(new File("input.txt")); out = new PrintWriter(new File("output.txt")); } for (int t = multitests ? in.nextInt() : 1; t-- > 0; ) solve(); out.close(); } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String nextLine() { try { return br.readLine(); } catch (IOException e) { return null; } } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } public static void main(String[] arg) throws IOException { new solveLOL().run(); } }
Java
["5 3\n1 2 2 4 5", "5 3\n1 2 3 4 5", "5 3\n1 2 3 3 3"]
2 seconds
["1", "2", "0"]
null
Java 8
standard input
[ "sortings", "brute force", "math" ]
ed1a2ae733121af6486568e528fe2d84
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 50$$$) — the number of elements in the array and the number of equal numbers required. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,600
Print one integer — the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.
standard output
PASSED
f09da1e3714bc469227dd42ad2927e64
train_002.jsonl
1567175700
The only difference between easy and hard versions is the number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. In one move you can choose any $$$a_i$$$ and divide it by $$$2$$$ rounding down (in other words, in one move you can set $$$a_i := \lfloor\frac{a_i}{2}\rfloor$$$).You can perform such an operation any (possibly, zero) number of times with any $$$a_i$$$.Your task is to calculate the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.Don't forget that it is possible to have $$$a_i = 0$$$ after some operations, thus the answer always exists.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; import static java.lang.Math.min; public class D2_1312 { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] __) { FastReader sc = new FastReader(); int n = sc.nextInt(), k = sc.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = sc.nextInt(); Map<Integer, List<Integer>> map = new HashMap<>(); for (int x : arr) { int cnt = 0; while (x > 0) { if (map.containsKey(x)) map.get(x).add(cnt); else { List<Integer> al = new ArrayList<>(); al.add(cnt); map.put(x, al); } cnt++; x /= 2; } } int ans = Integer.MAX_VALUE; for (int x : map.keySet()) { List<Integer> cur = map.get(x); if (cur.size() >= k) { Collections.sort(cur); int su = 0; for (int i = 0; i < k; i++) su += cur.get(i); ans = min(ans, su); } } System.out.println(ans); } }
Java
["5 3\n1 2 2 4 5", "5 3\n1 2 3 4 5", "5 3\n1 2 3 3 3"]
2 seconds
["1", "2", "0"]
null
Java 8
standard input
[ "sortings", "brute force", "math" ]
ed1a2ae733121af6486568e528fe2d84
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 50$$$) — the number of elements in the array and the number of equal numbers required. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,600
Print one integer — the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.
standard output
PASSED
59f1c933b22d195dd7622f21fcca2376
train_002.jsonl
1567175700
The only difference between easy and hard versions is the number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. In one move you can choose any $$$a_i$$$ and divide it by $$$2$$$ rounding down (in other words, in one move you can set $$$a_i := \lfloor\frac{a_i}{2}\rfloor$$$).You can perform such an operation any (possibly, zero) number of times with any $$$a_i$$$.Your task is to calculate the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.Don't forget that it is possible to have $$$a_i = 0$$$ after some operations, thus the answer always exists.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader sc = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(1, sc, out); out.close(); } static class Task { public static final int Max=(1<<18)+10; public void solve(int testNumber, InputReader sc, PrintWriter out) { int n=sc.nextInt(); int k=sc.nextInt(); int[] a=new int[n+1]; int[] cnt=new int[Max]; int[] pre=new int[Max]; for(int i=1;i<=n;i++) { a[i]=sc.nextInt(); cnt[a[i]]++; } int index=0; int s=cnt[Max-1]; for(int i=Max-2;i>=0;i--) { s+=cnt[i]; if(s>=k) { index=i; break; } } pre[0]=cnt[0]; for(int i=1;i<Max;i++) pre[i]=pre[i-1]+cnt[i]; int ans=Integer.MAX_VALUE; for(int i=index;i>=0;i--) { int now=k-Math.min(k,cnt[i]); int x=1; int count=0; boolean jud=now==0; if(i==0) { while(now>0&&i*(1<<x)+(1<<x)<Max) { int e=1<<x; int temp=pre[Math.min(Max-1, e*i+e-1)]-pre[Math.max(e*i+(e/2)-1, 0)]; count+=Math.min(now, temp)*x; now-=Math.min(now, temp); if(now==0) jud=true; x++; } if(jud) ans=Math.min(ans, count); continue; } while(now>0&&i*(1<<x)+(1<<x)<Max) { int e=1<<x; int temp=pre[Math.min(Max-1, e*i+e-1)]-pre[Math.max(e*i-1, 0)]; count+=Math.min(now, temp)*x; now-=Math.min(now, temp); if(now==0) jud=true; x++; } if(!jud) continue; ans=Math.min(ans, count); } out.println(ans); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["5 3\n1 2 2 4 5", "5 3\n1 2 3 4 5", "5 3\n1 2 3 3 3"]
2 seconds
["1", "2", "0"]
null
Java 8
standard input
[ "sortings", "brute force", "math" ]
ed1a2ae733121af6486568e528fe2d84
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 50$$$) — the number of elements in the array and the number of equal numbers required. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,600
Print one integer — the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.
standard output
PASSED
25bb1a44649ef7444840374b41997eff
train_002.jsonl
1567175700
The only difference between easy and hard versions is the number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. In one move you can choose any $$$a_i$$$ and divide it by $$$2$$$ rounding down (in other words, in one move you can set $$$a_i := \lfloor\frac{a_i}{2}\rfloor$$$).You can perform such an operation any (possibly, zero) number of times with any $$$a_i$$$.Your task is to calculate the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.Don't forget that it is possible to have $$$a_i = 0$$$ after some operations, thus the answer always exists.
256 megabytes
// package cf1213; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.math.BigInteger; import java.util.Arrays; import java.util.InputMismatchException; import java.util.Random; public class CFD2a { private static final String INPUT = "5 3\n" + "1 2 7 8 200000\n"; private static final int MOD = 1_000_000_007; private PrintWriter out; private FastScanner sc; public static void main(String[] args) { new CFD2a().run(); } public void run() { sc = new FastScanner(oj ? System.in : new ByteArrayInputStream(INPUT.getBytes())); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis() - s + "ms"); } private void solve() { int n = sc.nextInt(); int k = sc.nextInt(); int[] a = readIntArray(n); int[] qs = new int[200_001]; int[] cans = new int[200_001]; sort(a); int ans = Integer.MAX_VALUE; for (int i = 0; i < 20; i++) { for (int j = a.length - 1; j >= 0; j--) { int nr = a[j] >> i; if (nr == 0) break; if (qs[nr] < k) { qs[nr]++; cans[nr] += i; if (qs[nr] == k) { ans = Math.min(ans, cans[nr]); } } } } out.println(ans); } //******************************************************************************************** //******************************************************************************************** //******************************************************************************************** static class SolutionFailedException extends Exception { int code; public SolutionFailedException(int code) { this.code = code; } } int [] sort(int [] a) { final int SHIFT = 16, MASK = (1 << SHIFT) - 1, SIZE = (1 << SHIFT) + 1; int n = a.length, ta [] = new int [n], ai [] = new int [SIZE]; for (int i = 0; i < n; ai[(a[i] & MASK) + 1]++, i++); for (int i = 1; i < SIZE; ai[i] += ai[i - 1], i++); for (int i = 0; i < n; ta[ai[a[i] & MASK]++] = a[i], i++); int [] t = a; a = ta; ta = t; ai = new int [SIZE]; for (int i = 0; i < n; ai[(a[i] >> SHIFT) + 1]++, i++); for (int i = 1; i < SIZE; ai[i] += ai[i - 1], i++); for (int i = 0; i < n; ta[ai[a[i] >> SHIFT]++] = a[i], i++); return ta; } private static void shuffle(int[] array) { Random random = new Random(); for (int i = array.length - 1; i > 0; i--) { int index = random.nextInt(i + 1); int temp = array[index]; array[index] = array[i]; array[i] = temp; } } /** * If searched element doesn't exist, returns index of first element which is bigger than searched value.<br> * If searched element is bigger than any array element function returns first index after last element.<br> * If searched element is lower than any array element function returns index of first element.<br> * If there are many values equals searched value function returns first occurrence.<br> */ private static int lowerBound(long[] arr, long key) { int lo = 0; int hi = arr.length - 1; while (lo < hi) { int mid = (lo + hi) / 2; if (key <= arr[mid]) { hi = mid - 1; } else { lo = mid + 1; } } return arr[lo] < key ? lo + 1 : lo; } /** * Returns index of first element which is grater than searched value. * If searched element is bigger than any array element, returns first index after last element. */ private static int upperBound(long[] arr, long key) { int lo = 0; int hi = arr.length - 1; while (lo < hi) { int mid = (lo + hi) / 2; if (key >= arr[mid]) { lo = mid + 1; } else { hi = mid; } } return arr[lo] <= key ? lo + 1 : lo; } private static int ceil(double d) { int ret = (int) d; return ret == d ? ret : ret + 1; } private static int round(double d) { return (int) (d + 0.5); } private static int gcd(int a, int b) { BigInteger b1 = BigInteger.valueOf(a); BigInteger b2 = BigInteger.valueOf(b); BigInteger gcd = b1.gcd(b2); return gcd.intValue(); } private static long gcd(long a, long b) { BigInteger b1 = BigInteger.valueOf(a); BigInteger b2 = BigInteger.valueOf(b); BigInteger gcd = b1.gcd(b2); return gcd.longValue(); } private int[] readIntArray(int n) { int[] res = new int[n]; for (int i = 0; i < n; i++) { res[i] = sc.nextInt(); } return res; } private long[] readLongArray(int n) { long[] res = new long[n]; for (int i = 0; i < n; i++) { res[i] = sc.nextLong(); } return res; } @SuppressWarnings("unused") static class FastScanner { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; FastScanner(InputStream stream) { this.stream = stream; } 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++]; } boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } boolean isEndline(int c) { return c == '\n' || c == '\r' || c == -1; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String next() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isEndline(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndline(c)); return res.toString(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if (!oj) System.out.println(Arrays.deepToString(o)); } }
Java
["5 3\n1 2 2 4 5", "5 3\n1 2 3 4 5", "5 3\n1 2 3 3 3"]
2 seconds
["1", "2", "0"]
null
Java 8
standard input
[ "sortings", "brute force", "math" ]
ed1a2ae733121af6486568e528fe2d84
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 50$$$) — the number of elements in the array and the number of equal numbers required. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,600
Print one integer — the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.
standard output
PASSED
c6b42af5f7b1734b856b95cd7ad01f44
train_002.jsonl
1567175700
The only difference between easy and hard versions is the number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. In one move you can choose any $$$a_i$$$ and divide it by $$$2$$$ rounding down (in other words, in one move you can set $$$a_i := \lfloor\frac{a_i}{2}\rfloor$$$).You can perform such an operation any (possibly, zero) number of times with any $$$a_i$$$.Your task is to calculate the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.Don't forget that it is possible to have $$$a_i = 0$$$ after some operations, thus the answer always exists.
256 megabytes
// package cf1213; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.math.BigInteger; import java.util.*; public class CFD2 { private static final String INPUT = "5 3\n" + "1 2 8 8 200000\n"; private static final int MOD = 1_000_000_007; private PrintWriter out; private FastScanner sc; public static void main(String[] args) { new CFD2().run(); } public void run() { sc = new FastScanner(oj ? System.in : new ByteArrayInputStream(INPUT.getBytes())); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis() - s + "ms"); } static class Node { int cur; int below; int[] arr = new int[20]; public Node() {} public Node(int cur, int below) { this.cur = cur; this.below = below; } @Override public String toString() { return "Node{" + "cur=" + cur + ", below=" + below + ", arr=" + Arrays.toString(arr) + '}'; } } private void solve() { int n = sc.nextInt(); int k = sc.nextInt(); Node[] tree = new Node[200_001]; for (int i = 0; i < tree.length; i++) { tree[i] = new Node(); } for (int i = 0; i < n; i++) { int nr = sc.nextInt(); tree[nr].cur++; } for (int i = 200_000; i >= 1; i--) { Node node = tree[i]; Node parent = tree[i >> 1]; if (node.below + node.cur > 0) { parent.below += node.below + node.cur; node.arr[0] = node.cur; for (int j = 1; j < 20; j++) { parent.arr[j] += node.arr[j-1]; } } } int ans = Integer.MAX_VALUE; for (int i = 0; i < tree.length; i++) { Node node = tree[i]; if (node.cur + node.below < k) continue; int sum = 0; int cans = 0; for (int j = 0; j < 20; j++) { if (sum + node.arr[j] < k) { sum += node.arr[j]; cans += node.arr[j]*j; } else { cans += (k-sum)*j; break; } } ans = Math.min(ans, cans); } out.println(ans); } //******************************************************************************************** //******************************************************************************************** //******************************************************************************************** static class SolutionFailedException extends Exception { int code; public SolutionFailedException(int code) { this.code = code; } } private static void shuffle(int[] array) { Random random = new Random(); for (int i = array.length - 1; i > 0; i--) { int index = random.nextInt(i + 1); int temp = array[index]; array[index] = array[i]; array[i] = temp; } } /** * If searched element doesn't exist, returns index of first element which is bigger than searched value.<br> * If searched element is bigger than any array element function returns first index after last element.<br> * If searched element is lower than any array element function returns index of first element.<br> * If there are many values equals searched value function returns first occurrence.<br> */ private static int lowerBound(long[] arr, long key) { int lo = 0; int hi = arr.length - 1; while (lo < hi) { int mid = (lo + hi) / 2; if (key <= arr[mid]) { hi = mid - 1; } else { lo = mid + 1; } } return arr[lo] < key ? lo + 1 : lo; } /** * Returns index of first element which is grater than searched value. * If searched element is bigger than any array element, returns first index after last element. */ private static int upperBound(long[] arr, long key) { int lo = 0; int hi = arr.length - 1; while (lo < hi) { int mid = (lo + hi) / 2; if (key >= arr[mid]) { lo = mid + 1; } else { hi = mid; } } return arr[lo] <= key ? lo + 1 : lo; } private static int ceil(double d) { int ret = (int) d; return ret == d ? ret : ret + 1; } private static int round(double d) { return (int) (d + 0.5); } private static int gcd(int a, int b) { BigInteger b1 = BigInteger.valueOf(a); BigInteger b2 = BigInteger.valueOf(b); BigInteger gcd = b1.gcd(b2); return gcd.intValue(); } private static long gcd(long a, long b) { BigInteger b1 = BigInteger.valueOf(a); BigInteger b2 = BigInteger.valueOf(b); BigInteger gcd = b1.gcd(b2); return gcd.longValue(); } private int[] readIntArray(int n) { int[] res = new int[n]; for (int i = 0; i < n; i++) { res[i] = sc.nextInt(); } return res; } private long[] readLongArray(int n) { long[] res = new long[n]; for (int i = 0; i < n; i++) { res[i] = sc.nextLong(); } return res; } @SuppressWarnings("unused") static class FastScanner { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; FastScanner(InputStream stream) { this.stream = stream; } 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++]; } boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } boolean isEndline(int c) { return c == '\n' || c == '\r' || c == -1; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String next() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isEndline(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndline(c)); return res.toString(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if (!oj) System.out.println(Arrays.deepToString(o)); } }
Java
["5 3\n1 2 2 4 5", "5 3\n1 2 3 4 5", "5 3\n1 2 3 3 3"]
2 seconds
["1", "2", "0"]
null
Java 8
standard input
[ "sortings", "brute force", "math" ]
ed1a2ae733121af6486568e528fe2d84
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 50$$$) — the number of elements in the array and the number of equal numbers required. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,600
Print one integer — the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.
standard output
PASSED
b38687d01a9af18c47fe238e2b2a9906
train_002.jsonl
1567175700
The only difference between easy and hard versions is the number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. In one move you can choose any $$$a_i$$$ and divide it by $$$2$$$ rounding down (in other words, in one move you can set $$$a_i := \lfloor\frac{a_i}{2}\rfloor$$$).You can perform such an operation any (possibly, zero) number of times with any $$$a_i$$$.Your task is to calculate the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.Don't forget that it is possible to have $$$a_i = 0$$$ after some operations, thus the answer always exists.
256 megabytes
// package cf1213; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.math.BigInteger; import java.util.Arrays; import java.util.InputMismatchException; import java.util.Random; public class CFD2a { private static final String INPUT = "5 3\n" + "1 2 7 8 200000\n"; private static final int MOD = 1_000_000_007; private PrintWriter out; private FastScanner sc; public static void main(String[] args) { new CFD2a().run(); } public void run() { sc = new FastScanner(oj ? System.in : new ByteArrayInputStream(INPUT.getBytes())); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis() - s + "ms"); } private void solve() { int n = sc.nextInt(); int k = sc.nextInt(); int[] a = readIntArray(n); int[] qs = new int[200_001]; int[] cans = new int[200_001]; shuffle(a); Arrays.sort(a); int ans = Integer.MAX_VALUE; OUT: for (int i = 0; i < 20; i++) { for (int j = a.length - 1; j >= 0; j--) { int nr = a[j] >> i; if (nr == 0) break; if (qs[nr] < k) { qs[nr]++; cans[nr] += i; if (qs[nr] == k) { ans = Math.min(ans, cans[nr]); } } } } out.println(ans); } //******************************************************************************************** //******************************************************************************************** //******************************************************************************************** static class SolutionFailedException extends Exception { int code; public SolutionFailedException(int code) { this.code = code; } } private static void shuffle(int[] array) { Random random = new Random(); for (int i = array.length - 1; i > 0; i--) { int index = random.nextInt(i + 1); int temp = array[index]; array[index] = array[i]; array[i] = temp; } } /** * If searched element doesn't exist, returns index of first element which is bigger than searched value.<br> * If searched element is bigger than any array element function returns first index after last element.<br> * If searched element is lower than any array element function returns index of first element.<br> * If there are many values equals searched value function returns first occurrence.<br> */ private static int lowerBound(long[] arr, long key) { int lo = 0; int hi = arr.length - 1; while (lo < hi) { int mid = (lo + hi) / 2; if (key <= arr[mid]) { hi = mid - 1; } else { lo = mid + 1; } } return arr[lo] < key ? lo + 1 : lo; } /** * Returns index of first element which is grater than searched value. * If searched element is bigger than any array element, returns first index after last element. */ private static int upperBound(long[] arr, long key) { int lo = 0; int hi = arr.length - 1; while (lo < hi) { int mid = (lo + hi) / 2; if (key >= arr[mid]) { lo = mid + 1; } else { hi = mid; } } return arr[lo] <= key ? lo + 1 : lo; } private static int ceil(double d) { int ret = (int) d; return ret == d ? ret : ret + 1; } private static int round(double d) { return (int) (d + 0.5); } private static int gcd(int a, int b) { BigInteger b1 = BigInteger.valueOf(a); BigInteger b2 = BigInteger.valueOf(b); BigInteger gcd = b1.gcd(b2); return gcd.intValue(); } private static long gcd(long a, long b) { BigInteger b1 = BigInteger.valueOf(a); BigInteger b2 = BigInteger.valueOf(b); BigInteger gcd = b1.gcd(b2); return gcd.longValue(); } private int[] readIntArray(int n) { int[] res = new int[n]; for (int i = 0; i < n; i++) { res[i] = sc.nextInt(); } return res; } private long[] readLongArray(int n) { long[] res = new long[n]; for (int i = 0; i < n; i++) { res[i] = sc.nextLong(); } return res; } @SuppressWarnings("unused") static class FastScanner { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; FastScanner(InputStream stream) { this.stream = stream; } 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++]; } boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } boolean isEndline(int c) { return c == '\n' || c == '\r' || c == -1; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String next() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isEndline(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndline(c)); return res.toString(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if (!oj) System.out.println(Arrays.deepToString(o)); } }
Java
["5 3\n1 2 2 4 5", "5 3\n1 2 3 4 5", "5 3\n1 2 3 3 3"]
2 seconds
["1", "2", "0"]
null
Java 8
standard input
[ "sortings", "brute force", "math" ]
ed1a2ae733121af6486568e528fe2d84
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 50$$$) — the number of elements in the array and the number of equal numbers required. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,600
Print one integer — the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.
standard output
PASSED
d73b3bb8f36e354aaca2a9925e035b17
train_002.jsonl
1567175700
The only difference between easy and hard versions is the number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. In one move you can choose any $$$a_i$$$ and divide it by $$$2$$$ rounding down (in other words, in one move you can set $$$a_i := \lfloor\frac{a_i}{2}\rfloor$$$).You can perform such an operation any (possibly, zero) number of times with any $$$a_i$$$.Your task is to calculate the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.Don't forget that it is possible to have $$$a_i = 0$$$ after some operations, thus the answer always exists.
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class e { public static class FastReader { BufferedReader br; StringTokenizer st; //it reads the data about the specified point and divide the data about it ,it is quite fast //than using direct public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception r) { r.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next());//converts string to integer } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (Exception r) { r.printStackTrace(); } return str; } } static ArrayList<String>list1=new ArrayList<String>(); static void combine(String instr, StringBuffer outstr, int index,int k) { if(outstr.length()==k) { list1.add(outstr.toString());return; } if(outstr.toString().length()==0) outstr.append(instr.charAt(index)); for (int i = 0; i < instr.length(); i++) { outstr.append(instr.charAt(i)); combine(instr, outstr, i + 1,k); outstr.deleteCharAt(outstr.length() - 1); } index++; } static ArrayList<ArrayList<Integer>>l=new ArrayList<>(); static void comb(int n,int k,int ind,ArrayList<Integer>list) { if(k==0) { l.add(new ArrayList<>(list)); return; } for(int i=ind;i<=n;i++) { list.add(i); comb(n,k-1,ind+1,list); list.remove(list.size()-1); } } static int getans(int a,int b) {int ct=0; while(a<b) { b/=2;ct++; if(a==b) break; } if(a==b) return ct; else return 0; } public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out)); public static void main(String[] args) { // TODO Auto-generated method stub FastReader in=new FastReader(); TreeMap<Integer,Integer>map=new TreeMap<Integer,Integer>(); int n=in.nextInt(); int k=in.nextInt(); ArrayList<Integer>a[]=new ArrayList[2*100005]; for(int i=0;i<2*100005;i++) a[i]=new ArrayList<Integer>(); for(int i=0;i<n;i++) { int y=in.nextInt(); int ct=0; while(y>0) { a[y].add(ct); ct++; y/=2; } } int ans=Integer.MAX_VALUE;int m=0; for(int i=0;i<2*100005;i++) { if(a[i].size()>=k) {m=0; Collections.sort(a[i]); for(int j=0;j<k;j++) m+=a[i].get(j); ans=Math.min(m, ans); } } out.println(ans); out.close(); } }
Java
["5 3\n1 2 2 4 5", "5 3\n1 2 3 4 5", "5 3\n1 2 3 3 3"]
2 seconds
["1", "2", "0"]
null
Java 8
standard input
[ "sortings", "brute force", "math" ]
ed1a2ae733121af6486568e528fe2d84
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 50$$$) — the number of elements in the array and the number of equal numbers required. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,600
Print one integer — the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.
standard output
PASSED
c96c137cbb581eb553a137e34a454398
train_002.jsonl
1567175700
The only difference between easy and hard versions is the number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. In one move you can choose any $$$a_i$$$ and divide it by $$$2$$$ rounding down (in other words, in one move you can set $$$a_i := \lfloor\frac{a_i}{2}\rfloor$$$).You can perform such an operation any (possibly, zero) number of times with any $$$a_i$$$.Your task is to calculate the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.Don't forget that it is possible to have $$$a_i = 0$$$ after some operations, thus the answer always exists.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.security.KeyStore.Entry; import java.util.ArrayList; import java.util.Arrays; import java.util.PriorityQueue; import java.util.StringTokenizer; import java.util.TreeMap; public class Main { public static void main(String[] args) throws Exception { Scanner sc=new Scanner(System.in); PrintWriter out=new PrintWriter(System.out); int n=sc.nextInt(); int k=sc.nextInt(); int a[]=new int[n]; int b[]=new int[n]; for (int i = 0; i < a.length; i++) { a[i]=sc.nextInt(); b[i]=a[i]; } a=schuffle(a); Arrays.sort(a); int count1[]=new int[(int) (2*1e6+1)]; for (int i = 0; i < a.length; i++) { count1[a[i]]++; } for (int i = 0; i < a.length; i++) { if(count1[a[i]]>=k) { System.out.println(0); return; } } TreeMap<Integer,Integer> map=new TreeMap<>(); int count[]=new int[(int) (2*1e6+1)]; for (int i = 0; i < a.length; i++) { int x=a[i]; map.put(x,map.getOrDefault(x,0)+1); while(x!=0) { x=x/2; if(map.get(x)!=null&&map.get(x)==k) { continue; } map.put(x,map.getOrDefault(x,0)+1); int y=0; int x2=0; double x1=0; if(x!=0&&x!=1) { double z=Math.log(a[i])/Math.log(2); z=Math.floor(z+0.000000001); x1=Math.log(x)/Math.log(2); x1=Math.floor(x1+0.00000001); x2=(int) x1; y=(int) z; count[x]+=y-x2; } if(x==0&&a[i]>1) { double z=Math.log(a[i])/Math.log(2); z=Math.ceil(z+0.000000001); y=(int) z; count[x]+=y; } else if(x==0&&a[i]==1) { count[x]++; } else if(x==1&&a[i]>1) { double z=Math.log(a[i])/Math.log(2); z=Math.floor(z+0.000000001); y=(int) z; count[x]+=y; } } } ArrayList<Integer> l=new ArrayList<>(); for(java.util.Map.Entry<Integer, Integer> entry : map.entrySet()) { int x=entry.getKey(); int y=entry.getValue(); if(y>=k) { l.add(x); //System.out.println(x+" "+y); } } int min=(int) 1e9; for(int x:l) { min=Math.min(count[x], min); } System.out.println(min); out.flush(); } public static int[] schuffle(int a[]) { for (int i = 0; i < a.length; i++) { int x=(int)(Math.random()*a.length); int temp=a[x]; a[x]=a[i]; a[i]=temp; } return a; } static int V; static int INF=(int) 1E9; static class Edge implements Comparable<Edge> { int node, cost; Edge(int a, int b) { node = a; cost = b; } public int compareTo(Edge e){ return cost - e.cost; } } static class Edge2 implements Comparable<Edge2> { int node, cost; int p; Edge2(int a, int b,int c) { node = a; cost = b; p=c;} public int compareTo(Edge2 e){ return cost - e.cost; } } static int[] []dijkstra(int S, int T) //O(E log E) { int[] []dist = new int[3][V]; Arrays.fill(dist[0], INF); Arrays.fill(dist[1], INF); Arrays.fill(dist[2], INF); PriorityQueue<Edge2> pq = new PriorityQueue<Edge2>(); dist[0][S] = 0; pq.add(new Edge2(S, 0,0)); //may add more in case of MSSP (Mult-Source) while(!pq.isEmpty()) { Edge2 cur = pq.remove(); int p=cur.p; if(cur.node==T) { continue; } for(Edge nxt: adjList[cur.node]) { int roads=(p+1)%3; if(cur.cost + nxt.cost < dist[roads][nxt.node]) { pq.add(new Edge2(nxt.node, dist[roads][nxt.node] = cur.cost + nxt.cost,roads)); } } } return dist; } static ArrayList<Edge>adjList[]; static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } }
Java
["5 3\n1 2 2 4 5", "5 3\n1 2 3 4 5", "5 3\n1 2 3 3 3"]
2 seconds
["1", "2", "0"]
null
Java 8
standard input
[ "sortings", "brute force", "math" ]
ed1a2ae733121af6486568e528fe2d84
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 50$$$) — the number of elements in the array and the number of equal numbers required. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,600
Print one integer — the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.
standard output
PASSED
34c57ae21480ef44ad9813e5ae309e18
train_002.jsonl
1567175700
The only difference between easy and hard versions is the number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. In one move you can choose any $$$a_i$$$ and divide it by $$$2$$$ rounding down (in other words, in one move you can set $$$a_i := \lfloor\frac{a_i}{2}\rfloor$$$).You can perform such an operation any (possibly, zero) number of times with any $$$a_i$$$.Your task is to calculate the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.Don't forget that it is possible to have $$$a_i = 0$$$ after some operations, thus the answer always exists.
256 megabytes
import java.util.*; import java.io.*; public class HelloWorld { public void run() throws Exception { Scanner file = new Scanner(System.in); int times = file.nextInt(); int k = file.nextInt(); ArrayList<Integer> w= new ArrayList(); int max = Integer.MIN_VALUE; for (int i = 0; i < times; i++) { int temp = file.nextInt(); w.add(temp); max = Math.max(max, temp); } Collections.sort(w); int[] kamt = new int[200001], moves = new int[200001]; int min = Integer.MAX_VALUE; for (int i = 0; i < times; i++) { int temp = w.get(i); int count = 1; while (temp > 0) { kamt[temp]++; if (kamt[temp] >= k) min = Math.min(min, moves[temp]); temp /= 2; moves[temp] += count; count++; } } System.out.println(min); } public static void main(String[] args) throws Exception { new HelloWorld().run(); } }
Java
["5 3\n1 2 2 4 5", "5 3\n1 2 3 4 5", "5 3\n1 2 3 3 3"]
2 seconds
["1", "2", "0"]
null
Java 8
standard input
[ "sortings", "brute force", "math" ]
ed1a2ae733121af6486568e528fe2d84
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 50$$$) — the number of elements in the array and the number of equal numbers required. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,600
Print one integer — the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.
standard output
PASSED
11ec95996f47cc77b90f0e79357b425e
train_002.jsonl
1567175700
The only difference between easy and hard versions is the number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. In one move you can choose any $$$a_i$$$ and divide it by $$$2$$$ rounding down (in other words, in one move you can set $$$a_i := \lfloor\frac{a_i}{2}\rfloor$$$).You can perform such an operation any (possibly, zero) number of times with any $$$a_i$$$.Your task is to calculate the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.Don't forget that it is possible to have $$$a_i = 0$$$ after some operations, thus the answer always exists.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class HelloWorld { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); Integer[] arr = new Integer[n]; st = new StringTokenizer(br.readLine()); for(int i = 0; i < n; i++) arr[i] = Integer.parseInt(st.nextToken()); int[] touch = new int[200001]; int[] moves = new int[200001]; int min = Integer.MAX_VALUE; Arrays.sort(arr); for(int i = 0; i < n; i++) { int temp = arr[i]; int count = 1; while(temp > 0) { touch[temp]++; if(touch[temp] >= k) min = Math.min(min, moves[temp]); temp /= 2; moves[temp] += count; count++; } } System.out.println(min); } }
Java
["5 3\n1 2 2 4 5", "5 3\n1 2 3 4 5", "5 3\n1 2 3 3 3"]
2 seconds
["1", "2", "0"]
null
Java 8
standard input
[ "sortings", "brute force", "math" ]
ed1a2ae733121af6486568e528fe2d84
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 50$$$) — the number of elements in the array and the number of equal numbers required. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
1,600
Print one integer — the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.
standard output
PASSED
54e135d81ac139c419ff8fef29fc615d
train_002.jsonl
1451215200
Vika has n jars with paints of distinct colors. All the jars are numbered from 1 to n and the i-th jar contains ai liters of paint of color i.Vika also has an infinitely long rectangular piece of paper of width 1, consisting of squares of size 1 × 1. Squares are numbered 1, 2, 3 and so on. Vika decided that she will start painting squares one by one from left to right, starting from the square number 1 and some arbitrary color. If the square was painted in color x, then the next square will be painted in color x + 1. In case of x = n, next square is painted in color 1. If there is no more paint of the color Vika wants to use now, then she stops.Square is always painted in only one color, and it takes exactly 1 liter of paint. Your task is to calculate the maximum number of squares that might be painted, if Vika chooses right color to paint the first square.
256 megabytes
import java.util.Scanner; public class VikaAndSquares { public static void main(String[] args) { Scanner scan=new Scanner(System.in); long n=scan.nextLong(); int nex=(int) n; int[] a=new int[nex]; for(int i=0;i<nex;i++){ a[i]=scan.nextInt(); } long min=a[0],index=0; for(int i=1;i<nex;i++){ if(a[i]<min){ min=a[i]; index=i; } } long total=min*n; long count=0; for(int i=0;i<n;i++){ if(a[i]==min){ count=i; break; } } int next=(int) count; int[] b=new int[next]; for(int i=0;i<count;i++){ b[i]=a[i]; } for(int i=next;i<nex;i++){ a[i-next]=a[i]; } for(int i=nex-next;i<nex;i++){ a[i]=b[i-nex+next]; } long counter=0; long max=0; for(int i=0;i<nex;i++){ if(a[i]==min){ if(counter>max){ max=counter; } counter=-1; } counter++; if(i==n-1){ if(counter>max){ max=counter; } } } System.out.println(total+max); } }
Java
["5\n2 4 2 3 3", "3\n5 5 5", "6\n10 10 10 1 10 10"]
2 seconds
["12", "15", "11"]
NoteIn the first sample the best strategy is to start painting using color 4. Then the squares will be painted in the following colors (from left to right): 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5.In the second sample Vika can start to paint using any color.In the third sample Vika should start painting using color number 5.
Java 8
standard input
[ "constructive algorithms", "implementation" ]
e2db09803d87362c67763ef71e8b7f47
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of jars with colors Vika has. The second line of the input contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is equal to the number of liters of paint in the i-th jar, i.e. the number of liters of color i that Vika has.
1,300
The only line of the output should contain a single integer — the maximum number of squares that Vika can paint if she follows the rules described above.
standard output
PASSED
b40169eac7766828aa0f911f75ddd39b
train_002.jsonl
1451215200
Vika has n jars with paints of distinct colors. All the jars are numbered from 1 to n and the i-th jar contains ai liters of paint of color i.Vika also has an infinitely long rectangular piece of paper of width 1, consisting of squares of size 1 × 1. Squares are numbered 1, 2, 3 and so on. Vika decided that she will start painting squares one by one from left to right, starting from the square number 1 and some arbitrary color. If the square was painted in color x, then the next square will be painted in color x + 1. In case of x = n, next square is painted in color 1. If there is no more paint of the color Vika wants to use now, then she stops.Square is always painted in only one color, and it takes exactly 1 liter of paint. Your task is to calculate the maximum number of squares that might be painted, if Vika chooses right color to paint the first square.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class main { static Scanner in = new Scanner(System.in); public static void main(String[] args) { long n = in.nextInt(); long[] ar = new long[(int)n]; for(int i = 0;i<n;i++){ ar[i]=in.nextLong(); } long min = ar[0]; long mini = 0; for(int i = 0;i<n;i++){ if(min>ar[i]){ mini = i; min = ar[i]; } } long r = 0; long[] res = new long[2*(int)n]; for(int i = 0;i<2*n;i++){ res[i]=ar[i%(int)n]; } for(int i = 0;i<=n;i++){ if(ar[i%(int)n]!=min)continue; long rasnow = 0; for(int j = i+1;j<2*n;j++){ if(ar[j%(int)n]!=min){ rasnow++; } else { if(rasnow>r){ r=rasnow; } break; } } } long sum = n*min+r; System.out.println(sum); } }
Java
["5\n2 4 2 3 3", "3\n5 5 5", "6\n10 10 10 1 10 10"]
2 seconds
["12", "15", "11"]
NoteIn the first sample the best strategy is to start painting using color 4. Then the squares will be painted in the following colors (from left to right): 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5.In the second sample Vika can start to paint using any color.In the third sample Vika should start painting using color number 5.
Java 8
standard input
[ "constructive algorithms", "implementation" ]
e2db09803d87362c67763ef71e8b7f47
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of jars with colors Vika has. The second line of the input contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is equal to the number of liters of paint in the i-th jar, i.e. the number of liters of color i that Vika has.
1,300
The only line of the output should contain a single integer — the maximum number of squares that Vika can paint if she follows the rules described above.
standard output
PASSED
26a4c975670ecf70d20dd45f006da6db
train_002.jsonl
1451215200
Vika has n jars with paints of distinct colors. All the jars are numbered from 1 to n and the i-th jar contains ai liters of paint of color i.Vika also has an infinitely long rectangular piece of paper of width 1, consisting of squares of size 1 × 1. Squares are numbered 1, 2, 3 and so on. Vika decided that she will start painting squares one by one from left to right, starting from the square number 1 and some arbitrary color. If the square was painted in color x, then the next square will be painted in color x + 1. In case of x = n, next square is painted in color 1. If there is no more paint of the color Vika wants to use now, then she stops.Square is always painted in only one color, and it takes exactly 1 liter of paint. Your task is to calculate the maximum number of squares that might be painted, if Vika chooses right color to paint the first square.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; import java.math.*; public class Main{ public static int[] xyz; public static void main (String[] args) throws java.lang.Exception{ //BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); InputReader in=new InputReader(System.in); PrintWriter out=new PrintWriter(System.out); int n=in.readInt(); int[] a=new int[n]; long min=Integer.MAX_VALUE;int minat=0; for(int i=0;i<n;i++){ a[i]=in.readInt(); if(a[i]<min){ min=a[i]; minat=i; } } long ans=min*n; for(int i=0;i<n;i++){ a[i]-=min; } long max=0,count=0; for(int i=0;i<=n;i++){ if(a[(i+minat)%n]==0){ max=Math.max(max,count); count=0; }else{ count++; } } max=Math.max(max,count); ans+=max; out.println(ans); out.flush();out.close(); } static final class InputReader{ private final InputStream stream; private final byte[] buf=new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream){this.stream=stream;} private int read()throws IOException{ if(curChar>=numChars){ curChar=0; numChars=stream.read(buf); if(numChars<=0) return -1; } return buf[curChar++]; } public final int readInt()throws IOException{return (int)readLong();} public final long readLong()throws IOException{ int c=read(); while(isSpaceChar(c)){ c=read(); if(c==-1) throw new IOException(); } boolean negative=false; if(c=='-'){ negative=true; 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 negative?(-res):(res); } public final int[] readIntBrray(int size)throws IOException{ int[] arr=new int[size]; for(int i=0;i<size;i++)arr[i]=readInt(); return arr; } public final String readString()throws IOException{ int c=read(); while(isSpaceChar(c))c=read(); StringBuilder res=new StringBuilder(); do{ res.append((char)c); c=read(); }while(!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c){ return c==' '||c=='\n'||c=='\r'||c=='\t'||c==-1; } } }
Java
["5\n2 4 2 3 3", "3\n5 5 5", "6\n10 10 10 1 10 10"]
2 seconds
["12", "15", "11"]
NoteIn the first sample the best strategy is to start painting using color 4. Then the squares will be painted in the following colors (from left to right): 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5.In the second sample Vika can start to paint using any color.In the third sample Vika should start painting using color number 5.
Java 8
standard input
[ "constructive algorithms", "implementation" ]
e2db09803d87362c67763ef71e8b7f47
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of jars with colors Vika has. The second line of the input contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is equal to the number of liters of paint in the i-th jar, i.e. the number of liters of color i that Vika has.
1,300
The only line of the output should contain a single integer — the maximum number of squares that Vika can paint if she follows the rules described above.
standard output
PASSED
ddfc2163137e2add83cc0d810a435719
train_002.jsonl
1451215200
Vika has n jars with paints of distinct colors. All the jars are numbered from 1 to n and the i-th jar contains ai liters of paint of color i.Vika also has an infinitely long rectangular piece of paper of width 1, consisting of squares of size 1 × 1. Squares are numbered 1, 2, 3 and so on. Vika decided that she will start painting squares one by one from left to right, starting from the square number 1 and some arbitrary color. If the square was painted in color x, then the next square will be painted in color x + 1. In case of x = n, next square is painted in color 1. If there is no more paint of the color Vika wants to use now, then she stops.Square is always painted in only one color, and it takes exactly 1 liter of paint. Your task is to calculate the maximum number of squares that might be painted, if Vika chooses right color to paint the first square.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; import java.math.*; public class Main{ public static int[] xyz; public static void main (String[] args) throws java.lang.Exception{ //BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); InputReader in=new InputReader(System.in); PrintWriter out=new PrintWriter(System.out); int n=in.readInt(); int[] a=new int[n]; long min=Integer.MAX_VALUE;int minat=0; for(int i=0;i<n;i++){ a[i]=in.readInt(); if(a[i]<min){ min=a[i]; minat=i; } } long ans=min*n; for(int i=0;i<n;i++){ a[i]-=min; } long max=0,count=0; for(int i=0;i<=n;i++){ if(a[(i+minat)%n]==0){ max=Math.max(max,count); count=0; }else{ count++; } } max=Math.max(max,count); ans+=max; out.println(ans); out.flush();out.close(); } static final class InputReader{ private final InputStream stream; private final byte[] buf=new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream){this.stream=stream;} private int read()throws IOException{ if(curChar>=numChars){ curChar=0; numChars=stream.read(buf); if(numChars<=0) return -1; } return buf[curChar++]; } public final int readInt()throws IOException{return (int)readLong();} public final long readLong()throws IOException{ int c=read(); while(isSpaceChar(c)){ c=read(); if(c==-1) throw new IOException(); } boolean negative=false; if(c=='-'){ negative=true; 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 negative?(-res):(res); } public final int[] readIntBrray(int size)throws IOException{ int[] arr=new int[size]; for(int i=0;i<size;i++)arr[i]=readInt(); return arr; } public final String readString()throws IOException{ int c=read(); while(isSpaceChar(c))c=read(); StringBuilder res=new StringBuilder(); do{ res.append((char)c); c=read(); }while(!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c){ return c==' '||c=='\n'||c=='\r'||c=='\t'||c==-1; } } }
Java
["5\n2 4 2 3 3", "3\n5 5 5", "6\n10 10 10 1 10 10"]
2 seconds
["12", "15", "11"]
NoteIn the first sample the best strategy is to start painting using color 4. Then the squares will be painted in the following colors (from left to right): 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5.In the second sample Vika can start to paint using any color.In the third sample Vika should start painting using color number 5.
Java 8
standard input
[ "constructive algorithms", "implementation" ]
e2db09803d87362c67763ef71e8b7f47
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of jars with colors Vika has. The second line of the input contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is equal to the number of liters of paint in the i-th jar, i.e. the number of liters of color i that Vika has.
1,300
The only line of the output should contain a single integer — the maximum number of squares that Vika can paint if she follows the rules described above.
standard output
PASSED
3a180262ff806c92f02fcc24611f77be
train_002.jsonl
1451215200
Vika has n jars with paints of distinct colors. All the jars are numbered from 1 to n and the i-th jar contains ai liters of paint of color i.Vika also has an infinitely long rectangular piece of paper of width 1, consisting of squares of size 1 × 1. Squares are numbered 1, 2, 3 and so on. Vika decided that she will start painting squares one by one from left to right, starting from the square number 1 and some arbitrary color. If the square was painted in color x, then the next square will be painted in color x + 1. In case of x = n, next square is painted in color 1. If there is no more paint of the color Vika wants to use now, then she stops.Square is always painted in only one color, and it takes exactly 1 liter of paint. Your task is to calculate the maximum number of squares that might be painted, if Vika chooses right color to paint the first square.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.ArrayList; public class b { public static void main(String[] args) throws IOException { //BufferedReader input = new BufferedReader(new FileReader("input.txt")); BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); String s[] = input.readLine().split(" "); int n = Integer.parseInt(s[0]); s = input.readLine().split(" "); ArrayList<Integer> list = new ArrayList<Integer>(); int arr[] = new int[n]; long lowest = Integer.parseInt(s[0]); long total= 0; long max = 0; for (int i = 0; i < s.length; i++) { arr[i] = Integer.parseInt(s[i]); if(arr[i] <= lowest){ lowest = arr[i] ; } } int j; int space; for (int i = 0; i < arr.length; i++) { if(lowest == arr[i]) { j=i; space=0; while(true){ if(j+1 == arr.length) j=0; else j++; if(arr[j] == lowest) break; space++; } if(space > max ) max = space; //System.out.print(space + " "); } } //BigInteger total = (BigInteger.valueOf(n)).multiply(BigInteger.valueOf(lowest)); //total = total.add(BigInteger.valueOf(max)); total = max; total += (n*lowest); System.out.println(total); } }
Java
["5\n2 4 2 3 3", "3\n5 5 5", "6\n10 10 10 1 10 10"]
2 seconds
["12", "15", "11"]
NoteIn the first sample the best strategy is to start painting using color 4. Then the squares will be painted in the following colors (from left to right): 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5.In the second sample Vika can start to paint using any color.In the third sample Vika should start painting using color number 5.
Java 8
standard input
[ "constructive algorithms", "implementation" ]
e2db09803d87362c67763ef71e8b7f47
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of jars with colors Vika has. The second line of the input contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is equal to the number of liters of paint in the i-th jar, i.e. the number of liters of color i that Vika has.
1,300
The only line of the output should contain a single integer — the maximum number of squares that Vika can paint if she follows the rules described above.
standard output
PASSED
2700db875fb31261305f838fa1674ca3
train_002.jsonl
1451215200
Vika has n jars with paints of distinct colors. All the jars are numbered from 1 to n and the i-th jar contains ai liters of paint of color i.Vika also has an infinitely long rectangular piece of paper of width 1, consisting of squares of size 1 × 1. Squares are numbered 1, 2, 3 and so on. Vika decided that she will start painting squares one by one from left to right, starting from the square number 1 and some arbitrary color. If the square was painted in color x, then the next square will be painted in color x + 1. In case of x = n, next square is painted in color 1. If there is no more paint of the color Vika wants to use now, then she stops.Square is always painted in only one color, and it takes exactly 1 liter of paint. Your task is to calculate the maximum number of squares that might be painted, if Vika chooses right color to paint the first square.
256 megabytes
import java.util.*; public class main{ public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n= scan.nextInt(); long least=Long.MAX_VALUE; int [] a = new int[n]; for(int i =0;i<n;i++) { a[i] = scan.nextInt(); if(a[i] <= least ) least = a[i]; } //System.out.println(least); int[] a2 = new int[2*n]; for(int i =0;i<n;i++) { a2[i] = a[i]; } for(int i=0;i<n;i++) { a2[i+n] = a[i]; } ArrayList<Integer> in = new ArrayList<Integer>(); long tot = (least) * n; int ma=0; int cur=0; for(int i=0;i<2*n; i++) { if(a2[i] == least) { if(ma <= cur) ma = cur; cur =0; } else cur++; } tot+=ma; System.out.println(tot); } }
Java
["5\n2 4 2 3 3", "3\n5 5 5", "6\n10 10 10 1 10 10"]
2 seconds
["12", "15", "11"]
NoteIn the first sample the best strategy is to start painting using color 4. Then the squares will be painted in the following colors (from left to right): 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5.In the second sample Vika can start to paint using any color.In the third sample Vika should start painting using color number 5.
Java 8
standard input
[ "constructive algorithms", "implementation" ]
e2db09803d87362c67763ef71e8b7f47
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of jars with colors Vika has. The second line of the input contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is equal to the number of liters of paint in the i-th jar, i.e. the number of liters of color i that Vika has.
1,300
The only line of the output should contain a single integer — the maximum number of squares that Vika can paint if she follows the rules described above.
standard output
PASSED
b65444c0cb00c62ed482bfeb3139a8d7
train_002.jsonl
1451215200
Vika has n jars with paints of distinct colors. All the jars are numbered from 1 to n and the i-th jar contains ai liters of paint of color i.Vika also has an infinitely long rectangular piece of paper of width 1, consisting of squares of size 1 × 1. Squares are numbered 1, 2, 3 and so on. Vika decided that she will start painting squares one by one from left to right, starting from the square number 1 and some arbitrary color. If the square was painted in color x, then the next square will be painted in color x + 1. In case of x = n, next square is painted in color 1. If there is no more paint of the color Vika wants to use now, then she stops.Square is always painted in only one color, and it takes exactly 1 liter of paint. Your task is to calculate the maximum number of squares that might be painted, if Vika chooses right color to paint the first square.
256 megabytes
import java.math.BigInteger; import java.util.Scanner; public class B { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] c = new int[n]; int min = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { c[i] = sc.nextInt(); if (c[i] < min) { min = c[i]; } } int longestNonMin = 0; int current = 0; for (int i = 0; i < n; i++) { if (c[i] == min) { longestNonMin = Math.max(current, longestNonMin); current = 0; } else { current++; } } for (int i = 0;;i++) { if (c[i] == min) break; else current++; } longestNonMin = Math.max(current, longestNonMin); BigInteger result = BigInteger.valueOf(min).multiply(BigInteger.valueOf(n)); System.out.println(result.add(BigInteger.valueOf(longestNonMin)).toString()); sc.close(); } }
Java
["5\n2 4 2 3 3", "3\n5 5 5", "6\n10 10 10 1 10 10"]
2 seconds
["12", "15", "11"]
NoteIn the first sample the best strategy is to start painting using color 4. Then the squares will be painted in the following colors (from left to right): 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5.In the second sample Vika can start to paint using any color.In the third sample Vika should start painting using color number 5.
Java 8
standard input
[ "constructive algorithms", "implementation" ]
e2db09803d87362c67763ef71e8b7f47
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of jars with colors Vika has. The second line of the input contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is equal to the number of liters of paint in the i-th jar, i.e. the number of liters of color i that Vika has.
1,300
The only line of the output should contain a single integer — the maximum number of squares that Vika can paint if she follows the rules described above.
standard output
PASSED
b506d8112ee955c345c8dfaa63621415
train_002.jsonl
1451215200
Vika has n jars with paints of distinct colors. All the jars are numbered from 1 to n and the i-th jar contains ai liters of paint of color i.Vika also has an infinitely long rectangular piece of paper of width 1, consisting of squares of size 1 × 1. Squares are numbered 1, 2, 3 and so on. Vika decided that she will start painting squares one by one from left to right, starting from the square number 1 and some arbitrary color. If the square was painted in color x, then the next square will be painted in color x + 1. In case of x = n, next square is painted in color 1. If there is no more paint of the color Vika wants to use now, then she stops.Square is always painted in only one color, and it takes exactly 1 liter of paint. Your task is to calculate the maximum number of squares that might be painted, if Vika chooses right color to paint the first square.
256 megabytes
//package CodeForces.Round337; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; /** * Created by ilya on 27.12.15. */ public class B610 { public static void main(String[] args) { sc sc = new sc(); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int n = sc.nextInt(); int[] m = new int[n]; int min = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { int a = sc.nextInt(); if (min > a) min = a; m[i] = a; } int[] l = new int[n]; for (int i = 0; i < n; i++) { if (m[i] > min) { l[i]++; if (i > 0) l[i] += l[i - 1]; } } int count = 0; int[] r = new int[n]; for (int i = n - 1; i >= 0; i--) { if (m[i] > min) { r[i]++; if (i + 1 < n) r[i] += r[i + 1]; } } for (int i = 0; i < n; i++) { if (m[i] > min) { int l1 = (i+n-1) % n; count = Integer.max(r[i] + l[l1], count); } } long result = (long)n *(long) min + (long)count; out.println(result); out.close(); } public static class sc { BufferedReader br; StringTokenizer st; public sc() { 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(); } Integer nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5\n2 4 2 3 3", "3\n5 5 5", "6\n10 10 10 1 10 10"]
2 seconds
["12", "15", "11"]
NoteIn the first sample the best strategy is to start painting using color 4. Then the squares will be painted in the following colors (from left to right): 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5.In the second sample Vika can start to paint using any color.In the third sample Vika should start painting using color number 5.
Java 8
standard input
[ "constructive algorithms", "implementation" ]
e2db09803d87362c67763ef71e8b7f47
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of jars with colors Vika has. The second line of the input contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is equal to the number of liters of paint in the i-th jar, i.e. the number of liters of color i that Vika has.
1,300
The only line of the output should contain a single integer — the maximum number of squares that Vika can paint if she follows the rules described above.
standard output
PASSED
5945422aad2b4dc3b8f7a5602c6f8ba4
train_002.jsonl
1451215200
Vika has n jars with paints of distinct colors. All the jars are numbered from 1 to n and the i-th jar contains ai liters of paint of color i.Vika also has an infinitely long rectangular piece of paper of width 1, consisting of squares of size 1 × 1. Squares are numbered 1, 2, 3 and so on. Vika decided that she will start painting squares one by one from left to right, starting from the square number 1 and some arbitrary color. If the square was painted in color x, then the next square will be painted in color x + 1. In case of x = n, next square is painted in color 1. If there is no more paint of the color Vika wants to use now, then she stops.Square is always painted in only one color, and it takes exactly 1 liter of paint. Your task is to calculate the maximum number of squares that might be painted, if Vika chooses right color to paint the first square.
256 megabytes
import java.io.*; import java.util.*; public class Solution { public static void main(String args[]) { Scanner in; try { in = new Scanner(new File("input.txt")); } catch (Exception e) { in = new Scanner(System.in); } long n = in.nextInt(); long res = 0; long first = 0; long prev = 0; long last = 0; long maxDiff = 0; long min = in.nextInt(); boolean different = false; for (long i = 1; i < n; ++i) { long a = in.nextInt(); if (a < min) { min = a; first = i; prev = i; last = i; different = true; } else if (a == min) { prev = last; last = i; if (last - prev - 1 > maxDiff) { maxDiff = last - prev - 1; } } else { different = true; } } if (n - 1 - last + first > maxDiff) { maxDiff = n - 1 - last + first; } res = min * n; if (different) { res += maxDiff; } System.out.println(res); } }
Java
["5\n2 4 2 3 3", "3\n5 5 5", "6\n10 10 10 1 10 10"]
2 seconds
["12", "15", "11"]
NoteIn the first sample the best strategy is to start painting using color 4. Then the squares will be painted in the following colors (from left to right): 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5.In the second sample Vika can start to paint using any color.In the third sample Vika should start painting using color number 5.
Java 8
standard input
[ "constructive algorithms", "implementation" ]
e2db09803d87362c67763ef71e8b7f47
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of jars with colors Vika has. The second line of the input contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is equal to the number of liters of paint in the i-th jar, i.e. the number of liters of color i that Vika has.
1,300
The only line of the output should contain a single integer — the maximum number of squares that Vika can paint if she follows the rules described above.
standard output
PASSED
48c39e34c1b01f9213b418d605dc4009
train_002.jsonl
1451215200
Vika has n jars with paints of distinct colors. All the jars are numbered from 1 to n and the i-th jar contains ai liters of paint of color i.Vika also has an infinitely long rectangular piece of paper of width 1, consisting of squares of size 1 × 1. Squares are numbered 1, 2, 3 and so on. Vika decided that she will start painting squares one by one from left to right, starting from the square number 1 and some arbitrary color. If the square was painted in color x, then the next square will be painted in color x + 1. In case of x = n, next square is painted in color 1. If there is no more paint of the color Vika wants to use now, then she stops.Square is always painted in only one color, and it takes exactly 1 liter of paint. Your task is to calculate the maximum number of squares that might be painted, if Vika chooses right color to paint the first square.
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 safadurimo */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(); long[] a = new long[n]; long minimum = Long.MAX_VALUE; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); minimum = Math.min(minimum, a[i]); } long best = 0; int index = 0; long current = 0; for (int i = 0; i < 3 * n; i++) { if (a[index] != minimum) { current++; best = Math.max(current, best); } else current = 0; index = (index + 1) % n; } out.println(n * minimum + best); } } }
Java
["5\n2 4 2 3 3", "3\n5 5 5", "6\n10 10 10 1 10 10"]
2 seconds
["12", "15", "11"]
NoteIn the first sample the best strategy is to start painting using color 4. Then the squares will be painted in the following colors (from left to right): 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5.In the second sample Vika can start to paint using any color.In the third sample Vika should start painting using color number 5.
Java 8
standard input
[ "constructive algorithms", "implementation" ]
e2db09803d87362c67763ef71e8b7f47
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of jars with colors Vika has. The second line of the input contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is equal to the number of liters of paint in the i-th jar, i.e. the number of liters of color i that Vika has.
1,300
The only line of the output should contain a single integer — the maximum number of squares that Vika can paint if she follows the rules described above.
standard output
PASSED
c7623ee9b06790813852464fbeaeef3f
train_002.jsonl
1451215200
Vika has n jars with paints of distinct colors. All the jars are numbered from 1 to n and the i-th jar contains ai liters of paint of color i.Vika also has an infinitely long rectangular piece of paper of width 1, consisting of squares of size 1 × 1. Squares are numbered 1, 2, 3 and so on. Vika decided that she will start painting squares one by one from left to right, starting from the square number 1 and some arbitrary color. If the square was painted in color x, then the next square will be painted in color x + 1. In case of x = n, next square is painted in color 1. If there is no more paint of the color Vika wants to use now, then she stops.Square is always painted in only one color, and it takes exactly 1 liter of paint. Your task is to calculate the maximum number of squares that might be painted, if Vika chooses right color to paint the first square.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; import java.util.TreeSet; public class _337_1 { public static void main(String[] args) { // TODO Auto-generated method stub MyfScanner in=new MyfScanner(); int n=in.nextInt(); long a[]=new long[n]; long min=Long.MAX_VALUE; for(int i=0;i<n;i++) { a[i]=in.nextLong(); if(a[i]<min) min=a[i]; } //System.out.println(min); //ArrayList<Integer> list=new ArrayList<Integer>(); TreeSet<Integer> ts=new TreeSet<Integer>(); for(int i=0;i<n;i++) { if(a[i]==min) ts.add(i); } //System.out.println(ts.toString()); int max=Integer.MIN_VALUE; for(int i=0;i<n;i++) { int temp=0; if(!ts.contains(i)) { if(ts.ceiling(i)==null) { //System.out.println("herer"); temp=ts.first(); } else temp=ts.ceiling(i); //System.out.println(temp+" "+i); if(temp>i) { if(max<temp-i) max=temp-i; } else { //System.out.println("here") if(max<(n-i+temp)) max=n-i+temp; } } else max=Math.max(temp,max); //System.out.println(max); } //System.out.println(max); long ans=n*min+max; System.out.println(ans); } } class MyfScanner { BufferedReader br; StringTokenizer st; public MyfScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
Java
["5\n2 4 2 3 3", "3\n5 5 5", "6\n10 10 10 1 10 10"]
2 seconds
["12", "15", "11"]
NoteIn the first sample the best strategy is to start painting using color 4. Then the squares will be painted in the following colors (from left to right): 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5.In the second sample Vika can start to paint using any color.In the third sample Vika should start painting using color number 5.
Java 8
standard input
[ "constructive algorithms", "implementation" ]
e2db09803d87362c67763ef71e8b7f47
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of jars with colors Vika has. The second line of the input contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is equal to the number of liters of paint in the i-th jar, i.e. the number of liters of color i that Vika has.
1,300
The only line of the output should contain a single integer — the maximum number of squares that Vika can paint if she follows the rules described above.
standard output
PASSED
6a0fbe61ca702b78a2b2a747bc02905d
train_002.jsonl
1451215200
Vika has n jars with paints of distinct colors. All the jars are numbered from 1 to n and the i-th jar contains ai liters of paint of color i.Vika also has an infinitely long rectangular piece of paper of width 1, consisting of squares of size 1 × 1. Squares are numbered 1, 2, 3 and so on. Vika decided that she will start painting squares one by one from left to right, starting from the square number 1 and some arbitrary color. If the square was painted in color x, then the next square will be painted in color x + 1. In case of x = n, next square is painted in color 1. If there is no more paint of the color Vika wants to use now, then she stops.Square is always painted in only one color, and it takes exactly 1 liter of paint. Your task is to calculate the maximum number of squares that might be painted, if Vika chooses right color to paint the first square.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Artem Gilmudinov */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Reader in = new Reader(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, Reader in, PrintWriter out) { int n = in.ni(); Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) { a[i] = in.ni(); } long min = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { min = Math.min(a[i], min); } int[] closestAfter = new int[n]; ArrayList<Integer> mins = new ArrayList<>(); for (int i = 0; i < n; i++) { if (min == a[i]) { mins.add(i); } } for (int i = 0, j = 0; i < n; i++) { if (j == mins.size()) { closestAfter[i] = -1; } else if (mins.get(j) >= i) { closestAfter[i] = mins.get(j); if (mins.get(j) == i) { ++j; } } } long res = Long.MIN_VALUE; for (int i = 0; i < n; i++) { if (closestAfter[i] != -1) { res = Math.max(n - i + (min - 1) * n + closestAfter[i], res); } else { res = Math.max(n - i + min * n + mins.get(0), res); } } out.println(res); } } static class Reader { private BufferedReader in; private StringTokenizer st = new StringTokenizer(""); private String delim = " "; public Reader(InputStream in) { this.in = new BufferedReader(new InputStreamReader(in)); } public String next() { if (!st.hasMoreTokens()) { st = new StringTokenizer(rl()); } return st.nextToken(delim); } public String rl() { try { return in.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } public int ni() { return Integer.parseInt(next()); } } }
Java
["5\n2 4 2 3 3", "3\n5 5 5", "6\n10 10 10 1 10 10"]
2 seconds
["12", "15", "11"]
NoteIn the first sample the best strategy is to start painting using color 4. Then the squares will be painted in the following colors (from left to right): 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5.In the second sample Vika can start to paint using any color.In the third sample Vika should start painting using color number 5.
Java 8
standard input
[ "constructive algorithms", "implementation" ]
e2db09803d87362c67763ef71e8b7f47
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of jars with colors Vika has. The second line of the input contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is equal to the number of liters of paint in the i-th jar, i.e. the number of liters of color i that Vika has.
1,300
The only line of the output should contain a single integer — the maximum number of squares that Vika can paint if she follows the rules described above.
standard output
PASSED
0932fba57912350e6e787358b29213a7
train_002.jsonl
1451215200
Vika has n jars with paints of distinct colors. All the jars are numbered from 1 to n and the i-th jar contains ai liters of paint of color i.Vika also has an infinitely long rectangular piece of paper of width 1, consisting of squares of size 1 × 1. Squares are numbered 1, 2, 3 and so on. Vika decided that she will start painting squares one by one from left to right, starting from the square number 1 and some arbitrary color. If the square was painted in color x, then the next square will be painted in color x + 1. In case of x = n, next square is painted in color 1. If there is no more paint of the color Vika wants to use now, then she stops.Square is always painted in only one color, and it takes exactly 1 liter of paint. Your task is to calculate the maximum number of squares that might be painted, if Vika chooses right color to paint the first square.
256 megabytes
import java.io.*; import java.util.*; public class B { void solve() { int n = in.nextInt(); int[] colors = new int[n]; for (int i = 0; i < n; i++) { colors[i] = in.nextInt(); } List<Integer> indxs = new ArrayList<>(); int min = colors[0]; for (int i = 0; i < n; i++) { if (min > colors[i]) min = colors[i]; } for (int i = 0; i < n; i++) { if (colors[i] == min) indxs.add(i); } if (indxs.size() == n){ out.print((long)min*n); return; } if (indxs.size() == 1){ int len = n - 1; out.print((long)n*min + len); return; } int cycleLen = n - indxs.get(indxs.size() - 1) - 1 + indxs.get(0); int difLen = -1; // int indxMaxLen = -1; for (int i = 1; i < indxs.size(); i++) { int len = indxs.get(i) - indxs.get(i - 1) - 1; if (len > difLen){ difLen = len; // indxMaxLen = indxs.get(i - 1) + 1; } } int maxLen = Integer.max(cycleLen, difLen); out.print((long)n*min + maxLen); } InputReader in; PrintWriter out; void runIO() { in = new InputReader(System.in); out = new PrintWriter(System.out); solve(); out.close(); } class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String next() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } public static void main(String[] args) { new B().runIO(); } }
Java
["5\n2 4 2 3 3", "3\n5 5 5", "6\n10 10 10 1 10 10"]
2 seconds
["12", "15", "11"]
NoteIn the first sample the best strategy is to start painting using color 4. Then the squares will be painted in the following colors (from left to right): 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5.In the second sample Vika can start to paint using any color.In the third sample Vika should start painting using color number 5.
Java 8
standard input
[ "constructive algorithms", "implementation" ]
e2db09803d87362c67763ef71e8b7f47
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of jars with colors Vika has. The second line of the input contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is equal to the number of liters of paint in the i-th jar, i.e. the number of liters of color i that Vika has.
1,300
The only line of the output should contain a single integer — the maximum number of squares that Vika can paint if she follows the rules described above.
standard output
PASSED
da4d5442c09cf8c95e654b3c2e272a1b
train_002.jsonl
1451215200
Vika has n jars with paints of distinct colors. All the jars are numbered from 1 to n and the i-th jar contains ai liters of paint of color i.Vika also has an infinitely long rectangular piece of paper of width 1, consisting of squares of size 1 × 1. Squares are numbered 1, 2, 3 and so on. Vika decided that she will start painting squares one by one from left to right, starting from the square number 1 and some arbitrary color. If the square was painted in color x, then the next square will be painted in color x + 1. In case of x = n, next square is painted in color 1. If there is no more paint of the color Vika wants to use now, then she stops.Square is always painted in only one color, and it takes exactly 1 liter of paint. Your task is to calculate the maximum number of squares that might be painted, if Vika chooses right color to paint the first square.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Scanner; import java.util.ArrayList; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Likai */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { public void solve(int testNumber, Scanner in, PrintWriter out) { while (testNumber-- > 0) { int n = in.nextInt(); int[] a = new int[n]; int minval = 1000000001; ArrayList<Integer> poslist = new ArrayList<>(); for (int i = 0; i < n; ++i) { a[i] = in.nextInt(); if (a[i] < minval) { minval = a[i]; } } for (int i = 0; i < n; ++i) { if (a[i] == minval) { poslist.add(i); } } int bidx = poslist.get(0); int lidx = poslist.get(poslist.size() - 1); int maxd = n - lidx + bidx; for (int i = 1; i < poslist.size(); ++i) { int idx = poslist.get(i); if (idx - bidx > maxd) { maxd = idx - bidx; } bidx = idx; } out.println((long) minval * n + maxd - 1); } } } }
Java
["5\n2 4 2 3 3", "3\n5 5 5", "6\n10 10 10 1 10 10"]
2 seconds
["12", "15", "11"]
NoteIn the first sample the best strategy is to start painting using color 4. Then the squares will be painted in the following colors (from left to right): 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5.In the second sample Vika can start to paint using any color.In the third sample Vika should start painting using color number 5.
Java 8
standard input
[ "constructive algorithms", "implementation" ]
e2db09803d87362c67763ef71e8b7f47
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of jars with colors Vika has. The second line of the input contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is equal to the number of liters of paint in the i-th jar, i.e. the number of liters of color i that Vika has.
1,300
The only line of the output should contain a single integer — the maximum number of squares that Vika can paint if she follows the rules described above.
standard output
PASSED
f2790fe23a1c01a20dc528aa04d09c21
train_002.jsonl
1451215200
Vika has n jars with paints of distinct colors. All the jars are numbered from 1 to n and the i-th jar contains ai liters of paint of color i.Vika also has an infinitely long rectangular piece of paper of width 1, consisting of squares of size 1 × 1. Squares are numbered 1, 2, 3 and so on. Vika decided that she will start painting squares one by one from left to right, starting from the square number 1 and some arbitrary color. If the square was painted in color x, then the next square will be painted in color x + 1. In case of x = n, next square is painted in color 1. If there is no more paint of the color Vika wants to use now, then she stops.Square is always painted in only one color, and it takes exactly 1 liter of paint. Your task is to calculate the maximum number of squares that might be painted, if Vika chooses right color to paint the first square.
256 megabytes
import java.util.ArrayList; import java.util.Scanner; public class hef { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int a[] = new int[n]; long min = Long.MAX_VALUE; for(int i=0;i<a.length;i++) { a[i] = s.nextInt(); min = Math.min(min,a[i]); } ArrayList<Integer> a1 = new ArrayList<>(); for(int i=0;i<a.length;i++) { if(a[i]==min) { a1.add(i); } } int min1 = a.length-1-a1.get(a1.size()-1)+a1.get(0); for(int i=1;i<a1.size();i++) { if(a1.get(i)-a1.get(i-1)-1>min1) { min1 = a1.get(i)-a1.get(i-1)-1; } } System.out.println(a.length*min+min1); } }
Java
["5\n2 4 2 3 3", "3\n5 5 5", "6\n10 10 10 1 10 10"]
2 seconds
["12", "15", "11"]
NoteIn the first sample the best strategy is to start painting using color 4. Then the squares will be painted in the following colors (from left to right): 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5.In the second sample Vika can start to paint using any color.In the third sample Vika should start painting using color number 5.
Java 8
standard input
[ "constructive algorithms", "implementation" ]
e2db09803d87362c67763ef71e8b7f47
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of jars with colors Vika has. The second line of the input contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is equal to the number of liters of paint in the i-th jar, i.e. the number of liters of color i that Vika has.
1,300
The only line of the output should contain a single integer — the maximum number of squares that Vika can paint if she follows the rules described above.
standard output
PASSED
22aa0edb72a1e4c8ab3e1f1f74084acc
train_002.jsonl
1451215200
Vika has n jars with paints of distinct colors. All the jars are numbered from 1 to n and the i-th jar contains ai liters of paint of color i.Vika also has an infinitely long rectangular piece of paper of width 1, consisting of squares of size 1 × 1. Squares are numbered 1, 2, 3 and so on. Vika decided that she will start painting squares one by one from left to right, starting from the square number 1 and some arbitrary color. If the square was painted in color x, then the next square will be painted in color x + 1. In case of x = n, next square is painted in color 1. If there is no more paint of the color Vika wants to use now, then she stops.Square is always painted in only one color, and it takes exactly 1 liter of paint. Your task is to calculate the maximum number of squares that might be painted, if Vika chooses right color to paint the first square.
256 megabytes
import java.io.*; import java.util.*; /* * This file was created by ayush in attempt to solve the problem problems */ public class main { public void solve(int n,int[] litres, PrintWriter out) { int min = 2000000000; for(int i=0;i<n;i++){ min = Math.min(min,litres[i]); } int[] pos = new int[2000001]; int index = 0; for(int i =0;i<n;i++){ if(litres[i]==min){ pos[index++]=i; } } pos[index++]=pos[0]+n; long ans=n*(long)min; int max = 0; for(int i=0;i+1<index;i++){ max = Math.max(max,pos[i+1]-pos[i]); } ans+=max-1; out.println(ans); } public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int n = Integer.parseInt(in.readLine()); int[] litres =IOUtils.readLinearIntArray(in); Date t1 = new Date(); main solver = new main(); solver.solve(n,litres, out); out.flush(); Date t2 = new Date(); System.err.println(String.format("Your program took %f seconds", (t2.getTime() - t1.getTime()) / 1000.0)); out.close(); } static class IOUtils { public static int[] readIntArray(Scanner in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = in.nextInt(); return array; } public static String[] readStringArray(Scanner in, int size) { String[] array = new String[size]; for (int i = 0; i < size; i++) array[i] = in.nextLine(); return array; } public static int[] readLinearIntArray(Scanner in, int size) { //in.nextLine(); String[] arr = in.nextLine().split(" "); int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = Integer.parseInt(arr[i]); return array; } public static int[] readLinearIntArray(BufferedReader in) throws IOException { //in.nextLine(); String[] arr = in.readLine().split(" "); int[] array = new int[arr.length]; for (int i = 0; i < arr.length; i++) array[i] = Integer.parseInt(arr[i]); return array; } public static Double[] readLinearDoubleArray(BufferedReader in) throws IOException { //in.nextLine(); String[] arr = in.readLine().split(" "); Double[] array = new Double[arr.length]; for (int i = 0; i < arr.length; i++) array[i] = Double.parseDouble(arr[i]); return array; } public static String[] convert(int[] from) { String[] to = new String[from.length]; for (int i = 0; i < to.length; i++) to[i] = String.valueOf(from[i]); return to; } public static int[] convert(String[] from) { int[] to = new int[from.length]; for (int i = 0; i < to.length; i++) to[i] = Integer.parseInt(from[i]); return to; } public static int[][] read2DIntArray(BufferedReader in, int rows, int columns, String seprator) throws IOException { int[][] array = new int[rows][columns]; for (int i = 0; i < rows; i++) { array[i] = convert(in.readLine().split(seprator)); } return array; } public static String[][] read2DStringArray(BufferedReader in, int rows, int columns, String seprator) throws IOException { String[][] array = new String[rows][columns]; for (int i = 0; i < rows; i++) { array[i] = in.readLine().split(seprator); } return array; } } static class DEBUG { public static void DebugInfo(String disp) { System.err.println("DEBUG Info: " + disp); } public static void DebugVariable(String variable, String value) { System.err.println("DEBUG Info: " + variable + " => " + value); } public static void DebugVariable(String variable, int value) { System.err.println("DEBUG Info: " + variable + " => " + value); } public static void DebugVariable(String variable, long value) { System.err.println("DEBUG Info: " + variable + " => " + value); } public static void DebugArray(int[] value) { for (int i = 0; i < value.length; i++) { System.err.println("DEBUG Info: " + i + " => " + value[i]); } } } }
Java
["5\n2 4 2 3 3", "3\n5 5 5", "6\n10 10 10 1 10 10"]
2 seconds
["12", "15", "11"]
NoteIn the first sample the best strategy is to start painting using color 4. Then the squares will be painted in the following colors (from left to right): 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5.In the second sample Vika can start to paint using any color.In the third sample Vika should start painting using color number 5.
Java 8
standard input
[ "constructive algorithms", "implementation" ]
e2db09803d87362c67763ef71e8b7f47
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of jars with colors Vika has. The second line of the input contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is equal to the number of liters of paint in the i-th jar, i.e. the number of liters of color i that Vika has.
1,300
The only line of the output should contain a single integer — the maximum number of squares that Vika can paint if she follows the rules described above.
standard output
PASSED
768eda3a8ec36d2a7b9753ef1738d509
train_002.jsonl
1451215200
Vika has n jars with paints of distinct colors. All the jars are numbered from 1 to n and the i-th jar contains ai liters of paint of color i.Vika also has an infinitely long rectangular piece of paper of width 1, consisting of squares of size 1 × 1. Squares are numbered 1, 2, 3 and so on. Vika decided that she will start painting squares one by one from left to right, starting from the square number 1 and some arbitrary color. If the square was painted in color x, then the next square will be painted in color x + 1. In case of x = n, next square is painted in color 1. If there is no more paint of the color Vika wants to use now, then she stops.Square is always painted in only one color, and it takes exactly 1 liter of paint. Your task is to calculate the maximum number of squares that might be painted, if Vika chooses right color to paint the first square.
256 megabytes
/* * Code Author: Jayesh Udhani * Dhirubhai Ambani Institute of Information and Communication Technology (DA-IICT ,Gandhinagar) * 2nd Year ICT BTECH Student */ import java.io.*; import java.util.*; public class Main { public static void main(String args[]) { InputReader in = new InputReader(System.in); OutputStream outputStream = System.out; PrintWriter out = new PrintWriter(outputStream); //----------My Code Starts Here---------- int n=in.nextInt(),i; long min=Long.MAX_VALUE,max=Long.MIN_VALUE; long[] a=new long[n]; // String str=in.nextLine(); // String s[]=str.split(" "); for(i=0;i<n;i++) a[i]=in.nextInt(); List<Integer> al = new ArrayList<>(); for(i=0;i<n;i++) { if(a[i]<min) min=a[i]; } for(i=0;i<n;i++) { if(a[i]==min) al.add(i+1); } if(al.size()==n) { System.out.println((long)min*n); return; } else if(al.size()==1) { System.out.println((long)((min*n)+(n-1))); } else { for(i=0;i<al.size()-1;i++) { if(al.get(i+1) - al.get(i) -1 >max) max = al.get(i+1) - al.get(i) -1; } if(al.get(0)-1+n-al.get(al.size()-1) > max) max = al.get(0)-1+n-al.get(al.size()-1); System.out.println((long)((long)min*n)+max); } //---------------The End——————————————————— } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream inputstream) { reader = new BufferedReader(new InputStreamReader(inputstream)); tokenizer = null; } public String nextLine(){ String fullLine=null; while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { fullLine=reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return fullLine; } return fullLine; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["5\n2 4 2 3 3", "3\n5 5 5", "6\n10 10 10 1 10 10"]
2 seconds
["12", "15", "11"]
NoteIn the first sample the best strategy is to start painting using color 4. Then the squares will be painted in the following colors (from left to right): 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5.In the second sample Vika can start to paint using any color.In the third sample Vika should start painting using color number 5.
Java 8
standard input
[ "constructive algorithms", "implementation" ]
e2db09803d87362c67763ef71e8b7f47
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of jars with colors Vika has. The second line of the input contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is equal to the number of liters of paint in the i-th jar, i.e. the number of liters of color i that Vika has.
1,300
The only line of the output should contain a single integer — the maximum number of squares that Vika can paint if she follows the rules described above.
standard output
PASSED
eaea837d8ea7d30a2092d946d590e3b9
train_002.jsonl
1451215200
Vika has n jars with paints of distinct colors. All the jars are numbered from 1 to n and the i-th jar contains ai liters of paint of color i.Vika also has an infinitely long rectangular piece of paper of width 1, consisting of squares of size 1 × 1. Squares are numbered 1, 2, 3 and so on. Vika decided that she will start painting squares one by one from left to right, starting from the square number 1 and some arbitrary color. If the square was painted in color x, then the next square will be painted in color x + 1. In case of x = n, next square is painted in color 1. If there is no more paint of the color Vika wants to use now, then she stops.Square is always painted in only one color, and it takes exactly 1 liter of paint. Your task is to calculate the maximum number of squares that might be painted, if Vika chooses right color to paint the first square.
256 megabytes
import java.io.*; import java.util.*; public class Main { private void solve() { int n = nextInt(); int min=1000000000; int a[] = new int[n]; int rast[] = new int[n]; int all[] = new int[n]; for (int i = 0; i < n; i++) { a[i]= nextInt(); if(min>=a[i]){ min=a[i]; } } int k=-1; int first=0,last=0; int max=0; int t=0; for (int i = 0; i < n; i++) { if(min==a[i]){ if(k==-1)first=i; k++; all[k]=i; last=i; } if(k!=-1) { rast[k]++; if (max < rast[k]) { max = rast[k]; t = k; } } } rast[k]=(first+n)-last; if(max<rast[k]){ max=rast[k]; t=k; } // out.println(first+" "+last); /*for (int i = 0; i < k; i++) { out.println(rast[i]); }*/ // out.println(max); int i=all[t]+1; /*int kol=0; if(i==n)i=0;*/ /*while (a[i]!=0){ a[i]--; i++; if(i==n)i=0; kol++; }*/ long l = (long)n*min+max-1; out.print(l); } public static void main(String[] args) { new Main().run(); } BufferedReader br; StringTokenizer st; PrintWriter out; private void run() { try { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); //br = new BufferedReader(new FileReader("birthday.in")); //out = new PrintWriter(new FileWriter("birthday.out")); solve(); br.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } private int nextInt() { return Integer.parseInt(next()); } private String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); return "END_OF_FILE"; } } return st.nextToken(); } }
Java
["5\n2 4 2 3 3", "3\n5 5 5", "6\n10 10 10 1 10 10"]
2 seconds
["12", "15", "11"]
NoteIn the first sample the best strategy is to start painting using color 4. Then the squares will be painted in the following colors (from left to right): 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5.In the second sample Vika can start to paint using any color.In the third sample Vika should start painting using color number 5.
Java 8
standard input
[ "constructive algorithms", "implementation" ]
e2db09803d87362c67763ef71e8b7f47
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of jars with colors Vika has. The second line of the input contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is equal to the number of liters of paint in the i-th jar, i.e. the number of liters of color i that Vika has.
1,300
The only line of the output should contain a single integer — the maximum number of squares that Vika can paint if she follows the rules described above.
standard output
PASSED
829a60c19dcdc4f42bfdf2a0388408a5
train_002.jsonl
1451215200
Vika has n jars with paints of distinct colors. All the jars are numbered from 1 to n and the i-th jar contains ai liters of paint of color i.Vika also has an infinitely long rectangular piece of paper of width 1, consisting of squares of size 1 × 1. Squares are numbered 1, 2, 3 and so on. Vika decided that she will start painting squares one by one from left to right, starting from the square number 1 and some arbitrary color. If the square was painted in color x, then the next square will be painted in color x + 1. In case of x = n, next square is painted in color 1. If there is no more paint of the color Vika wants to use now, then she stops.Square is always painted in only one color, and it takes exactly 1 liter of paint. Your task is to calculate the maximum number of squares that might be painted, if Vika chooses right color to paint the first square.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class OneNumber { static FastReader in=new FastReader(); public static void main(String[] args) throws IOException { long n=in.nextInt(), sum=0,cho=Integer.MAX_VALUE,max=0; long ans=0l; ArrayList<Integer> A=new ArrayList(); long a[]; a=new long[(int)n]; for(int i=0;i<n;i++){ a[i]=in.nextInt(); sum+=a[i]; if(cho>a[i])cho=a[i];} long min =(int) cho; for(int i=0;i<n;i++){if(a[i]==cho)A.add(i);} if(A.size()>=1){ for(int i=0;i<A.size()-1;i++){ if(A.get(i+1)-A.get(i)>max){max=A.get(i+1)-A.get(i);cho=A.get(i);} } if(n-A.get(A.size()-1)+A.get(0)>max){cho=A.get(A.size()-1);max=n-A.get(A.size()-1)+A.get(0);} ans=n*(min); ans+=max-1; } else {ans=n*(min+1);ans--;} System.out.println(ans); } } class FastReader { private BufferedReader br; private StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public String next() throws IOException { while (st == null || !st.hasMoreElements()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } }
Java
["5\n2 4 2 3 3", "3\n5 5 5", "6\n10 10 10 1 10 10"]
2 seconds
["12", "15", "11"]
NoteIn the first sample the best strategy is to start painting using color 4. Then the squares will be painted in the following colors (from left to right): 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5.In the second sample Vika can start to paint using any color.In the third sample Vika should start painting using color number 5.
Java 8
standard input
[ "constructive algorithms", "implementation" ]
e2db09803d87362c67763ef71e8b7f47
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of jars with colors Vika has. The second line of the input contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is equal to the number of liters of paint in the i-th jar, i.e. the number of liters of color i that Vika has.
1,300
The only line of the output should contain a single integer — the maximum number of squares that Vika can paint if she follows the rules described above.
standard output
PASSED
f1bc56e4cc9335072edade5777fd9235
train_002.jsonl
1451215200
Vika has n jars with paints of distinct colors. All the jars are numbered from 1 to n and the i-th jar contains ai liters of paint of color i.Vika also has an infinitely long rectangular piece of paper of width 1, consisting of squares of size 1 × 1. Squares are numbered 1, 2, 3 and so on. Vika decided that she will start painting squares one by one from left to right, starting from the square number 1 and some arbitrary color. If the square was painted in color x, then the next square will be painted in color x + 1. In case of x = n, next square is painted in color 1. If there is no more paint of the color Vika wants to use now, then she stops.Square is always painted in only one color, and it takes exactly 1 liter of paint. Your task is to calculate the maximum number of squares that might be painted, if Vika chooses right color to paint the first square.
256 megabytes
import java.util.*; /** * Created by slie742 on 27/02/2016. */ public class VikaAndSquares { private static final Scanner INPUT = new Scanner(System.in); public static void main(String[] args) { int n = INPUT.nextInt(); int [] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = INPUT.nextInt(); } int min = Integer.MAX_VALUE; List<Integer> minPos = new ArrayList<>(); for (int i = 0; i < n; i++) { if (a[i] < min) { min = a[i]; minPos.clear(); minPos.add(i); } else if (a[i] == min) { minPos.add(i); } } int maxSeparation = -1; for (int i = 0; i < minPos.size() - 1; i++) { if (minPos.get(i+1) - minPos.get(i) > maxSeparation) { maxSeparation = minPos.get(i+1) - minPos.get(i); } } if (n + minPos.get(0)-minPos.get(minPos.size()-1) > maxSeparation) { maxSeparation = n + minPos.get(0)-minPos.get(minPos.size()-1) ; } /*if (n == 300) { //System.out.println("minPos = " + Arrays.toString(minPos.toArray())); System.out.println("maxSeparation = " + maxSeparation); System.out.println("min = " + min); System.out.println("n = " + n); }*/ long number = ((long) min)*n + maxSeparation - 1; // number += maxSeparation - 1; System.out.println(number); } }
Java
["5\n2 4 2 3 3", "3\n5 5 5", "6\n10 10 10 1 10 10"]
2 seconds
["12", "15", "11"]
NoteIn the first sample the best strategy is to start painting using color 4. Then the squares will be painted in the following colors (from left to right): 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5.In the second sample Vika can start to paint using any color.In the third sample Vika should start painting using color number 5.
Java 8
standard input
[ "constructive algorithms", "implementation" ]
e2db09803d87362c67763ef71e8b7f47
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of jars with colors Vika has. The second line of the input contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is equal to the number of liters of paint in the i-th jar, i.e. the number of liters of color i that Vika has.
1,300
The only line of the output should contain a single integer — the maximum number of squares that Vika can paint if she follows the rules described above.
standard output
PASSED
729cbac4845c50ff2871b252feea1366
train_002.jsonl
1451215200
Vika has n jars with paints of distinct colors. All the jars are numbered from 1 to n and the i-th jar contains ai liters of paint of color i.Vika also has an infinitely long rectangular piece of paper of width 1, consisting of squares of size 1 × 1. Squares are numbered 1, 2, 3 and so on. Vika decided that she will start painting squares one by one from left to right, starting from the square number 1 and some arbitrary color. If the square was painted in color x, then the next square will be painted in color x + 1. In case of x = n, next square is painted in color 1. If there is no more paint of the color Vika wants to use now, then she stops.Square is always painted in only one color, and it takes exactly 1 liter of paint. Your task is to calculate the maximum number of squares that might be painted, if Vika chooses right color to paint the first square.
256 megabytes
import java.util.Scanner; public class B { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n=sc.nextInt(); long[] arr=new long[n+1]; for (int i = 1; i < arr.length; i++) { arr[i]=sc.nextInt(); } long res=0,min=arr[1],count=0,maxcount=0,start=1,stop=1; for (int i = 2; i < arr.length; i++) { if(arr[i]<min){ min=arr[i]; if(count>maxcount) maxcount=count; count=0; start=i; stop=i; } else if(arr[i]>min){ count++; } else{ if(count>maxcount) maxcount=count; count=0; stop=i; } } if(count>maxcount){ maxcount=count; } if(n-stop+start-1>maxcount){ maxcount=n-stop+start-1; } res=min*n+maxcount; // if(n==300){ // System.out.println(maxcount); // System.out.println(start); // System.out.println(stop); // } System.out.println(res); sc.close(); } }
Java
["5\n2 4 2 3 3", "3\n5 5 5", "6\n10 10 10 1 10 10"]
2 seconds
["12", "15", "11"]
NoteIn the first sample the best strategy is to start painting using color 4. Then the squares will be painted in the following colors (from left to right): 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5.In the second sample Vika can start to paint using any color.In the third sample Vika should start painting using color number 5.
Java 8
standard input
[ "constructive algorithms", "implementation" ]
e2db09803d87362c67763ef71e8b7f47
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of jars with colors Vika has. The second line of the input contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is equal to the number of liters of paint in the i-th jar, i.e. the number of liters of color i that Vika has.
1,300
The only line of the output should contain a single integer — the maximum number of squares that Vika can paint if she follows the rules described above.
standard output
PASSED
6d836b88095fe8980f31e72eea8ec923
train_002.jsonl
1386493200
There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor.Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: Add xi liters of water to the pi-th vessel; Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import static java.lang.Math.*; import static java.lang.Integer.*; public class D218 { int INF = Integer.MAX_VALUE / 100; static Scanner sc = null; static BufferedReader br = null; static PrintStream out = null; static BufferedWriter bw = null; int N = 0; public void solve() throws Exception{ int n = nextInt(); int[] cap = nextInts(); int[] d = new int[n]; int m = nextInt(); TreeSet<Integer> rems = new TreeSet<Integer>(); for(int i = 0; i < n; i++){ rems.add(i); } for(int t = 0; t < m; t++){ int[] in = nextInts(); if(in.length == 3){ int num = in[2]; int idx = in[1] - 1; while(num > 0 && idx >= 0){ if(rems.contains(idx)){ if(num >= cap[idx] - d[idx]){ num -= cap[idx] - d[idx]; d[idx] = cap[idx]; rems.remove(idx); Integer high = rems.higher(idx); if(high == null){ break; } idx = high; } else{ d[idx] += num; num = 0; } } else{ Integer high = rems.higher(idx); if(high == null){ break; } idx = high; } } } else{ out.println(d[in[1]-1]); } } } public int[] readIntArray(int n) { int[] ret = new int[n]; for (int i = 0; i < n; i++) { ret[i] = sc.nextInt(); } return ret; } private int nextInt() throws IOException{ String s = br.readLine(); return parseInt(s); } private int[] nextInts() throws IOException{ String s = br.readLine(); String[] sp = s.split(" "); int[] r = new int[sp.length]; for(int i = 0;i < sp.length; i++){ r[i] = parseInt(sp[i]); } return r; } /** * @param args */ public static void main(String[] args) throws Exception{ File file = new File("input.txt"); if(file.exists()){ System.setIn(new BufferedInputStream(new FileInputStream("input.txt"))); } out = System.out; bw = new BufferedWriter(new PrintWriter(out)); //sc = new Scanner(System.in); br = new BufferedReader(new InputStreamReader(System.in)); D218 t = new D218(); t.solve(); bw.close(); } }
Java
["2\n5 10\n6\n1 1 4\n2 1\n1 2 5\n1 1 4\n2 1\n2 2", "3\n5 10 8\n6\n1 1 12\n2 2\n1 1 6\n1 3 2\n2 2\n2 3"]
2 seconds
["4\n5\n8", "7\n10\n5"]
null
Java 7
standard input
[ "data structures", "dsu", "implementation", "trees" ]
37e2bb1c7caeeae7f8a7c837a2b390c9
The first line contains integer n — the number of vessels (1 ≤ n ≤ 2·105). The second line contains n integers a1, a2, ..., an — the vessels' capacities (1 ≤ ai ≤ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m — the number of queries (1 ≤ m ≤ 2·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≤ pi ≤ n, 1 ≤ xi ≤ 109, 1 ≤ ki ≤ n).
1,800
For each query, print on a single line the number of liters of water in the corresponding vessel.
standard output
PASSED
7f1e0433e5b92c76804ec24eb875127b
train_002.jsonl
1386493200
There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor.Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: Add xi liters of water to the pi-th vessel; Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Main { static BufferedReader br; static StringTokenizer st; static PrintWriter out; public static String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public static int nextInt() throws IOException { return Integer.parseInt(next()); } static int[] a, b, p; static int n; static int get(int i) { if (i != p[i]) p[i] = get(p[i]); return p[i]; } public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); n = nextInt(); a = new int[n + 1]; b = new int[n + 1]; p = new int[n + 1]; for (int i = 0; i < n; ++i) { a[i] = nextInt(); p[i] = i; } p[n] = n; int m = nextInt(), k, x, tip; for (int iter = 0; iter < m; ++iter) { tip = nextInt(); if (tip == 1) { k = nextInt() - 1; x = nextInt(); while (k < n && x > 0) { k = get(k); if (k < n) { int t = Math.max(0, a[k] - b[k]); t = Math.min(t, x); b[k] += t; if (a[k] == b[k]) { p[k] = k + 1; } x -= t; } k++; } } else { k = nextInt() - 1; out.println(b[k]); } } out.close(); } }
Java
["2\n5 10\n6\n1 1 4\n2 1\n1 2 5\n1 1 4\n2 1\n2 2", "3\n5 10 8\n6\n1 1 12\n2 2\n1 1 6\n1 3 2\n2 2\n2 3"]
2 seconds
["4\n5\n8", "7\n10\n5"]
null
Java 7
standard input
[ "data structures", "dsu", "implementation", "trees" ]
37e2bb1c7caeeae7f8a7c837a2b390c9
The first line contains integer n — the number of vessels (1 ≤ n ≤ 2·105). The second line contains n integers a1, a2, ..., an — the vessels' capacities (1 ≤ ai ≤ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m — the number of queries (1 ≤ m ≤ 2·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≤ pi ≤ n, 1 ≤ xi ≤ 109, 1 ≤ ki ≤ n).
1,800
For each query, print on a single line the number of liters of water in the corresponding vessel.
standard output
PASSED
d9b97571fe743df91f8c571829442656
train_002.jsonl
1386493200
There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor.Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: Add xi liters of water to the pi-th vessel; Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels.
256 megabytes
import java.util.*; import java.io.*; public class TaskD { public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int[] a = new int[n]; for (int i=0;i<n;i++) { a[i] = in.nextInt(); } int m = in.nextInt(); int[] b = new int[n]; TreeSet<Integer> nonEmpty = new TreeSet<Integer>(); for (int i=0;i<n;i++) { nonEmpty.add(i); } in.nextLine(); for (int i=0;i<m;i++) { String s = in.nextLine(); String[] c = s.split(" "); if (c[0].equals("1")) { int p = Integer.parseInt(c[1])-1; int x = Integer.parseInt(c[2]); while (x > 0) { Integer pos; if (a[p] - b[p] > 0) pos = p; else pos = nonEmpty.higher(p); if (pos == null) break; int t = a[pos] - b[pos]; if (t >= x) { b[pos] += x; x = 0; } else { b[pos] = a[pos]; nonEmpty.remove(pos); x -= t; } } } else { int p = Integer.parseInt(c[1]) - 1; out.println(b[p]); } } out.close(); } }
Java
["2\n5 10\n6\n1 1 4\n2 1\n1 2 5\n1 1 4\n2 1\n2 2", "3\n5 10 8\n6\n1 1 12\n2 2\n1 1 6\n1 3 2\n2 2\n2 3"]
2 seconds
["4\n5\n8", "7\n10\n5"]
null
Java 7
standard input
[ "data structures", "dsu", "implementation", "trees" ]
37e2bb1c7caeeae7f8a7c837a2b390c9
The first line contains integer n — the number of vessels (1 ≤ n ≤ 2·105). The second line contains n integers a1, a2, ..., an — the vessels' capacities (1 ≤ ai ≤ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m — the number of queries (1 ≤ m ≤ 2·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≤ pi ≤ n, 1 ≤ xi ≤ 109, 1 ≤ ki ≤ n).
1,800
For each query, print on a single line the number of liters of water in the corresponding vessel.
standard output
PASSED
a07f005ee4094b1de7900bdaef2223d3
train_002.jsonl
1386493200
There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor.Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: Add xi liters of water to the pi-th vessel; Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels.
256 megabytes
import java.io.IOException; import java.io.PrintWriter; import java.util.InputMismatchException; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author hitarthk */ public class C_218_D { public static void main(String[] args) { FasterScanner in=new FasterScanner(); PrintWriter out=new PrintWriter(System.out); int n=in.nextInt(); int[] c=in.nextIntArray(n); int[] f=new int[n]; int[] parent=new int[n+1]; for(int i=0;i<=n;i++){ parent[i]=i; } int m=in.nextInt(); while(m>0){ m--; int q=in.nextInt(); if(q==1){ int p=in.nextInt()-1; int x=in.nextInt(); while(x>0 && p<n){ //System.out.println("x "+x); { int X=x; x-=Math.min(x, c[p]-f[p]); f[p]=Math.min(c[p], f[p]+X); if(f[p]==c[p]){ parent[p]=p+1; } while (p != parent[p]) { //System.out.println("Hre"); parent[p] = parent[parent[p]]; // path compression by halving p = parent[p]; } } } } else{ int k=in.nextInt()-1; System.out.println(f[k]); } } out.close(); } /* 10 71 59 88 55 18 98 38 73 53 58 20 1 5 93 1 7 69 2 3 1 1 20 2 10 1 6 74 1 7 100 1 9 14 2 3 2 4 2 7 1 3 31 2 4 1 6 64 2 2 2 2 1 3 54 2 9 2 1 1 6 86 */ 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
["2\n5 10\n6\n1 1 4\n2 1\n1 2 5\n1 1 4\n2 1\n2 2", "3\n5 10 8\n6\n1 1 12\n2 2\n1 1 6\n1 3 2\n2 2\n2 3"]
2 seconds
["4\n5\n8", "7\n10\n5"]
null
Java 7
standard input
[ "data structures", "dsu", "implementation", "trees" ]
37e2bb1c7caeeae7f8a7c837a2b390c9
The first line contains integer n — the number of vessels (1 ≤ n ≤ 2·105). The second line contains n integers a1, a2, ..., an — the vessels' capacities (1 ≤ ai ≤ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m — the number of queries (1 ≤ m ≤ 2·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≤ pi ≤ n, 1 ≤ xi ≤ 109, 1 ≤ ki ≤ n).
1,800
For each query, print on a single line the number of liters of water in the corresponding vessel.
standard output
PASSED
5f06a2ef7d417365d503e90852129c40
train_002.jsonl
1386493200
There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor.Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: Add xi liters of water to the pi-th vessel; Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.InputMismatchException; import java.util.Scanner; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author MojtabaPC */ public class Main { /** * @param args the command line arguments * */ static int nextIndex; public static void main(String[] args) throws IOException { //Scanner in = new Scanner(System.in); FastScanner in; in = new FastScanner((InputStream) System.in); int zarf; int kar; zarf = in.nextInt(); Zarf[] zoroof = new Zarf[zarf]; for (int i = 0; i < zarf; i++) { zoroof[i] = new Zarf(0, in.nextInt(), i + 1); } kar = in.nextInt(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < kar; i++) { int chikar = in.nextInt(); switch (chikar) { case 1: int index = in.nextInt() - 1; int addit = in.nextInt(); add(zoroof, index, addit); break; case 2: sb.append(zoroof[in.nextInt() - 1].hajm).append("\n"); //System.out.println(a[in.nextInt() - 1][0]); } } System.out.print(sb); } private static void add(Zarf[] zoroof, int index, int addit) { if (index >= zoroof.length) { return; } zoroof[index].hajm += addit; int temp = zoroof[index].hajm - zoroof[index].gonjayesh; if (temp <= 0) { return; } zoroof[index].hajm = zoroof[index].gonjayesh; nextIndex = index + 1; add(zoroof, zoroof[index].nextIndex, temp); zoroof[index].nextIndex = nextIndex; } } class Zarf { int hajm, gonjayesh; int nextIndex; public Zarf(int hajm, int gonjayesh, int nextIndex) { this.hajm = hajm; this.gonjayesh = gonjayesh; this.nextIndex = nextIndex; } } class FastScanner { private InputStream stream; private byte[] buffer = new byte[1024]; private int curChar; private int numChars; public FastScanner(InputStream stream) { this.stream = stream; } int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buffer); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buffer[curChar++]; } boolean isWhiteSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } boolean isEndline(int c) { return c == '\n' || c == '\r' || c == -1; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String next() { int c = read(); while (isWhiteSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isWhiteSpaceChar(c)); return res.toString(); } String nextLine() { int c = read(); while (isEndline(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndline(c)); return res.toString(); } }
Java
["2\n5 10\n6\n1 1 4\n2 1\n1 2 5\n1 1 4\n2 1\n2 2", "3\n5 10 8\n6\n1 1 12\n2 2\n1 1 6\n1 3 2\n2 2\n2 3"]
2 seconds
["4\n5\n8", "7\n10\n5"]
null
Java 7
standard input
[ "data structures", "dsu", "implementation", "trees" ]
37e2bb1c7caeeae7f8a7c837a2b390c9
The first line contains integer n — the number of vessels (1 ≤ n ≤ 2·105). The second line contains n integers a1, a2, ..., an — the vessels' capacities (1 ≤ ai ≤ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m — the number of queries (1 ≤ m ≤ 2·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≤ pi ≤ n, 1 ≤ xi ≤ 109, 1 ≤ ki ≤ n).
1,800
For each query, print on a single line the number of liters of water in the corresponding vessel.
standard output
PASSED
556bf7df4ba37355d68b47f50e99b3b2
train_002.jsonl
1386493200
There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor.Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: Add xi liters of water to the pi-th vessel; Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Map; import java.util.SortedMap; import java.util.StringTokenizer; import java.util.TreeMap; public class D { public static void main(String[] args) { MyScanner in = new MyScanner(); int N = in.nextInt(); long[] cur = new long[N]; TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>(); for (int i = 0; i < N; i++) { map.put(i, in.nextInt()); cur[i] = 0; } int M = in.nextInt(); for (int i = 0; i < M; i++) { int type = in.nextInt(); // Pouring if (type == 1) { int start = in.nextInt() - 1; long toAdd = in.nextLong(); while (toAdd > 0) { if (start >= N) break; Map.Entry<Integer, Integer> e = map.ceilingEntry(start); if (e == null) break; // Overflow and continue if (e.getValue() <= toAdd) { cur[e.getKey()] += e.getValue(); map.remove(e.getKey()); } // Done else { cur[e.getKey()] += toAdd; int next = (int)(e.getValue() - toAdd); map.put(e.getKey(), next); } toAdd -= e.getValue(); start++; } } // Query else { int toPrint = in.nextInt() - 1; System.out.println(cur[toPrint]); } } } //-----------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\n5 10\n6\n1 1 4\n2 1\n1 2 5\n1 1 4\n2 1\n2 2", "3\n5 10 8\n6\n1 1 12\n2 2\n1 1 6\n1 3 2\n2 2\n2 3"]
2 seconds
["4\n5\n8", "7\n10\n5"]
null
Java 7
standard input
[ "data structures", "dsu", "implementation", "trees" ]
37e2bb1c7caeeae7f8a7c837a2b390c9
The first line contains integer n — the number of vessels (1 ≤ n ≤ 2·105). The second line contains n integers a1, a2, ..., an — the vessels' capacities (1 ≤ ai ≤ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m — the number of queries (1 ≤ m ≤ 2·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≤ pi ≤ n, 1 ≤ xi ≤ 109, 1 ≤ ki ≤ n).
1,800
For each query, print on a single line the number of liters of water in the corresponding vessel.
standard output
PASSED
bd9037a925f55cbc21548df961422ee0
train_002.jsonl
1386493200
There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor.Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: Add xi liters of water to the pi-th vessel; Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels.
256 megabytes
import java.io.*; import java.util.*; public class r21824 { public void solve() { int n = in.nextInt(); long[] a = new long[n + 1]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } a[n] = Long.MAX_VALUE; long[] cur = new long[n + 1]; DSU dsu = new DSU(n + 1); int m = in.nextInt(); while (m-- > 0) { int t = in.nextInt(); if (t == 1) { int p = in.nextInt() - 1, x = in.nextInt(); while (x > 0) { long curAdd = Math.min(a[p] - cur[p], x); cur[p] += curAdd; x -= curAdd; if (cur[p] == a[p]) { dsu.union(p, p + 1); } if (x == 0) { break; } p = dsu.max[dsu.get(p + 1)]; } } else { out.println(cur[in.nextInt() - 1]); } } } class DSU { int[] p, r, max; public DSU(int n) { p = new int[n]; r = new int[n]; max = new int[n]; for (int i =0 ; i < n; i++) { p[i] = i; max[i] = i; } } int get(int v) { if (p[v] == v) { return v; } return p[v] = get(p[v]); } void union(int a, int b) { a = get(a); b = get(b); if (a == b) { return; } if (r[a] == r[b]) { r[a]++; } if (r[a] > r[b]) { p[b] = a; max[a] = Math.max(max[a], max[b]); } else { p[a] = b; max[b] = Math.max(max[a], max[b]); } } } FastScanner in; PrintWriter out; public void run() { try { in = new FastScanner(); out = new PrintWriter(System.out); solve(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastScanner(String name) { try { br = new BufferedReader(new FileReader(name)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } public static void main(String[] args) { new r21824().run(); } }
Java
["2\n5 10\n6\n1 1 4\n2 1\n1 2 5\n1 1 4\n2 1\n2 2", "3\n5 10 8\n6\n1 1 12\n2 2\n1 1 6\n1 3 2\n2 2\n2 3"]
2 seconds
["4\n5\n8", "7\n10\n5"]
null
Java 7
standard input
[ "data structures", "dsu", "implementation", "trees" ]
37e2bb1c7caeeae7f8a7c837a2b390c9
The first line contains integer n — the number of vessels (1 ≤ n ≤ 2·105). The second line contains n integers a1, a2, ..., an — the vessels' capacities (1 ≤ ai ≤ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m — the number of queries (1 ≤ m ≤ 2·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≤ pi ≤ n, 1 ≤ xi ≤ 109, 1 ≤ ki ≤ n).
1,800
For each query, print on a single line the number of liters of water in the corresponding vessel.
standard output
PASSED
522dd0ec33e714710ec65c1d8a57823f
train_002.jsonl
1386493200
There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor.Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: Add xi liters of water to the pi-th vessel; Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels.
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; import java.util.TreeSet; /** * * @author nbheeroo */ public class Vessels { private void solve() { int n, m, queryNum, p, x, k; Integer current; int[] capacities, levels; TreeSet<Integer> vessels = new TreeSet<>(); n = in.nextInt(); capacities = new int[n]; levels = new int[n]; for (int i = 0; i < n; i++) { capacities[i] = in.nextInt(); levels[i] = 0; vessels.add(i); } m = in.nextInt(); for (int i = 0; i < m; i++) { queryNum = in.nextInt(); if (queryNum == 1) { p = in.nextInt() - 1; x = in.nextInt(); current = vessels.ceiling(p); while (true) { if (current == null) break; if (levels[current] + x < capacities[current]) { levels[current] += x; break; } else { x -= (capacities[current] - levels[current]); levels[current] = capacities[current]; vessels.remove(current); } if (x <= 0) break; current = vessels.higher(current); } } else { k = in.nextInt() - 1; out.println(levels[k]); } } } FastScanner in; PrintWriter out; public void run() { try { in = new FastScanner(); out = new PrintWriter(System.out); solve(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastScanner(String name) { try { br = new BufferedReader(new FileReader(name)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } public static void main(String[] args) { new Vessels().run(); } }
Java
["2\n5 10\n6\n1 1 4\n2 1\n1 2 5\n1 1 4\n2 1\n2 2", "3\n5 10 8\n6\n1 1 12\n2 2\n1 1 6\n1 3 2\n2 2\n2 3"]
2 seconds
["4\n5\n8", "7\n10\n5"]
null
Java 7
standard input
[ "data structures", "dsu", "implementation", "trees" ]
37e2bb1c7caeeae7f8a7c837a2b390c9
The first line contains integer n — the number of vessels (1 ≤ n ≤ 2·105). The second line contains n integers a1, a2, ..., an — the vessels' capacities (1 ≤ ai ≤ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m — the number of queries (1 ≤ m ≤ 2·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≤ pi ≤ n, 1 ≤ xi ≤ 109, 1 ≤ ki ≤ n).
1,800
For each query, print on a single line the number of liters of water in the corresponding vessel.
standard output
PASSED
c5ce9e241ee86b31ff2002f0c8ef63a7
train_002.jsonl
1386493200
There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor.Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: Add xi liters of water to the pi-th vessel; Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels.
256 megabytes
import java.io.PrintWriter; import java.util.Scanner; import java.util.TreeSet; /** * * @author nbheeroo */ public class Vessels { public static void main(String[] args) { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); solve(in, out); out.close(); in.close(); } private static void solve(Scanner in, PrintWriter out) { int n, m, queryNum, p, x, k; Integer current; int[] capacities, levels; TreeSet<Integer> vessels = new TreeSet<>(); n = in.nextInt(); capacities = new int[n]; levels = new int[n]; for (int i = 0; i < n; i++) { capacities[i] = in.nextInt(); levels[i] = 0; vessels.add(i); } m = in.nextInt(); for (int i = 0; i < m; i++) { queryNum = in.nextInt(); if (queryNum == 1) { p = in.nextInt() - 1; x = in.nextInt(); current = vessels.ceiling(p); while (true) { if (current == null) break; if (levels[current] + x < capacities[current]) { levels[current] += x; break; } else { x -= (capacities[current] - levels[current]); levels[current] = capacities[current]; vessels.remove(current); } if (x <= 0) break; current = vessels.higher(current); } } else { k = in.nextInt() - 1; out.println(levels[k]); } } } }
Java
["2\n5 10\n6\n1 1 4\n2 1\n1 2 5\n1 1 4\n2 1\n2 2", "3\n5 10 8\n6\n1 1 12\n2 2\n1 1 6\n1 3 2\n2 2\n2 3"]
2 seconds
["4\n5\n8", "7\n10\n5"]
null
Java 7
standard input
[ "data structures", "dsu", "implementation", "trees" ]
37e2bb1c7caeeae7f8a7c837a2b390c9
The first line contains integer n — the number of vessels (1 ≤ n ≤ 2·105). The second line contains n integers a1, a2, ..., an — the vessels' capacities (1 ≤ ai ≤ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m — the number of queries (1 ≤ m ≤ 2·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≤ pi ≤ n, 1 ≤ xi ≤ 109, 1 ≤ ki ≤ n).
1,800
For each query, print on a single line the number of liters of water in the corresponding vessel.
standard output
PASSED
b910dd16ac1120d44a7532613af96a99
train_002.jsonl
1386493200
There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor.Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: Add xi liters of water to the pi-th vessel; Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels.
256 megabytes
import java.util.*; public class D { public static void main(String [] args){ final Scanner s = new Scanner(System.in); final int n = s.nextInt(); final int [] a = new int[n]; for (int i = 0; i < n; ++i){ a[i] = s.nextInt(); } final int [] amount = new int[n]; final SortedSet<Integer> notFull = new TreeSet<Integer>(); for (int i = 0; i < n; ++i){ notFull.add(i); } final int m = s.nextInt(); for (int i = 0; i < m; ++i){ final int t = s.nextInt(); switch (t){ case 1: { final int p = s.nextInt() - 1; int x = s.nextInt(); final Iterator<Integer> iterator = notFull.tailSet(p).iterator(); while (iterator.hasNext()){ final int j = iterator.next(); final int b = amount[j] + x; amount[j] = Math.min(b, a[j]); x = Math.max(b - a[j], 0); if (amount[j] == a[j]){ iterator.remove(); } if (x == 0){ break; } } break; } case 2: { final int k = s.nextInt() - 1; System.out.println(amount[k]); break; } } } s.close(); } }
Java
["2\n5 10\n6\n1 1 4\n2 1\n1 2 5\n1 1 4\n2 1\n2 2", "3\n5 10 8\n6\n1 1 12\n2 2\n1 1 6\n1 3 2\n2 2\n2 3"]
2 seconds
["4\n5\n8", "7\n10\n5"]
null
Java 7
standard input
[ "data structures", "dsu", "implementation", "trees" ]
37e2bb1c7caeeae7f8a7c837a2b390c9
The first line contains integer n — the number of vessels (1 ≤ n ≤ 2·105). The second line contains n integers a1, a2, ..., an — the vessels' capacities (1 ≤ ai ≤ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m — the number of queries (1 ≤ m ≤ 2·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≤ pi ≤ n, 1 ≤ xi ≤ 109, 1 ≤ ki ≤ n).
1,800
For each query, print on a single line the number of liters of water in the corresponding vessel.
standard output
PASSED
e6435a53e0e35207dcf4c4ec5a604019
train_002.jsonl
1386493200
There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor.Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: Add xi liters of water to the pi-th vessel; Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class Main { /** * @param args */ static long ar[] = new long[200006]; static long rem[] = new long[200006]; static int next[] = new int[200006]; static int getNext( int x ){ if( next[x] == x ) return x; return next[x] = getNext( next[x] ); } public static void main(String[] args) { BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); try{ StringTokenizer token = new StringTokenizer(read.readLine()); int N = Integer.parseInt(token.nextToken()); token = new StringTokenizer( read.readLine() ); for( int i = 1; i <= N; i++ ) ar[i] = Long.parseLong(token.nextToken()); for( int i = 1; i <= N+3; i++ ) next[i] = i; token = new StringTokenizer( read.readLine() ); int M = Integer.parseInt(token.nextToken()); Arrays.fill(rem, 0); for( int i = 1; i <= M; i++ ){ token = new StringTokenizer(read.readLine()); int op = Integer.parseInt( token.nextToken() ); if( op == 1 ){ int p = Integer.parseInt(token.nextToken()); long x = Long.parseLong(token.nextToken()); while( x > 0 && p <= N ){ p = getNext( p ); if( p > N ) break; if( ar[p] == 0 ){ next[p] = getNext( next[p]+1 ); p = next[p]; } else{ if( x <= ar[p] ){ ar[p] -= x; rem[p] += x; //if( p == 2 ) System.out.println("yess " + acp); x = 0; } else{ rem[p] += ar[p]; x -= ar[p]; ar[p] = 0; next[p] = getNext(next[p]+1); p = next[p]; } } } } else{ int k = Integer.parseInt(token.nextToken()); System.out.println( rem[k] ); } } } catch( Exception e ){ } } } /* * 10 71 59 88 55 18 98 38 73 53 58 20 1 5 93 1 7 69 2 3 1 1 20 2 10 1 6 74 1 7 100 1 9 14 2 3 2 4 2 7 1 3 31 2 4 1 6 64 2 2 2 2 1 3 54 2 9 2 1 1 6 86 0 0 0 0 0 0 0 0 0 0 */
Java
["2\n5 10\n6\n1 1 4\n2 1\n1 2 5\n1 1 4\n2 1\n2 2", "3\n5 10 8\n6\n1 1 12\n2 2\n1 1 6\n1 3 2\n2 2\n2 3"]
2 seconds
["4\n5\n8", "7\n10\n5"]
null
Java 7
standard input
[ "data structures", "dsu", "implementation", "trees" ]
37e2bb1c7caeeae7f8a7c837a2b390c9
The first line contains integer n — the number of vessels (1 ≤ n ≤ 2·105). The second line contains n integers a1, a2, ..., an — the vessels' capacities (1 ≤ ai ≤ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m — the number of queries (1 ≤ m ≤ 2·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≤ pi ≤ n, 1 ≤ xi ≤ 109, 1 ≤ ki ≤ n).
1,800
For each query, print on a single line the number of liters of water in the corresponding vessel.
standard output
PASSED
11daded65648b48a5c04438e1e8eb28e
train_002.jsonl
1386493200
There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor.Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: Add xi liters of water to the pi-th vessel; Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class Main { /** * @param args */ static long ar[] = new long[200006]; static long rem[] = new long[200006]; static int next[] = new int[200006]; static int getNext( int x ){ if( next[x] == x ) return x; return next[x] = getNext( next[x] ); } public static void main(String[] args) { BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); try{ StringTokenizer token = new StringTokenizer(read.readLine()); int N = Integer.parseInt(token.nextToken()); token = new StringTokenizer( read.readLine() ); for( int i = 1; i <= N; i++ ) ar[i] = Long.parseLong(token.nextToken()); for( int i = 1; i <= N+3; i++ ) next[i] = i; token = new StringTokenizer( read.readLine() ); int M = Integer.parseInt(token.nextToken()); Arrays.fill(rem, 0); for( int i = 1; i <= M; i++ ){ token = new StringTokenizer(read.readLine()); int op = Integer.parseInt( token.nextToken() ); if( op == 1 ){ int p = Integer.parseInt(token.nextToken()); long x = Long.parseLong(token.nextToken()); while( x > 0 && p <= N ){ p = getNext( p ); if( p > N ) break; if( ar[p] == 0 ){ next[p] = getNext( p+1 ); p = next[p]; } else{ if( x <= ar[p] ){ ar[p] -= x; rem[p] += x; //if( p == 2 ) System.out.println("yess " + acp); x = 0; } else{ rem[p] += ar[p]; x -= ar[p]; ar[p] = 0; next[p] = getNext(p+1); p = next[p]; } } } } else{ int k = Integer.parseInt(token.nextToken()); System.out.println( rem[k] ); } } } catch( Exception e ){ } } } /* * 10 71 59 88 55 18 98 38 73 53 58 20 1 5 93 1 7 69 2 3 1 1 20 2 10 1 6 74 1 7 100 1 9 14 2 3 2 4 2 7 1 3 31 2 4 1 6 64 2 2 2 2 1 3 54 2 9 2 1 1 6 86 0 0 0 0 0 0 0 0 0 0 */
Java
["2\n5 10\n6\n1 1 4\n2 1\n1 2 5\n1 1 4\n2 1\n2 2", "3\n5 10 8\n6\n1 1 12\n2 2\n1 1 6\n1 3 2\n2 2\n2 3"]
2 seconds
["4\n5\n8", "7\n10\n5"]
null
Java 7
standard input
[ "data structures", "dsu", "implementation", "trees" ]
37e2bb1c7caeeae7f8a7c837a2b390c9
The first line contains integer n — the number of vessels (1 ≤ n ≤ 2·105). The second line contains n integers a1, a2, ..., an — the vessels' capacities (1 ≤ ai ≤ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m — the number of queries (1 ≤ m ≤ 2·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≤ pi ≤ n, 1 ≤ xi ≤ 109, 1 ≤ ki ≤ n).
1,800
For each query, print on a single line the number of liters of water in the corresponding vessel.
standard output
PASSED
26739dc7e51bc84c582cdcf4867fa3b0
train_002.jsonl
1386493200
There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor.Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: Add xi liters of water to the pi-th vessel; Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels.
256 megabytes
import com.sun.org.apache.regexp.internal.recompile; import sun.print.resources.serviceui; import javax.management.remote.rmi._RMIConnection_Stub; import java.awt.*; import java.io.*; import java.util.*; public class D { private static int [] tree; public static void main(String [] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter(new OutputStreamWriter(System.out)); int n = Integer.parseInt(reader.readLine()); long [] capacities = new long[n]; StringTokenizer tokenizer = new StringTokenizer(reader.readLine()); for(int i = 0 ; i < n ; i++) capacities[i] = Integer.parseInt(tokenizer.nextToken()); long [] rem = capacities.clone(); long [] sum = new long[n+1]; for(int i = 1 ; i <= n ; i++) sum[i] = sum[i-1] + capacities[i-1]; tree = new int[n]; for(int i = 0 ; i < n ; i++) tree[i] = i; int queriesNumber = Integer.parseInt(reader.readLine()); while(queriesNumber-- > 0) { tokenizer = new StringTokenizer(reader.readLine()); tokenizer.nextToken(); int idx = Integer.parseInt(tokenizer.nextToken()) - 1; if(tokenizer.hasMoreTokens()) { long lit = Integer.parseInt(tokenizer.nextToken()); update(set(idx), lit, rem); } else { writer.println(capacities[idx] - rem[idx]); } } writer.flush(); writer.close(); } private static int set(int idx) { return tree[idx] == idx ? idx : (tree[idx] = set(tree[idx])); } private static void update(int idx, long lit, long [] rem) { rem[idx] -= lit; if(rem[idx] < 0) { if(idx+1 < rem.length) { tree[set(idx)] = set(idx+1); update(set(idx), -rem[idx], rem); } rem[idx] = 0; } } }
Java
["2\n5 10\n6\n1 1 4\n2 1\n1 2 5\n1 1 4\n2 1\n2 2", "3\n5 10 8\n6\n1 1 12\n2 2\n1 1 6\n1 3 2\n2 2\n2 3"]
2 seconds
["4\n5\n8", "7\n10\n5"]
null
Java 7
standard input
[ "data structures", "dsu", "implementation", "trees" ]
37e2bb1c7caeeae7f8a7c837a2b390c9
The first line contains integer n — the number of vessels (1 ≤ n ≤ 2·105). The second line contains n integers a1, a2, ..., an — the vessels' capacities (1 ≤ ai ≤ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m — the number of queries (1 ≤ m ≤ 2·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≤ pi ≤ n, 1 ≤ xi ≤ 109, 1 ≤ ki ≤ n).
1,800
For each query, print on a single line the number of liters of water in the corresponding vessel.
standard output
PASSED
884d1b4f79f5a59e18abb8ed29a456bf
train_002.jsonl
1386493200
There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor.Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: Add xi liters of water to the pi-th vessel; Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels.
256 megabytes
import java.io.*; import java.util.*; public class D { private static TreeSet<Integer> set; public static void main(String [] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter(new OutputStreamWriter(System.out)); int n = Integer.parseInt(reader.readLine()); long [] capacities = new long[n]; StringTokenizer tokenizer = new StringTokenizer(reader.readLine()); for(int i = 0 ; i < n ; i++) capacities[i] = Integer.parseInt(tokenizer.nextToken()); long [] rem = capacities.clone(); set = new TreeSet<Integer>(); for(int i = 0 ; i < n ; i++) set.add(i); int queriesNumber = Integer.parseInt(reader.readLine()); while(queriesNumber-- > 0) { tokenizer = new StringTokenizer(reader.readLine()); tokenizer.nextToken(); int idx = Integer.parseInt(tokenizer.nextToken()) - 1; if(tokenizer.hasMoreTokens()) { long lit = Integer.parseInt(tokenizer.nextToken()); update(idx, lit, rem); } else { writer.println(capacities[idx] - rem[idx]); } } writer.flush(); writer.close(); } private static void update(int idx, long lit, long [] rem) { rem[idx] -= lit; if(rem[idx] < 0) { int next = set.higher(idx) == null ? -1 : set.higher(idx); set.remove(idx); if(next != -1) update(next, -rem[idx], rem); rem[idx] = 0; } } }
Java
["2\n5 10\n6\n1 1 4\n2 1\n1 2 5\n1 1 4\n2 1\n2 2", "3\n5 10 8\n6\n1 1 12\n2 2\n1 1 6\n1 3 2\n2 2\n2 3"]
2 seconds
["4\n5\n8", "7\n10\n5"]
null
Java 7
standard input
[ "data structures", "dsu", "implementation", "trees" ]
37e2bb1c7caeeae7f8a7c837a2b390c9
The first line contains integer n — the number of vessels (1 ≤ n ≤ 2·105). The second line contains n integers a1, a2, ..., an — the vessels' capacities (1 ≤ ai ≤ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m — the number of queries (1 ≤ m ≤ 2·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≤ pi ≤ n, 1 ≤ xi ≤ 109, 1 ≤ ki ≤ n).
1,800
For each query, print on a single line the number of liters of water in the corresponding vessel.
standard output
PASSED
d12f8d7773909b41d6240de8b7c6d2c6
train_002.jsonl
1386493200
There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor.Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: Add xi liters of water to the pi-th vessel; Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels.
256 megabytes
import java.util.*; import java.io.*; import java.math.BigDecimal; public class Task { public static void main(String[] args) throws Exception { new Task().solve(); } void solve() throws Exception { Reader in = new Reader("1.in"); PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(System.out) ) ); TreeSet<Integer> set = new TreeSet<Integer>(); int n = in.nextInt(); int[] a = new int[n]; int[] v = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); v[i] = a[i]; set.add(i); } int m = in.nextInt(); for (int i = 0; i < m; i++) { int c = in.nextInt(); if (c == 1) { int k = in.nextInt()-1; int w = in.nextInt(); while (w > 0) { if (w >= a[k]) { if (set.higher(k) != null) { int next = set.higher(k); set.remove(k); w -= a[k]; a[k] = 0; k = next; } else { w = 0; a[k] = 0; } } else { a[k] -= w; w = 0; } } } else { int k = in.nextInt()-1; out.println(v[k]-a[k]); } } out.flush(); out.close(); } class Pair implements Comparable<Pair>{ int i; int a; Pair(int i, int a) { this.i = i; this.a = a; } @Override public int compareTo(Pair pair) { return a > pair.a ? -1: a < pair.a ? 1: 0; } } class DSU { int size; int[] sz; int[] set; DSU(int size) { this.size = size; set = new int[size+1]; sz = new int[size+1]; for(int i = 0; i < size; i++) { set[i] = i; sz[i] = 1; } } int get(int x) { if (set[x] == x) return x; else return set[x] = get(set[x]); } void union(int x, int y) { x = get(x); y = get(y); if (sz[x] < sz[y]) { set[x] = y; sz[y] += sz[x]; } else { set[y] = x; sz[x] += sz[y]; } } boolean incomp(int x, int y) { return get(x) == get(y); } int getSize(int x) { x = get(x); return sz[x]; } } class Reader { BufferedReader br; StringTokenizer token = null; Reader(String file) throws Exception { br = new BufferedReader( new InputStreamReader(System.in) ); } String next() throws Exception { while (token == null || !token.hasMoreElements()) { token = new StringTokenizer(br.readLine()); } return token.nextToken(); } int nextInt() throws Exception { return Integer.parseInt(next()); } long nextLong() throws Exception { return Long.parseLong(next()); } double nextDouble() throws Exception { return Double.parseDouble(next()); } } }
Java
["2\n5 10\n6\n1 1 4\n2 1\n1 2 5\n1 1 4\n2 1\n2 2", "3\n5 10 8\n6\n1 1 12\n2 2\n1 1 6\n1 3 2\n2 2\n2 3"]
2 seconds
["4\n5\n8", "7\n10\n5"]
null
Java 7
standard input
[ "data structures", "dsu", "implementation", "trees" ]
37e2bb1c7caeeae7f8a7c837a2b390c9
The first line contains integer n — the number of vessels (1 ≤ n ≤ 2·105). The second line contains n integers a1, a2, ..., an — the vessels' capacities (1 ≤ ai ≤ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m — the number of queries (1 ≤ m ≤ 2·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≤ pi ≤ n, 1 ≤ xi ≤ 109, 1 ≤ ki ≤ n).
1,800
For each query, print on a single line the number of liters of water in the corresponding vessel.
standard output
PASSED
ab1b6d5de865ae310fd03a5ed8b6be5a
train_002.jsonl
1386493200
There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor.Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: Add xi liters of water to the pi-th vessel; Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels.
256 megabytes
import static java.util.Arrays.deepToString; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.StringTokenizer; import java.util.TreeSet; public class Main { static void solve() throws IOException { int n = nextInt(); int[] a = new int[n + 1]; int[] b = new int[n + 1]; TreeSet<Integer> set = new TreeSet<>(); for (int i = 0; i < n; i++) { a[i] = nextInt(); set.add(i); } int m = nextInt(); while (m != 0) { m--; int t = nextInt(); if (t == 1) { int p = nextInt() - 1; int x = nextInt(); while (x > 0) { if (b[p] + x <= a[p]) { b[p] += x; x = 0; } else { x = x - a[p] + b[p]; b[p] = a[p]; set.remove(p); Integer tmp = set.higher(p); if (tmp == null) { x = 0; } else { p = tmp; } } } } else { int k = nextInt() - 1; System.out.println(b[k]); } } } public static void main(String[] args) throws Exception { reader = new BufferedReader(new InputStreamReader(System.in)); writer = new PrintWriter(System.out); // reader = new BufferedReader(new FileReader("input.txt")); // writer = new PrintWriter("output.txt"); setTime(); solve(); printTime(); printMemory(); writer.close(); } static BufferedReader reader; static PrintWriter writer; static StringTokenizer tok = new StringTokenizer(""); static long systemTime; static void debug(Object... o) { System.err.println(deepToString(o)); } static void setTime() { systemTime = System.currentTimeMillis(); } static void printTime() { System.err.println("Time consumed: " + (System.currentTimeMillis() - systemTime)); } static void printMemory() { System.err.println("Memory consumed: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime() .freeMemory()) / 1000 + "kb"); } static String next() { while (!tok.hasMoreTokens()) { String w = null; try { w = reader.readLine(); } catch (Exception e) { e.printStackTrace(); } if (w == null) return null; tok = new StringTokenizer(w); } return tok.nextToken(); } static int nextInt() { return Integer.parseInt(next()); } static long nextLong() { return Long.parseLong(next()); } static double nextDouble() { return Double.parseDouble(next()); } static BigInteger nextBigInteger() { return new BigInteger(next()); } }
Java
["2\n5 10\n6\n1 1 4\n2 1\n1 2 5\n1 1 4\n2 1\n2 2", "3\n5 10 8\n6\n1 1 12\n2 2\n1 1 6\n1 3 2\n2 2\n2 3"]
2 seconds
["4\n5\n8", "7\n10\n5"]
null
Java 7
standard input
[ "data structures", "dsu", "implementation", "trees" ]
37e2bb1c7caeeae7f8a7c837a2b390c9
The first line contains integer n — the number of vessels (1 ≤ n ≤ 2·105). The second line contains n integers a1, a2, ..., an — the vessels' capacities (1 ≤ ai ≤ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m — the number of queries (1 ≤ m ≤ 2·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≤ pi ≤ n, 1 ≤ xi ≤ 109, 1 ≤ ki ≤ n).
1,800
For each query, print on a single line the number of liters of water in the corresponding vessel.
standard output
PASSED
a8448760798afb10ce37c6a061137392
train_002.jsonl
1386493200
There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor.Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: Add xi liters of water to the pi-th vessel; Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels.
256 megabytes
import static java.util.Arrays.deepToString; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.StringTokenizer; import java.util.TreeSet; public class Main { static void solve() throws IOException { int n = nextInt(); int[] a = new int[n + 1]; int[] b = new int[n + 1]; int[] next = new int[n + 1]; TreeSet<Integer> set = new TreeSet<>(); for (int i = 0; i < n; i++) { a[i] = nextInt(); next[i] = i + 1; set.add(i); } int m = nextInt(); while (m != 0) { m--; int t = nextInt(); if (t == 1) { int p = nextInt() - 1; int x = nextInt(); while (x > 0) { if (b[p] + x <= a[p]) { b[p] += x; x = 0; } else { x = x - a[p] + b[p]; b[p] = a[p]; set.remove(p); Integer tmp = set.higher(p); if (tmp == null) { x = 0; } else { p = tmp; } } } } else { int k = nextInt() - 1; System.out.println(b[k]); } } } public static void main(String[] args) throws Exception { reader = new BufferedReader(new InputStreamReader(System.in)); writer = new PrintWriter(System.out); // reader = new BufferedReader(new FileReader("input.txt")); // writer = new PrintWriter("output.txt"); setTime(); solve(); printTime(); printMemory(); writer.close(); } static BufferedReader reader; static PrintWriter writer; static StringTokenizer tok = new StringTokenizer(""); static long systemTime; static void debug(Object... o) { System.err.println(deepToString(o)); } static void setTime() { systemTime = System.currentTimeMillis(); } static void printTime() { System.err.println("Time consumed: " + (System.currentTimeMillis() - systemTime)); } static void printMemory() { System.err.println("Memory consumed: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime() .freeMemory()) / 1000 + "kb"); } static String next() { while (!tok.hasMoreTokens()) { String w = null; try { w = reader.readLine(); } catch (Exception e) { e.printStackTrace(); } if (w == null) return null; tok = new StringTokenizer(w); } return tok.nextToken(); } static int nextInt() { return Integer.parseInt(next()); } static long nextLong() { return Long.parseLong(next()); } static double nextDouble() { return Double.parseDouble(next()); } static BigInteger nextBigInteger() { return new BigInteger(next()); } }
Java
["2\n5 10\n6\n1 1 4\n2 1\n1 2 5\n1 1 4\n2 1\n2 2", "3\n5 10 8\n6\n1 1 12\n2 2\n1 1 6\n1 3 2\n2 2\n2 3"]
2 seconds
["4\n5\n8", "7\n10\n5"]
null
Java 7
standard input
[ "data structures", "dsu", "implementation", "trees" ]
37e2bb1c7caeeae7f8a7c837a2b390c9
The first line contains integer n — the number of vessels (1 ≤ n ≤ 2·105). The second line contains n integers a1, a2, ..., an — the vessels' capacities (1 ≤ ai ≤ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m — the number of queries (1 ≤ m ≤ 2·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≤ pi ≤ n, 1 ≤ xi ≤ 109, 1 ≤ ki ≤ n).
1,800
For each query, print on a single line the number of liters of water in the corresponding vessel.
standard output