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
75b3ae324516ed3e0c81466d1116c822
train_004.jsonl
1427387400
After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on β€” you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.The potato pie is located in the n-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class VitaliyAndPie { public static void main(String[] args) { Scanner input = new Scanner (System.in); int n = input.nextInt(); String s = input.next(); int [] array = new int [28]; int count = 0; for (int i = 0 ; i < s.length() ; i++) { //System.out.println(i); if(Character.isUpperCase(s.charAt(i))) { String temp = (s.charAt(i) + "").toLowerCase(); if(array[temp.charAt(0)-'a'+1] > 0) array[temp.charAt(0)-'a'+1]--; else count++; } else array[s.charAt(i)-'a'+1]++; } System.out.println(count); } }
Java
["3\naAbB", "4\naBaCaB", "5\nxYyXzZaZ"]
2 seconds
["0", "3", "2"]
null
Java 8
standard input
[ "hashing", "greedy", "strings" ]
80fdb95372c1e8d558b8c8f31c9d0479
The first line of the input contains a positive integer n (2 ≀ n ≀ 105)Β β€”Β the number of rooms in the house. The second line of the input contains string s of length 2Β·n - 2. Let's number the elements of the string from left to right, starting from one. The odd positions in the given string s contain lowercase Latin lettersΒ β€”Β the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter β€” the type of the key that lies in room number (i + 1) / 2. The even positions in the given string contain uppercase Latin letters β€” the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter β€” the type of the door that leads from room i / 2 to room i / 2 + 1.
1,100
Print the only integer β€” the minimum number of keys that Vitaly needs to buy to surely get from room one to room n.
standard output
PASSED
5e99e4b9bcc7f308344f676168e47f52
train_004.jsonl
1427387400
After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on β€” you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.The potato pie is located in the n-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number.
256 megabytes
import java.util.*; import java.math.*; public class qwe { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n=in.nextInt(),ans=0; String s=in.next(); int v[]=new int[26]; for(int i=0;i<v.length;i++) { v[i]=0; } for(int i=s.length()-1;i>=0;i--) { //System.out.println(s.length()-1); if(i%2==1) { v[(int)(s.charAt(i)-'A')]++; }else { v[(int)(s.charAt(i)-'a')]=Math.max(v[(int)(s.charAt(i)-'a')]-1,0); } } for(int i=0;i<v.length;i++) { ans+=v[i]; } System.out.println(ans); } }
Java
["3\naAbB", "4\naBaCaB", "5\nxYyXzZaZ"]
2 seconds
["0", "3", "2"]
null
Java 8
standard input
[ "hashing", "greedy", "strings" ]
80fdb95372c1e8d558b8c8f31c9d0479
The first line of the input contains a positive integer n (2 ≀ n ≀ 105)Β β€”Β the number of rooms in the house. The second line of the input contains string s of length 2Β·n - 2. Let's number the elements of the string from left to right, starting from one. The odd positions in the given string s contain lowercase Latin lettersΒ β€”Β the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter β€” the type of the key that lies in room number (i + 1) / 2. The even positions in the given string contain uppercase Latin letters β€” the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter β€” the type of the door that leads from room i / 2 to room i / 2 + 1.
1,100
Print the only integer β€” the minimum number of keys that Vitaly needs to buy to surely get from room one to room n.
standard output
PASSED
adb8e3854476919bcdf5b5179c767264
train_004.jsonl
1427387400
After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on β€” you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.The potato pie is located in the n-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number.
256 megabytes
import java.util.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class VitaliyAndPie { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { FastReader sc = new FastReader(); int n = sc.nextInt(); String s = sc.next(); int[] a = new int[27]; int count = 0; int x = 0; for(int i=0; i<s.length(); i++) { if(i%2==0) { x = s.charAt(i) - 'a'; a[x]++; } else { x = s.charAt(i) - 'A'; if(a[x]==0) { count++; } else { a[x]--; } } } System.out.println(count); } }
Java
["3\naAbB", "4\naBaCaB", "5\nxYyXzZaZ"]
2 seconds
["0", "3", "2"]
null
Java 8
standard input
[ "hashing", "greedy", "strings" ]
80fdb95372c1e8d558b8c8f31c9d0479
The first line of the input contains a positive integer n (2 ≀ n ≀ 105)Β β€”Β the number of rooms in the house. The second line of the input contains string s of length 2Β·n - 2. Let's number the elements of the string from left to right, starting from one. The odd positions in the given string s contain lowercase Latin lettersΒ β€”Β the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter β€” the type of the key that lies in room number (i + 1) / 2. The even positions in the given string contain uppercase Latin letters β€” the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter β€” the type of the door that leads from room i / 2 to room i / 2 + 1.
1,100
Print the only integer β€” the minimum number of keys that Vitaly needs to buy to surely get from room one to room n.
standard output
PASSED
886a33783f9cb22ad9e9dc83fc67f9cf
train_004.jsonl
1427387400
After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on β€” you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.The potato pie is located in the n-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); String rooms = br.readLine(); HashMap<Character, Integer> keys = new HashMap<>(); int cnt = 0; for(int i=1; i<rooms.length(); i+=2) { if((int) (rooms.charAt(i) - 'A') != (int) (rooms.charAt(i-1) - 'a')) { if(keys.get(rooms.charAt(i-1)) == null) keys.put(rooms.charAt(i-1), 1); else keys.put(rooms.charAt(i-1), keys.get(rooms.charAt(i-1)) + 1); char the_key = (char) (rooms.charAt(i) - 'A' + 'a'); if(keys.get(the_key) == null || keys.get(the_key) == 0) cnt++; else keys.put(the_key, keys.get(the_key) - 1); } } System.out.println(cnt); } }
Java
["3\naAbB", "4\naBaCaB", "5\nxYyXzZaZ"]
2 seconds
["0", "3", "2"]
null
Java 8
standard input
[ "hashing", "greedy", "strings" ]
80fdb95372c1e8d558b8c8f31c9d0479
The first line of the input contains a positive integer n (2 ≀ n ≀ 105)Β β€”Β the number of rooms in the house. The second line of the input contains string s of length 2Β·n - 2. Let's number the elements of the string from left to right, starting from one. The odd positions in the given string s contain lowercase Latin lettersΒ β€”Β the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter β€” the type of the key that lies in room number (i + 1) / 2. The even positions in the given string contain uppercase Latin letters β€” the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter β€” the type of the door that leads from room i / 2 to room i / 2 + 1.
1,100
Print the only integer β€” the minimum number of keys that Vitaly needs to buy to surely get from room one to room n.
standard output
PASSED
57c9660050c8f1b24e2677acdc7e4e53
train_004.jsonl
1427387400
After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on β€” you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.The potato pie is located in the n-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number.
256 megabytes
import java.util.ArrayList; import java.util.Scanner; public class Vitaliy_and_Pie { public static void main(String[] args) { // TODO Auto-generated method stub Scanner in = new Scanner(System.in); int n = in.nextInt(); in.nextLine(); String s = in.nextLine(); int a[] = new int [26]; int ans = 0; for (int i=0;i<s.length();i+=2) { int key = (s.charAt(i) - 'a'); //System.out.println(key); int door = (s.charAt(i+1) - 'A'); // System.out.println(door); a[key]++; // System.out.println(a[key]); // System.out.println(a[door]); if (a[door] == 0) { ans++; } else { a[door] --; } } System.out.println(ans); } }
Java
["3\naAbB", "4\naBaCaB", "5\nxYyXzZaZ"]
2 seconds
["0", "3", "2"]
null
Java 8
standard input
[ "hashing", "greedy", "strings" ]
80fdb95372c1e8d558b8c8f31c9d0479
The first line of the input contains a positive integer n (2 ≀ n ≀ 105)Β β€”Β the number of rooms in the house. The second line of the input contains string s of length 2Β·n - 2. Let's number the elements of the string from left to right, starting from one. The odd positions in the given string s contain lowercase Latin lettersΒ β€”Β the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter β€” the type of the key that lies in room number (i + 1) / 2. The even positions in the given string contain uppercase Latin letters β€” the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter β€” the type of the door that leads from room i / 2 to room i / 2 + 1.
1,100
Print the only integer β€” the minimum number of keys that Vitaly needs to buy to surely get from room one to room n.
standard output
PASSED
80b225945a75ccdbca016114c02f5ca6
train_004.jsonl
1427387400
After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on β€” you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.The potato pie is located in the n-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); try (PrintWriter out = new PrintWriter(outputStream)) { TaskA solver = new TaskA(); solver.solve(in, out); } } } 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()); } } class TaskA { void solve(InputReader in,PrintWriter out){ int n=in.nextInt(); String s=in.nextLine(); s=s.toLowerCase(); int keys[]=new int[27]; long count=0; for(int i=0;i<2*n-2;i++){ if(i%2==0){ keys[s.charAt(i)-96]++; } else{ if(keys[s.charAt(i)-96]!=0){ keys[s.charAt(i)-96]--; } else count++; } } out.println(count); } }
Java
["3\naAbB", "4\naBaCaB", "5\nxYyXzZaZ"]
2 seconds
["0", "3", "2"]
null
Java 8
standard input
[ "hashing", "greedy", "strings" ]
80fdb95372c1e8d558b8c8f31c9d0479
The first line of the input contains a positive integer n (2 ≀ n ≀ 105)Β β€”Β the number of rooms in the house. The second line of the input contains string s of length 2Β·n - 2. Let's number the elements of the string from left to right, starting from one. The odd positions in the given string s contain lowercase Latin lettersΒ β€”Β the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter β€” the type of the key that lies in room number (i + 1) / 2. The even positions in the given string contain uppercase Latin letters β€” the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter β€” the type of the door that leads from room i / 2 to room i / 2 + 1.
1,100
Print the only integer β€” the minimum number of keys that Vitaly needs to buy to surely get from room one to room n.
standard output
PASSED
796b583cc591993a2e4a4f93964f1420
train_004.jsonl
1427387400
After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on β€” you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.The potato pie is located in the n-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; /** * Idea: store obtained keys in a MultiSet so we can decide whether we must buy one * ot there is a key available * * */ public class VitaliyAndPie { public static void main(String[] args) { Scanner scanner = new Scanner(); int n = scanner.nextInt(); String s = scanner.next(); MultiSet<Integer> keySet = new MultiSet<>(); int keyCount = 0; for(int i=1; i<s.length(); i += 2) { int k = s.charAt(i-1); int d = s.charAt(i); keySet.add(k); if(keySet.contains(d+32)) keySet.remove(d+32); else { keyCount++; } } System.out.print(keyCount); } /**************** UTILITY FUNCTIONS ********************/ private static class Scanner { private BufferedReader br; private StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { if(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; } } private static class KMP { private String pattern; private String text; private int[] lps; private int prev; KMP(String pattern, String text) { this.pattern = pattern; this.text = text; this.lps = new int[pattern.length()]; this.prev = 0; int i=0; int j=i+1; while(j < lps.length) { if(pattern.charAt(i) == pattern.charAt(j)) { lps[j] = lps[j-1] + 1; i++; j++; } else { i = 0; j++; } } } int find() { int i = prev; while(i < text.length()-(pattern.length()-1)) { int j = 0; while (i < text.length() && j < pattern.length()) { if (text.charAt(i) == pattern.charAt(j)) { i++; j++; } else { if(j > 0) j = lps[j - 1]; else break; } } if(j == pattern.length()) return i - j; i++; } return -1; } int findNext() { int ind = find(); if(ind != -1) { prev = ind + pattern.length() - lps[pattern.length()-1]; return ind; } else { prev = text.length(); return -1; } } } private static class PrimeFactor { private int SPF[]; private int N; private Set<Integer> marked; PrimeFactor(int n) { this.SPF = new int[n+1]; this.N = n; this.marked = new HashSet<>(); for(int i=2; i<=Math.sqrt(n); i++) { int x=i*i; while(x <= n) { if(!marked.contains(x)) { SPF[x] = i; marked.add(x); } x += i; } } } List<Integer> getPrimeFactors(int num) { List<Integer> factors = new ArrayList<>(); while(SPF[num] > 0) { factors.add(SPF[num]); num /= SPF[num]; } if(num > 1 && SPF[num] == 0) factors.add(num); return factors; } List<Integer> getPrimes() { List<Integer> factors = new ArrayList<>(); for(int i=2; i<=N; i++) { if(SPF[i] == 0) factors.add(i); } return factors; } Set<Integer> getPrimeSet() { Set<Integer> primeSet = new HashSet<>(); for(int i=2; i<=N; i++) { if(SPF[i] == 0) primeSet.add(i); } return primeSet; } } private static class MultiSet<T> { private Map<T, Integer> elementsToCount; private int size; MultiSet(int cap) { this.elementsToCount = new HashMap<>(cap); this.size = 0; } MultiSet() { this(16); } int size() {return size; } boolean add(T element) { return add(element, 1); } boolean add(T element, int count) { Integer ret = elementsToCount.get(element); if(ret == null) elementsToCount.put(element, count); else elementsToCount.put(element, ret+count); size += count; return true; } boolean contains(T element) { return elementsToCount.containsKey(element); } int count(T element) { Integer ret = elementsToCount.get(element); if(ret == null) return 0; else return ret; } boolean remove(T element) { return remove(element, 1); } boolean remove(T element, int count) { Integer ret = elementsToCount.get(element); if(ret == null ||ret-count < 0) return false; else { if (ret-count == 0) elementsToCount.remove(element); else elementsToCount.put(element, ret - count); size -= count; return true; } } boolean removeAll(T element) { Integer ret = elementsToCount.remove(element); if(Objects.nonNull(ret)) { size -= ret; return true; } return false; } Iterator<T> iterator() { return elementsToCount.keySet().iterator(); } } }
Java
["3\naAbB", "4\naBaCaB", "5\nxYyXzZaZ"]
2 seconds
["0", "3", "2"]
null
Java 8
standard input
[ "hashing", "greedy", "strings" ]
80fdb95372c1e8d558b8c8f31c9d0479
The first line of the input contains a positive integer n (2 ≀ n ≀ 105)Β β€”Β the number of rooms in the house. The second line of the input contains string s of length 2Β·n - 2. Let's number the elements of the string from left to right, starting from one. The odd positions in the given string s contain lowercase Latin lettersΒ β€”Β the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter β€” the type of the key that lies in room number (i + 1) / 2. The even positions in the given string contain uppercase Latin letters β€” the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter β€” the type of the door that leads from room i / 2 to room i / 2 + 1.
1,100
Print the only integer β€” the minimum number of keys that Vitaly needs to buy to surely get from room one to room n.
standard output
PASSED
a79d988997afca9937decde3d1dda68c
train_004.jsonl
1427387400
After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on β€” you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.The potato pie is located in the n-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number.
256 megabytes
//package p525A; import java.util.Scanner; import java.util.Vector; public class VitaliyAndPie { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int n; //input n = sc.nextInt(); Vector<Character> key_list = new Vector<>(); Door[] door_list = new Door[26]; // the number of upper class alphabets for(int i=0; i<door_list.length; i++) door_list[i] = new Door(); String s = sc.next(); for(int i=0; i<s.length(); i++) { char c = s.charAt(i); if(Character.isUpperCase(c)) door_list[c-65].idx_list.add(i/2); else key_list.add(c); } int cnt = 0; for(int i=0, idx; i<key_list.size(); i++) { Door entry = door_list[key_list.get(i)-97]; while(!entry.idx_list.isEmpty()) { idx = entry.idx_list.remove(0); if(idx >= i) { if(entry.idx_list.isEmpty()) cnt--; break; } } if(entry.idx_list.isEmpty()) cnt++; } System.out.println(cnt); } } class Door { Vector<Integer> idx_list = new Vector<>(); }
Java
["3\naAbB", "4\naBaCaB", "5\nxYyXzZaZ"]
2 seconds
["0", "3", "2"]
null
Java 8
standard input
[ "hashing", "greedy", "strings" ]
80fdb95372c1e8d558b8c8f31c9d0479
The first line of the input contains a positive integer n (2 ≀ n ≀ 105)Β β€”Β the number of rooms in the house. The second line of the input contains string s of length 2Β·n - 2. Let's number the elements of the string from left to right, starting from one. The odd positions in the given string s contain lowercase Latin lettersΒ β€”Β the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter β€” the type of the key that lies in room number (i + 1) / 2. The even positions in the given string contain uppercase Latin letters β€” the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter β€” the type of the door that leads from room i / 2 to room i / 2 + 1.
1,100
Print the only integer β€” the minimum number of keys that Vitaly needs to buy to surely get from room one to room n.
standard output
PASSED
8ed98ca65150943d53bc594c908fc8fd
train_004.jsonl
1427387400
After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on β€” you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.The potato pie is located in the n-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number.
256 megabytes
import java.util.Scanner; /** * Created by mmaikovych on 27.03.2015. */ public class CF525A { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt() - 1; scanner.nextLine(); String s = scanner.nextLine(); int found[] = new int[26]; int bought[] = new int[26]; final char offset = 'a'; final char offsetA = 'A'; char key; char door; for (int i = 0; i < n; i++) { key = (char)(s.charAt(i*2) - offset); found[key]++; door = (char)(s.charAt(i*2 + 1) - offsetA); if (found[door] > 0) { found[door]--; } else { bought[door]++; } } int result = 0; for (int j = 0; j < 26; j++) { result += bought[j]; } System.out.println(result); } }
Java
["3\naAbB", "4\naBaCaB", "5\nxYyXzZaZ"]
2 seconds
["0", "3", "2"]
null
Java 8
standard input
[ "hashing", "greedy", "strings" ]
80fdb95372c1e8d558b8c8f31c9d0479
The first line of the input contains a positive integer n (2 ≀ n ≀ 105)Β β€”Β the number of rooms in the house. The second line of the input contains string s of length 2Β·n - 2. Let's number the elements of the string from left to right, starting from one. The odd positions in the given string s contain lowercase Latin lettersΒ β€”Β the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter β€” the type of the key that lies in room number (i + 1) / 2. The even positions in the given string contain uppercase Latin letters β€” the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter β€” the type of the door that leads from room i / 2 to room i / 2 + 1.
1,100
Print the only integer β€” the minimum number of keys that Vitaly needs to buy to surely get from room one to room n.
standard output
PASSED
032373d9215860d0ea686542d7174cc0
train_004.jsonl
1427387400
After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on β€” you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.The potato pie is located in the n-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int key[] = new int[26]; int n,count=0; String s; n=scan.nextInt(); s=scan.nextLine(); s=scan.nextLine(); for(int i=0;i<2*n-2;){ key[s.charAt(i++)-97]++; if(key[s.charAt(i)-65]>0){ key[s.charAt(i++)-65]--; }else{ count++; i++; } } System.out.println(count); scan.close(); } }
Java
["3\naAbB", "4\naBaCaB", "5\nxYyXzZaZ"]
2 seconds
["0", "3", "2"]
null
Java 8
standard input
[ "hashing", "greedy", "strings" ]
80fdb95372c1e8d558b8c8f31c9d0479
The first line of the input contains a positive integer n (2 ≀ n ≀ 105)Β β€”Β the number of rooms in the house. The second line of the input contains string s of length 2Β·n - 2. Let's number the elements of the string from left to right, starting from one. The odd positions in the given string s contain lowercase Latin lettersΒ β€”Β the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter β€” the type of the key that lies in room number (i + 1) / 2. The even positions in the given string contain uppercase Latin letters β€” the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter β€” the type of the door that leads from room i / 2 to room i / 2 + 1.
1,100
Print the only integer β€” the minimum number of keys that Vitaly needs to buy to surely get from room one to room n.
standard output
PASSED
1a664dba928539b035880738ea01a6ad
train_004.jsonl
1427387400
After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on β€” you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.The potato pie is located in the n-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.HashSet; import java.util.StringTokenizer; public class Aces { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in) ; int n =sc.nextInt() , ans = 0 ; String s = sc.next() ; HashMap<Character, Character> map = new HashMap<>() ; HashMap<Character ,Integer > has = new HashMap<>() ; char upper = 'A' , lower = 'a' ; for(int i = 0 ; i <26 ; i ++){ map.put( lower , upper ) ; has.put( upper , 0) ; lower++ ; upper++ ; } for(int i = 0 ; i < s.length() ; i +=2){ upper = s.charAt(i+1) ; lower = s.charAt(i) ; char currupper = map.get(lower) ; has.put(currupper , has.get(currupper)+1 ) ; if(has.get(upper)==0)ans++ ; else has.put( upper , has.get(upper)-1 ) ; } System.out.println(ans); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["3\naAbB", "4\naBaCaB", "5\nxYyXzZaZ"]
2 seconds
["0", "3", "2"]
null
Java 8
standard input
[ "hashing", "greedy", "strings" ]
80fdb95372c1e8d558b8c8f31c9d0479
The first line of the input contains a positive integer n (2 ≀ n ≀ 105)Β β€”Β the number of rooms in the house. The second line of the input contains string s of length 2Β·n - 2. Let's number the elements of the string from left to right, starting from one. The odd positions in the given string s contain lowercase Latin lettersΒ β€”Β the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter β€” the type of the key that lies in room number (i + 1) / 2. The even positions in the given string contain uppercase Latin letters β€” the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter β€” the type of the door that leads from room i / 2 to room i / 2 + 1.
1,100
Print the only integer β€” the minimum number of keys that Vitaly needs to buy to surely get from room one to room n.
standard output
PASSED
fd2b1d30ec1aab897e453e71aa1a4a71
train_004.jsonl
1427387400
After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on β€” you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.The potato pie is located in the n-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.StringTokenizer; /** * Created by yujiahao on 5/21/16. */ public class cf_297_a { private FastScanner in; private PrintWriter out; public void solve() throws IOException { int n = in.nextInt(); char[] c = in.next().toCharArray(); int count = 0; int[] has = new int[26]; for (int i=0; i<2*n-2; i++){ if (i%2==0){ has[c[i]-'a'] ++; }else{ if (has[c[i]-'A']>=1){ has[c[i]-'A']--; }else{ count++; } } } out.print(count); } public void run() { try { in = new FastScanner(); out = new PrintWriter(System.out); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); } } private class FastScanner { private BufferedReader br; private StringTokenizer st; public 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()); } public double nextDouble() { return Double.parseDouble(next()); } public BigInteger nextBigInteger() { return new BigInteger(next());} } public static void main(String[] arg) { new cf_297_a().run(); } }
Java
["3\naAbB", "4\naBaCaB", "5\nxYyXzZaZ"]
2 seconds
["0", "3", "2"]
null
Java 8
standard input
[ "hashing", "greedy", "strings" ]
80fdb95372c1e8d558b8c8f31c9d0479
The first line of the input contains a positive integer n (2 ≀ n ≀ 105)Β β€”Β the number of rooms in the house. The second line of the input contains string s of length 2Β·n - 2. Let's number the elements of the string from left to right, starting from one. The odd positions in the given string s contain lowercase Latin lettersΒ β€”Β the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter β€” the type of the key that lies in room number (i + 1) / 2. The even positions in the given string contain uppercase Latin letters β€” the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter β€” the type of the door that leads from room i / 2 to room i / 2 + 1.
1,100
Print the only integer β€” the minimum number of keys that Vitaly needs to buy to surely get from room one to room n.
standard output
PASSED
bddff3df0a3c9e293cd95c7fa3acf359
train_004.jsonl
1427387400
After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on β€” you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.The potato pie is located in the n-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number.
256 megabytes
import java.io.IOException; import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author saket */ 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); VitailyAndPie solver = new VitailyAndPie(); solver.solve(1, in, out); out.close(); } } class VitailyAndPie { public void solve(int testNumber, InputReader in, OutputWriter out) { int n=in.readInt(); int keys[]=new int[26]; String s=in.readLine(); int count=0; for(int i=0;i<s.length();i++) { if(Character.isLowerCase(s.charAt(i))) { keys[s.charAt(i)-'a']++; } else { if( keys[s.charAt(i)-'A']==0) count++; else keys[s.charAt(i)-'A']--; } } out.printLine(count); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } private String readLine0() { StringBuilder buf = new StringBuilder(); int c = read(); while (c != '\n' && c != -1) { if (c != '\r') buf.appendCodePoint(c); c = read(); } return buf.toString(); } public String readLine() { String s = readLine0(); while (s.trim().length() == 0) s = readLine0(); return s; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } }
Java
["3\naAbB", "4\naBaCaB", "5\nxYyXzZaZ"]
2 seconds
["0", "3", "2"]
null
Java 8
standard input
[ "hashing", "greedy", "strings" ]
80fdb95372c1e8d558b8c8f31c9d0479
The first line of the input contains a positive integer n (2 ≀ n ≀ 105)Β β€”Β the number of rooms in the house. The second line of the input contains string s of length 2Β·n - 2. Let's number the elements of the string from left to right, starting from one. The odd positions in the given string s contain lowercase Latin lettersΒ β€”Β the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter β€” the type of the key that lies in room number (i + 1) / 2. The even positions in the given string contain uppercase Latin letters β€” the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter β€” the type of the door that leads from room i / 2 to room i / 2 + 1.
1,100
Print the only integer β€” the minimum number of keys that Vitaly needs to buy to surely get from room one to room n.
standard output
PASSED
160a38f4bfb709befbf6f3a8cc149c2b
train_004.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.io.*; import java.util.Arrays; public class chess2 { public static void print2(char diff[][]){ for(int i=0;i<diff.length;i++){ for(int j=0;j<diff[0].length;j++) System.out.print(diff[i][j]); System.out.println(); } } public static void print(int diff[][]){ for(int i=0;i<diff.length;i++){ for(int j=0;j<diff[0].length;j++) System.out.print(diff[i][j]); System.out.println(); } } public static void computeDiff(char piece[][],char board[][], long n, int diff[][], int itr){ for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ //System.out.println("Comparing "+piece[i][j]+" and "+board[i][j]); if(piece[i][j]==board[i][j]) diff[1][itr]++; else diff[0][itr]++; } } } public static void main(String[] args) throws IOException, FileNotFoundException { // TODO Auto-generated method stub //BufferedReader b = new BufferedReader(new FileReader("C:\\Users\\mohit.18\\Desktop\\Graph\\chessInput.txt")); BufferedReader b = new BufferedReader(new InputStreamReader(System.in)); long n = Long.parseLong(b.readLine()); char a[][] = new char[(int)n][(int)n]; for(long i=0;i<n;i++) { String g = b.readLine(); if(g.equalsIgnoreCase("")) { i--; continue; } for(long j=0;j<n;j++) { a[(int)i][(int)j] = g.charAt((int)j); } } char c[][] = new char[(int)n][(int)n]; for(long i=0;i<n;i++) { String g = b.readLine(); if(g.equalsIgnoreCase("")) { i--; continue; } for(long j=0;j<n;j++) { c[(int)i][(int)j] = g.charAt((int)j); } } char d[][] = new char[(int)n][(int)n]; for(long i=0;i<n;i++) { String g = b.readLine(); if(g.equalsIgnoreCase("")) { i--; continue; } for(long j=0;j<n;j++) { d[(int)i][(int)j] = g.charAt((int)j); } } char e[][] = new char[(int)n][(int)n]; for(long i=0;i<n;i++) { String g = b.readLine(); if(g.equalsIgnoreCase("")) { i--; continue; } for(long j=0;j<n;j++) { e[(int)i][(int)j] = g.charAt((int)j); } } int diff[][] = new int[2][4]; char board[][] = new char[(int)n][(int)n]; int num = 1; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ board[i][j] = (char) (num+'0'); if(num==0) num++; else num--; } } /*print2(a); print2(c); print2(d); print2(e); print2(board);*/ computeDiff(a,board,n,diff,0); computeDiff(c,board,n,diff,1); computeDiff(d,board,n,diff,2); computeDiff(e,board,n,diff,3); //print(diff); Arrays.sort(diff[0]); Arrays.sort(diff[1]); //print(diff); System.out.println(diff[0][0] + diff[0][1] + diff[1][0] + diff[1][1]); } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≀ n ≀ 100) β€” the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number β€” minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
7d05cb14c756e3d142fba971a855f18c
train_004.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Stack; import java.util.StringTokenizer; public class Ezz { static int a1[][],a2[][]; static int diff(int a[][],int b[][]) { int q = 0; for (int i = 0 ; i < a.length ; ++i) { for (int j = 0 ; j < a[i].length ; ++j) { if (a[i][j] != b[i][j]) { ++q; } } } return q; } public static void main(String[]args) throws Throwable { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); int arr[][][] = new int[4][n][n]; a1 = new int[n][n]; a2 = new int[n][n]; int cur = 1; for (int i = 0 ; i < n ; ++i) { for (int j = 0 ; j < n ; ++j) { a1[i][j] = cur; cur ^= 1; } } cur = 0; for (int i = 0 ; i < n ; ++i) { for (int j = 0 ; j < n ; ++j) { a2[i][j] = cur; cur ^= 1; } } for (int i = 0 ; i < 4 ; ++i) { for (int j = 0 ; j < n ; ++j) { String str = sc.next(); for (int k = 0 ; k < n ; ++k) { arr[i][j][k] = str.charAt(k) - '0'; } } } int best = 1 << 30; for (int msk = 0; msk < (1 << 4) ; ++msk) { if (Integer.bitCount(msk) != 2) { continue; } int cost = 0; for (int i = 0 ; i < 4 ; ++i) { if ((msk & (1 << i)) > 0) { cost += diff(arr[i],a1); } else { cost += diff(arr[i],a2); } } best = Math.min(best, cost); } out.println(best); out.flush(); out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(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 { return Double.parseDouble(next()); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≀ n ≀ 100) β€” the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number β€” minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
42a1322d7f5fd3154cd13fd25f8a5e32
train_004.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.*; public class contest { public static void main(String args[]) throws IOException { ContestReader reader = new ContestReader(System.in); int n = reader.nextInt(); int ans = 0; int[] temp = new int[4]; int[][][] desk = new int[4][n][n]; String line; for (int q = 0; q<4; q++) { for (int i = 0; i<n; i++) { line = reader.next(); for (int j = 0; j < n; j++) { desk[q][i][j] = Character.digit(line.charAt(j), 10); } } temp[q] = evaluateMain(desk[q]); } Arrays.sort(temp); ans = temp[0]+temp[1]+(n*n-temp[2])+(n*n-temp[3]); System.out.println(ans); } static int evaluateMain(int[][] matrix) { int res = 0; for (int i = 0; i<matrix.length; i++) for (int j = 0; j<matrix.length; j++) if (matrix[i][j]!=((i+j)%2)) res++; return res; } } class ContestReader { static BufferedReader reader; static StringTokenizer tokenizer; static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input)); tokenizer = new StringTokenizer(""); } ContestReader(InputStream inpt) { init(inpt); } static String next() throws IOException { while (!tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer( reader.readLine()); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(next()); } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≀ n ≀ 100) β€” the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number β€” minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
61323a358e0b3ccd5a3b2a7d31bed338
train_004.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * Created by himanshubhardwaj on 08/11/18. * Statement: https://codeforces.com/contest/961/problem/C * 2:01 */ public class Chessboard { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); Board[] b = new Board[4]; for (int i = 0; i < 4; i++) { b[i] = new Board(n); for (int j = 0; j < n; j++) { String str = br.readLine(); for (int k = 0; k < n; k++) { if (str.charAt(k) != '0') { b[i].mat[j][k] = 1; } } } if (i != 3) { String ss = br.readLine(); } } int cost = Integer.MAX_VALUE; for (int i = 0; i < 4; i++) { for (int j = i + 1; j < 4; j++) { cost = Math.min(cost, Board.computeCostToColourWhite(b, i, j) + Board.computeCostToColourBlack(b, i, j)); } } System.out.print(cost); } } class Board { int[][] mat; public Board(int n) { mat = new int[n][n]; } public static int computeCostToColourWhite(Board[] boa, int a, int b) { return costToPrintWhite(boa[a].mat) + costToPrintWhite(boa[b].mat); } private static int costToPrintWhite(int[][] mat) { int cost = 0; for (int i = 0; i < mat.length; i++) { for (int j = 0; j < mat.length; j++) { if ((i + j) % 2 == 0) { if (mat[i][j] != 0) { cost++; } } else { if (mat[i][j] != 1) { cost++; } } } } return cost; } private static int costToPrintBlack(int[][] mat) { int cost = 0; for (int i = 0; i < mat.length; i++) { for (int j = 0; j < mat.length; j++) { if ((i + j) % 2 == 1) { if (mat[i][j] != 0) { cost++; } } else { if (mat[i][j] != 1) { cost++; } } } } return cost; } public static int computeCostToColourBlack(Board[] boa, int a, int b) { int cost = 0; for (int i = 0; i < 4; i++) { if (i != a && i != b) { cost += costToPrintBlack(boa[i].mat); } } return cost; } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≀ n ≀ 100) β€” the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number β€” minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
87dc835ab955147ff1b85ec3332bf1bd
train_004.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; public class CF_961_C_CHESS_BOARD { static Pair [] p; static int []curr = new int [2]; static int min = Integer.MAX_VALUE; public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[][] mat = new int[2 * n][2 * n]; int[][] ideal1 = new int[n][n]; int[][] ideal2 = new int[n][n]; int v1 = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) ideal1[i][j] = (v1 ^= 1); } v1 = 1; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) ideal2[i][j] = (v1 ^= 1); } p = new Pair[4]; for (int k = 0; k < 4; k++) { int ans1 = 0; int ans2 = 0; for (int i = 0; i < n; i++) { String s = sc.next(); for (int j = 0; j < n; j++) { mat[i][j] = Integer.parseInt(s.charAt(j) + ""); if(mat[i][j] !=ideal1[i][j]) ans1++; if(mat[i][j] !=ideal2[i][j]) ans2++; } } p[k] = new Pair(ans1, ans2); } curr = new int []{0,1,0,2,0,3,1,2,1,3,2,3}; for(int i = 0 ; i<curr.length-1 ;i++) { int i1 = curr[i]; int i2 = curr[i+1]; int i3 = -1; int i4 = -1; for(int k = 0 ; k<4 ;k++) if(i1!=k && i2!=k) { i3 = k; break; } for(int k = 0 ; k<4; k++) if(i1!=k && i2!=k && i3!=k) { i4 = k; break; } min = Math.min(p[i1].p1+p[i2].p1+p[i3].p2+p[i4].p2, min); } System.out.println(min); } static class Pair{ int p1 , p2; public Pair(int p1 , int p2 ) { this.p1 = p1 ; this.p2 = p2 ; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine(), ""); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≀ n ≀ 100) β€” the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number β€” minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
6875424379e0af1ca6514034d483d713
train_004.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
//package uva; import java.util.*; import java.io.*; public class Uva { public static void main(String arg[])throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); boolean a[][] = new boolean[4][n*n]; for(int x=0;x<4;x++){ for(int i=0;i<n;i++){ String s = br.readLine(); for(int j=0;j<s.length();j++){ if(s.charAt(j)=='1'){ a[x][i*n+j] = true; } } } if(x<3){ br.readLine(); } } int ans[][] = new int[2][4]; for(int i=0;i<2;i++){ for(int j=0;j<4;j++){ int count = 0; for(int k=0;k<n*n;k++){ if(a[j][k]&&(k+i)%2==1){ count++; }else if(!a[j][k]&&(k+i)%2==0){ count++; } } ans[i][j] = count; } } int a1 = ans[1][0]+ans[1][1]+ans[0][2]+ans[0][3]; int a2 = ans[1][0]+ans[0][1]+ans[1][2]+ans[0][3]; int a3 = ans[1][0]+ans[0][1]+ans[0][2]+ans[1][3]; int a4 = ans[0][0]+ans[1][1]+ans[1][2]+ans[0][3]; int a5 = ans[0][0]+ans[1][1]+ans[0][2]+ans[1][3]; int a6 = ans[0][0]+ans[0][1]+ans[1][2]+ans[1][3]; int min1 = Math.min(a1,a2); int min2 = Math.min(a3,a4); int min3 = Math.min(a5,a6); int min4 = Math.min(min1,min2); min4 = Math.min(min4,min3); System.out.println(min4); } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≀ n ≀ 100) β€” the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number β€” minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
0f42d1003df87db4c227cef72e4ea9d2
train_004.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.util.Scanner; public class c961 { static int getCntDiff(int startVal) { int res=0; int val=startVal; for(int x=0; x<2*n; x++) { for(int y=0; y<2*n; y++) { if(b[x][y]!=val) { res+=1; } if(val==0) { val=1; } else { val=0; } } if(val==0) { val=1; } else { val=0; } } return res; } static int check(int x, int y) { int cntR=0; int cntW=0; if(x>0) { if (b[x-1][y]!=b[x][y]) { cntR+=1; } else { cntW+=1; } } if (x<2*n-1) { if (b[x+1][y]!=b[x][y]) { cntR+=1; } else { cntW+=1; } } if (y>0) { if (b[x][y-1]!=b[x][y]) { cntR+=1; } else { cntW+=1; } } if (y<2*n-1) { if (b[x][y+1]!=b[x][y]) { cntR+=1; } else { cntW+=1; } } if (cntR>cntW) { return 1; } else if (cntR<cntW) { return -1; } else { return 0; } } static void fill(int i,int x0, int y0) { mb[x0][y0]=1; for(int x=x0*n; x<x0*n+n;x++) { for(int y=y0*n; y<y0*n+n; y++) { b[x][y]=a[i][x-x0*n][y-y0*n]; } } } static int[][][] a; static int[][] b; static int[][] mb=new int[2][2]; static int n; public static void main(String args[]) { Scanner sc = new Scanner(System.in); n = sc.nextInt(); a=new int[4][n][n]; for(int i=0; i<4; i++) { for(int x=0; x<n;x++) { char[] s=sc.next().toCharArray(); for(int y=0;y<n; y++) { a[i][x][y]=s[y]-48; } } } int minCntDiff=2*n*2*n; for(int x1=0;x1<2;x1++) { for(int y1=0;y1<2;y1++) { for(int x2=0; x2<2; x2++) { for(int y2=0; y2<2; y2++) { for(int x3=0; x3<2; x3++) { for(int y3=0; y3<2; y3++) { if(x1==x2 && y1==y2) { continue; } if(x1==x3 && y1==y3) { continue; } if(x2==x3 && y2==y3) { continue; } b= new int[2*n][2*n]; fill(0,x1,y1); fill(1,x2,y2); fill(2,x3,y3); boolean changed; for(int x4=0; x4<2;x4++) { for(int y4=0; y4<2; y4++) { if(mb[x4][y4]==0) { fill(3,x4,y4); } } } int[][] b0; b0 = new int[2*n][]; for(int i=0;i<2*n;i++) { b0[i]=b[i].clone(); } int step=0; /* !!! System.out.println("Step "+ step); for(int x=0; x<2*n;x++) { for(int y=0; y<2*n;y++) { System.out.print(b[x][y]); } System.out.println(""); } !!! do { changed=false; for (int x=0; x<2*n; x++) { for(int y=0; y<2*n; y++) { if (check(x, y)<0) { changed = true; if (b[x][y]==1) { b[x][y]=0; } else { b[x][y]=1; } } } } step+=1; !!! System.out.println("Step "+ step); for(int x=0; x<2*n;x++) { for(int y=0; y<2*n;y++) { System.out.print(b[x][y]); } System.out.println(""); } !!! } while(changed); */ int cntDiff0 = getCntDiff(0); int cntDiff1 = getCntDiff(1); if (cntDiff0<minCntDiff) { minCntDiff=cntDiff0; } if (cntDiff1<minCntDiff) { minCntDiff=cntDiff1; } mb=new int[2][2]; break; } } } } } } System.out.println(minCntDiff); } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≀ n ≀ 100) β€” the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number β€” minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
71f3459903aeed75b788720579c768f8
train_004.jsonl
1477922700
Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere. Zahar has n stones which are rectangular parallelepipeds. The edges sizes of the i-th of them are ai, bi and ci. He can take no more than two stones and present them to Kostya. If Zahar takes two stones, he should glue them together on one of the faces in order to get a new piece of rectangular parallelepiped of marble. Thus, it is possible to glue a pair of stones together if and only if two faces on which they are glued together match as rectangles. In such gluing it is allowed to rotate and flip the stones in any way. Help Zahar choose such a present so that Kostya can carve a sphere of the maximum possible volume and present it to Zahar.
256 megabytes
import java.io.BufferedInputStream; import java.util.HashMap; import java.util.Map; import java.util.Scanner; /** * Created by leen on 13/11/2016. */ public class _733D { public static void main(String[] args) { Scanner scan = new Scanner(new BufferedInputStream(System.in, 1024 * 128)); int n = scan.nextInt(); L2Map map = new L2Map(); Parallelepiped[] data = new Parallelepiped[n]; for(int i = 0; i < n; i++) { int a = scan.nextInt(), b = scan.nextInt(), c = scan.nextInt(); Parallelepiped p = new Parallelepiped(i,a,b,c); data[i] = p; map.put(p); } int maxDiameter = -1; int first = -1, second = -1; for(Parallelepiped p : data) { if(p.c > maxDiameter) { maxDiameter = p.c; first = p.index; second = -1; } Parallelepiped p2 = map.get(p); if(p2 != null) { int d = Math.min(Math.min(p.a,p.b),p.c+p2.c); if(d > maxDiameter) { first = p.index; second = p2.index; maxDiameter = d; } } } if(second == -1) { System.out.println(1); System.out.println(first+1); } else { System.out.println(2); System.out.println((first+1) + " " + (second+1)); } } static class Parallelepiped { final int index; final int a, b, c; Parallelepiped(int index, int a, int b, int c) { this.index = index; int m1 = Math.max(a,b), m2 = Math.max(b,c), m3 = Math.max(a,c); int m4 = Math.max(m1,m2), m5 = Math.min(Math.min(m1,m2),m3), m6 = Math.min(Math.min(a,b),c); this.a = m4; this.b = m5; this.c = m6; } } static class L2Map { private Map<Integer, Map<Integer, Parallelepiped[]>> map = new HashMap<Integer, Map<Integer, Parallelepiped[]>>(); void put(Parallelepiped v) { Map<Integer,Parallelepiped[]> map2 = map.get(v.a); if(map2 == null) { map2 = new HashMap<Integer, Parallelepiped[]>(); map.put(v.a, map2); } Parallelepiped[] currentVs = map2.get(v.b); if(currentVs == null) { currentVs = new Parallelepiped[2]; currentVs[0] = v; map2.put(v.b, currentVs); } else { if(currentVs[0].c < v.c) { currentVs[1] = currentVs[0]; currentVs[0] = v; } else if(currentVs[1] == null || currentVs[1].c < v.c) currentVs[1] = v; } } Parallelepiped get(Parallelepiped p) { Map<Integer,Parallelepiped[]> map2 = map.get(p.a); if(map2 == null) return null; Parallelepiped[] values = map2.get(p.b); if(values == null) return null; if(values[0] == p) return values[1]; else return values[0]; } } }
Java
["6\n5 5 5\n3 2 4\n1 4 1\n2 1 3\n3 2 4\n3 3 4", "7\n10 7 8\n5 10 3\n4 2 6\n5 5 5\n10 2 8\n4 2 1\n7 7 7"]
3 seconds
["1\n1", "2\n1 5"]
NoteIn the first example we can connect the pairs of stones: 2 and 4, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 2 and 5, the size of the parallelepiped: 3 × 2 × 8 or 6 × 2 × 4 or 3 × 4 × 4, the radius of the inscribed sphere 1, or 1, or 1.5 respectively. 2 and 6, the size of the parallelepiped: 3 × 5 × 4, the radius of the inscribed sphere 1.5 4 and 5, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 5 and 6, the size of the parallelepiped: 3 × 4 × 5, the radius of the inscribed sphere 1.5 Or take only one stone: 1 the size of the parallelepiped: 5 × 5 × 5, the radius of the inscribed sphere 2.5 2 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 3 the size of the parallelepiped: 1 × 4 × 1, the radius of the inscribed sphere 0.5 4 the size of the parallelepiped: 2 × 1 × 3, the radius of the inscribed sphere 0.5 5 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 6 the size of the parallelepiped: 3 × 3 × 4, the radius of the inscribed sphere 1.5 It is most profitable to take only the first stone.
Java 8
standard input
[ "data structures", "hashing" ]
ef82292a6591de818ddda9f426208291
The first line contains the integer n (1 ≀ n ≀ 105). n lines follow, in the i-th of which there are three integers ai, bi and ci (1 ≀ ai, bi, ci ≀ 109)Β β€” the lengths of edges of the i-th stone. Note, that two stones may have exactly the same sizes, but they still will be considered two different stones.
1,600
In the first line print k (1 ≀ k ≀ 2) the number of stones which Zahar has chosen. In the second line print k distinct integers from 1 to nΒ β€” the numbers of stones which Zahar needs to choose. Consider that stones are numbered from 1 to n in the order as they are given in the input data. You can print the stones in arbitrary order. If there are several answers print any of them.
standard output
PASSED
2a92b6a301a510e79b53a5ad8e15ad1a
train_004.jsonl
1477922700
Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere. Zahar has n stones which are rectangular parallelepipeds. The edges sizes of the i-th of them are ai, bi and ci. He can take no more than two stones and present them to Kostya. If Zahar takes two stones, he should glue them together on one of the faces in order to get a new piece of rectangular parallelepiped of marble. Thus, it is possible to glue a pair of stones together if and only if two faces on which they are glued together match as rectangles. In such gluing it is allowed to rotate and flip the stones in any way. Help Zahar choose such a present so that Kostya can carve a sphere of the maximum possible volume and present it to Zahar.
256 megabytes
import java.io.BufferedInputStream; import java.util.HashMap; import java.util.Map; import java.util.Scanner; /** * Created by leen on 13/11/2016. */ public class Skulptor2 { public static void main(String[] args) { Scanner scan = new Scanner(new BufferedInputStream(System.in, 1024 * 128)); int n = scan.nextInt(); L2Map map = new L2Map(); Parallelepiped[] data = new Parallelepiped[n]; for(int i = 0; i < n; i++) { int a = scan.nextInt(), b = scan.nextInt(), c = scan.nextInt(); Parallelepiped p = new Parallelepiped(i,a,b,c); data[i] = p; map.put(p); } int maxDiameter = -1; int first = -1, second = -1; for(Parallelepiped p : data) { if(p.c > maxDiameter) { maxDiameter = p.c; first = p.index; second = -1; } Parallelepiped p2 = map.get(p); if(p2 != null) { int d = Math.min(Math.min(p.a,p.b),p.c+p2.c); if(d > maxDiameter) { first = p.index; second = p2.index; maxDiameter = d; } } } if(second == -1) { System.out.println(1); System.out.println(first+1); } else { System.out.println(2); System.out.println((first+1) + " " + (second+1)); } } static class Parallelepiped { final int index; final int a, b, c; Parallelepiped(int index, int a, int b, int c) { this.index = index; int m1 = Math.max(a,b), m2 = Math.max(b,c), m3 = Math.max(a,c); int m4 = Math.max(m1,m2), m5 = Math.min(Math.min(m1,m2),m3), m6 = Math.min(Math.min(a,b),c); this.a = m4; this.b = m5; this.c = m6; } } static class L2Map { private Map<Integer, Map<Integer, Parallelepiped[]>> map = new HashMap<Integer, Map<Integer, Parallelepiped[]>>(); void put(Parallelepiped v) { Map<Integer,Parallelepiped[]> map2 = map.get(v.a); if(map2 == null) { map2 = new HashMap<Integer, Parallelepiped[]>(); map.put(v.a, map2); } Parallelepiped[] currentVs = map2.get(v.b); if(currentVs == null) { currentVs = new Parallelepiped[2]; currentVs[0] = v; map2.put(v.b, currentVs); } else { if(currentVs[0].c < v.c) { currentVs[1] = currentVs[0]; currentVs[0] = v; } else if(currentVs[1] == null || currentVs[1].c < v.c) currentVs[1] = v; } } Parallelepiped get(Parallelepiped p) { Map<Integer,Parallelepiped[]> map2 = map.get(p.a); if(map2 == null) return null; Parallelepiped[] values = map2.get(p.b); if(values == null) return null; if(values[0] == p) return values[1]; else return values[0]; } } }
Java
["6\n5 5 5\n3 2 4\n1 4 1\n2 1 3\n3 2 4\n3 3 4", "7\n10 7 8\n5 10 3\n4 2 6\n5 5 5\n10 2 8\n4 2 1\n7 7 7"]
3 seconds
["1\n1", "2\n1 5"]
NoteIn the first example we can connect the pairs of stones: 2 and 4, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 2 and 5, the size of the parallelepiped: 3 × 2 × 8 or 6 × 2 × 4 or 3 × 4 × 4, the radius of the inscribed sphere 1, or 1, or 1.5 respectively. 2 and 6, the size of the parallelepiped: 3 × 5 × 4, the radius of the inscribed sphere 1.5 4 and 5, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 5 and 6, the size of the parallelepiped: 3 × 4 × 5, the radius of the inscribed sphere 1.5 Or take only one stone: 1 the size of the parallelepiped: 5 × 5 × 5, the radius of the inscribed sphere 2.5 2 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 3 the size of the parallelepiped: 1 × 4 × 1, the radius of the inscribed sphere 0.5 4 the size of the parallelepiped: 2 × 1 × 3, the radius of the inscribed sphere 0.5 5 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 6 the size of the parallelepiped: 3 × 3 × 4, the radius of the inscribed sphere 1.5 It is most profitable to take only the first stone.
Java 8
standard input
[ "data structures", "hashing" ]
ef82292a6591de818ddda9f426208291
The first line contains the integer n (1 ≀ n ≀ 105). n lines follow, in the i-th of which there are three integers ai, bi and ci (1 ≀ ai, bi, ci ≀ 109)Β β€” the lengths of edges of the i-th stone. Note, that two stones may have exactly the same sizes, but they still will be considered two different stones.
1,600
In the first line print k (1 ≀ k ≀ 2) the number of stones which Zahar has chosen. In the second line print k distinct integers from 1 to nΒ β€” the numbers of stones which Zahar needs to choose. Consider that stones are numbered from 1 to n in the order as they are given in the input data. You can print the stones in arbitrary order. If there are several answers print any of them.
standard output
PASSED
af9f9e29e5e8cb177177f385a1ae614f
train_004.jsonl
1477922700
Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere. Zahar has n stones which are rectangular parallelepipeds. The edges sizes of the i-th of them are ai, bi and ci. He can take no more than two stones and present them to Kostya. If Zahar takes two stones, he should glue them together on one of the faces in order to get a new piece of rectangular parallelepiped of marble. Thus, it is possible to glue a pair of stones together if and only if two faces on which they are glued together match as rectangles. In such gluing it is allowed to rotate and flip the stones in any way. Help Zahar choose such a present so that Kostya can carve a sphere of the maximum possible volume and present it to Zahar.
256 megabytes
import java.awt.event.InputEvent; import java.util.*; import org.omg.PortableInterceptor.INACTIVE; public class CodeforcesRound378 { public static class Marble { int a, b, c, index; public Marble(){}; public Marble(int A, int B, int C, int Index) { a = A; b = B; c = C; index = Index; } } public static void main(String[] args) { Scanner input = new Scanner(System.in); int a,b,c, maxIndexFirst = -1, maxIndexSecond = -1; int n = input.nextInt(); ArrayList<Marble> marbles = new ArrayList<Marble>(n); double max = -1, newVolume = 1; //Enter the array for (int i=0; i<n; i++) { a = input.nextInt(); b = input.nextInt(); c = input.nextInt(); marbles.add(new Marble(a, b, c, i)); marbles.add(new Marble(a, c, b, i)); marbles.add(new Marble(b, a, c, i)); marbles.add(new Marble(b, c, a, i)); marbles.add(new Marble(c, a, b, i)); marbles.add(new Marble(c, b, a, i)); //Find individual maximum double marbleVolume = Math.min(Math.min(a, b), c); if (marbleVolume > max) { max = marbleVolume; maxIndexFirst = i; } } //1st Sort: A and B Collections.sort(marbles, new Comparator<Marble>() { public int compare(Marble x, Marble y) { if (x.a == y.a && x.b == y.b) return y.c - x.c; else if (x.a == y.a) return y.b - x.b; else return y.a - x.a; } }); for (int i=0; i<marbles.size()-1; i++) { Marble currentMarble = marbles.get(i); Marble nextMarble = marbles.get(i+1); if (currentMarble.index == nextMarble.index) continue; if (currentMarble.a == nextMarble.a && currentMarble.b == nextMarble.b) newVolume = Math.min(Math.min((currentMarble.c + nextMarble.c), currentMarble.a), currentMarble.b); else continue; if (newVolume > max) { max = newVolume; maxIndexFirst = currentMarble.index; maxIndexSecond = nextMarble.index; } } //2st Sort: B and C Collections.sort(marbles, new Comparator<Marble>() { public int compare(Marble x, Marble y) { if (x.c == y.c && x.b == y.b) return y.a - x.a; else if (x.c == y.c) return y.b - x.b; else return y.c - x.c; } }); for (int i=0; i<marbles.size()-1; i++) { Marble currentMarble = marbles.get(i); Marble nextMarble = marbles.get(i+1); if (currentMarble.index == nextMarble.index) continue; if (currentMarble.c == nextMarble.c && currentMarble.b == nextMarble.b) newVolume = Math.min(Math.min((currentMarble.a + nextMarble.a), currentMarble.b), currentMarble.c); else continue; if (newVolume > max) { max = newVolume; maxIndexFirst = currentMarble.index; maxIndexSecond = nextMarble.index; } } //3st Sort: C and A Collections.sort(marbles, new Comparator<Marble>() { public int compare(Marble x, Marble y) { if (x.c == y.c && x.a == y.a) return y.b - x.b; else if (x.c == y.c) return y.a - x.a; else return y.c - x.c; } }); for (int i=0; i<marbles.size()-1; i++) { Marble currentMarble = marbles.get(i); Marble nextMarble = marbles.get(i+1); if (currentMarble.index == nextMarble.index) continue; if (currentMarble.c == nextMarble.c && currentMarble.a == nextMarble.a) newVolume = Math.min(Math.min((currentMarble.b + nextMarble.b), currentMarble.c), currentMarble.a); else continue; if (newVolume > max) { max = newVolume; maxIndexFirst = currentMarble.index; maxIndexSecond = nextMarble.index; } } if (maxIndexSecond == -1) { System.out.println(1); System.out.println((maxIndexFirst + 1)); } else { System.out.println(2); System.out.println((maxIndexFirst + 1) + " " + (maxIndexSecond + 1)); } } }
Java
["6\n5 5 5\n3 2 4\n1 4 1\n2 1 3\n3 2 4\n3 3 4", "7\n10 7 8\n5 10 3\n4 2 6\n5 5 5\n10 2 8\n4 2 1\n7 7 7"]
3 seconds
["1\n1", "2\n1 5"]
NoteIn the first example we can connect the pairs of stones: 2 and 4, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 2 and 5, the size of the parallelepiped: 3 × 2 × 8 or 6 × 2 × 4 or 3 × 4 × 4, the radius of the inscribed sphere 1, or 1, or 1.5 respectively. 2 and 6, the size of the parallelepiped: 3 × 5 × 4, the radius of the inscribed sphere 1.5 4 and 5, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 5 and 6, the size of the parallelepiped: 3 × 4 × 5, the radius of the inscribed sphere 1.5 Or take only one stone: 1 the size of the parallelepiped: 5 × 5 × 5, the radius of the inscribed sphere 2.5 2 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 3 the size of the parallelepiped: 1 × 4 × 1, the radius of the inscribed sphere 0.5 4 the size of the parallelepiped: 2 × 1 × 3, the radius of the inscribed sphere 0.5 5 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 6 the size of the parallelepiped: 3 × 3 × 4, the radius of the inscribed sphere 1.5 It is most profitable to take only the first stone.
Java 8
standard input
[ "data structures", "hashing" ]
ef82292a6591de818ddda9f426208291
The first line contains the integer n (1 ≀ n ≀ 105). n lines follow, in the i-th of which there are three integers ai, bi and ci (1 ≀ ai, bi, ci ≀ 109)Β β€” the lengths of edges of the i-th stone. Note, that two stones may have exactly the same sizes, but they still will be considered two different stones.
1,600
In the first line print k (1 ≀ k ≀ 2) the number of stones which Zahar has chosen. In the second line print k distinct integers from 1 to nΒ β€” the numbers of stones which Zahar needs to choose. Consider that stones are numbered from 1 to n in the order as they are given in the input data. You can print the stones in arbitrary order. If there are several answers print any of them.
standard output
PASSED
3ca30c2c0cf87d469cda95be09fcd097
train_004.jsonl
1477922700
Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere. Zahar has n stones which are rectangular parallelepipeds. The edges sizes of the i-th of them are ai, bi and ci. He can take no more than two stones and present them to Kostya. If Zahar takes two stones, he should glue them together on one of the faces in order to get a new piece of rectangular parallelepiped of marble. Thus, it is possible to glue a pair of stones together if and only if two faces on which they are glued together match as rectangles. In such gluing it is allowed to rotate and flip the stones in any way. Help Zahar choose such a present so that Kostya can carve a sphere of the maximum possible volume and present it to Zahar.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.util.HashMap; import java.util.Map; public class Main { public static int nextInt(Reader in) throws IOException { String intAsString = nextString(in); return Integer.parseInt(intAsString); } public static String nextString(Reader in) throws IOException { StringBuilder stringBuilder = new StringBuilder(); int character = readNextNonWhitespaceCharacter(in); while (character != -1 && !Character.isWhitespace(character)) { stringBuilder.append((char) character); character = in.read(); } return stringBuilder.toString(); } private static int readNextNonWhitespaceCharacter(Reader in) throws IOException { int character; do { character = in.read(); } while (character != -1 && Character.isWhitespace(character)); return character; } public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int n = nextInt(in); Map<TwoSides, Record> map = new HashMap<>(); int maxRadius = 0; int maxFirstStoneNumber = 0; int maxSecondStoneNumber = 0; for (int i = 1; i <= n; i++) { int largestSide = nextInt(in); int mediumSide = nextInt(in); int smallestSide = nextInt(in); if (largestSide < mediumSide) { int tmp = largestSide; largestSide = mediumSide; mediumSide = tmp; } if (largestSide < smallestSide) { int tmp = largestSide; largestSide = smallestSide; smallestSide = tmp; } if (mediumSide < smallestSide) { int tmp = mediumSide; mediumSide = smallestSide; smallestSide = tmp; } TwoSides twoSides = new TwoSides(largestSide, mediumSide); Record rec = map.get(twoSides); if (rec == null) { map.put(twoSides, new Record(i, smallestSide, 0, 0, smallestSide)); if (smallestSide > maxRadius) { maxRadius = smallestSide; maxFirstStoneNumber = i; maxSecondStoneNumber = 0; } } else if (rec.sum < mediumSide) { if (smallestSide > rec.secondStoneSmallestSide) { rec.secondStoneSmallestSide = smallestSide; rec.secondStoneNumber = i; rec.sum = rec.firstStoneSmallestSide + smallestSide; rec.sum = rec.sum > mediumSide ? mediumSide : rec.sum; if (rec.secondStoneSmallestSide > rec.firstStoneSmallestSide) { int tmp = rec.firstStoneSmallestSide; rec.firstStoneSmallestSide = rec.secondStoneSmallestSide; rec.secondStoneSmallestSide = tmp; tmp = rec.firstStoneNumber; rec.firstStoneNumber = rec.secondStoneNumber; rec.secondStoneNumber = tmp; } if (rec.sum > maxRadius) { maxRadius = rec.sum; maxFirstStoneNumber = rec.firstStoneNumber; maxSecondStoneNumber = rec.secondStoneNumber; } map.put(twoSides, rec); } } } if (maxSecondStoneNumber == 0) { System.out.println(1); System.out.println(maxFirstStoneNumber); } else { System.out.println(2); System.out.println(maxFirstStoneNumber + " " + maxSecondStoneNumber); } } static class TwoSides { int largestSide; int mediumSide; public TwoSides(int largestSide, int mediumSide) { this.largestSide = largestSide; this.mediumSide = mediumSide; } @Override public boolean equals(Object obj) { TwoSides that = (TwoSides) obj; return this.largestSide == that.largestSide && this.mediumSide == that.mediumSide; } @Override public int hashCode() { String str = largestSide + "" + mediumSide; return str.hashCode(); } } static class Record { int firstStoneNumber; int firstStoneSmallestSide; int secondStoneNumber; int secondStoneSmallestSide; int sum; public Record(int firstStoneNumber, int firstStoneSmallestSide, int secondStoneNumber, int secondStoneSmallestSide, int sum) { this.firstStoneNumber = firstStoneNumber; this.secondStoneNumber = secondStoneNumber; this.firstStoneSmallestSide = firstStoneSmallestSide; this.secondStoneSmallestSide = secondStoneSmallestSide; this.sum = sum; } } }
Java
["6\n5 5 5\n3 2 4\n1 4 1\n2 1 3\n3 2 4\n3 3 4", "7\n10 7 8\n5 10 3\n4 2 6\n5 5 5\n10 2 8\n4 2 1\n7 7 7"]
3 seconds
["1\n1", "2\n1 5"]
NoteIn the first example we can connect the pairs of stones: 2 and 4, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 2 and 5, the size of the parallelepiped: 3 × 2 × 8 or 6 × 2 × 4 or 3 × 4 × 4, the radius of the inscribed sphere 1, or 1, or 1.5 respectively. 2 and 6, the size of the parallelepiped: 3 × 5 × 4, the radius of the inscribed sphere 1.5 4 and 5, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 5 and 6, the size of the parallelepiped: 3 × 4 × 5, the radius of the inscribed sphere 1.5 Or take only one stone: 1 the size of the parallelepiped: 5 × 5 × 5, the radius of the inscribed sphere 2.5 2 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 3 the size of the parallelepiped: 1 × 4 × 1, the radius of the inscribed sphere 0.5 4 the size of the parallelepiped: 2 × 1 × 3, the radius of the inscribed sphere 0.5 5 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 6 the size of the parallelepiped: 3 × 3 × 4, the radius of the inscribed sphere 1.5 It is most profitable to take only the first stone.
Java 8
standard input
[ "data structures", "hashing" ]
ef82292a6591de818ddda9f426208291
The first line contains the integer n (1 ≀ n ≀ 105). n lines follow, in the i-th of which there are three integers ai, bi and ci (1 ≀ ai, bi, ci ≀ 109)Β β€” the lengths of edges of the i-th stone. Note, that two stones may have exactly the same sizes, but they still will be considered two different stones.
1,600
In the first line print k (1 ≀ k ≀ 2) the number of stones which Zahar has chosen. In the second line print k distinct integers from 1 to nΒ β€” the numbers of stones which Zahar needs to choose. Consider that stones are numbered from 1 to n in the order as they are given in the input data. You can print the stones in arbitrary order. If there are several answers print any of them.
standard output
PASSED
95f5e42313b0b7eb3441ab52d7287d11
train_004.jsonl
1477922700
Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere. Zahar has n stones which are rectangular parallelepipeds. The edges sizes of the i-th of them are ai, bi and ci. He can take no more than two stones and present them to Kostya. If Zahar takes two stones, he should glue them together on one of the faces in order to get a new piece of rectangular parallelepiped of marble. Thus, it is possible to glue a pair of stones together if and only if two faces on which they are glued together match as rectangles. In such gluing it is allowed to rotate and flip the stones in any way. Help Zahar choose such a present so that Kostya can carve a sphere of the maximum possible volume and present it to Zahar.
256 megabytes
import java.util.*; public class D { int min(int a, int b, int c) { int t = a; if (b < t) t = b; if (c < t) t = c; return t; } int maxSize; List<Integer> ans; public D() { maxSize = 0; ans = new ArrayList<>(); } class Pair implements Comparable { public int x, y; public Pair() { } public Pair(int x0, int y0) { x = x0; y = y0; } @Override public boolean equals(Object o) { if (o instanceof Pair) { Pair p = (Pair) o; if ((x == p.x) && (y == p.y)) return true; if ((x == p.y) && (y == p.x)) return true; } return false; } @Override public int compareTo(Object o) { if (equals(o)) return 0; Pair p = (Pair) o; if (x * y < p.x * p.y) return -1; return 1; } } private void addToMap(Map<Pair, Pair> map, Pair r, int c, int index) { if (!map.containsKey(r)) { map.put(r, new Pair(c, index)); } else { Pair p = map.get(r); if (min(r.x, r.y, c + p.x) > maxSize) { maxSize = min(r.x, r.y, c + p.x); ans.clear(); ans.add(p.y); ans.add(index); } if (c > p.x) { map.put(r, new Pair(c, index)); } } } public void work() { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); Map<Pair, Pair> map = new TreeMap<>(); int[] d = new int[3]; for (int i = 0; i < n; ++i) { d[0] = sc.nextInt(); d[1] = sc.nextInt(); d[2] = sc.nextInt(); Arrays.sort(d); if (d[0] > maxSize) { maxSize = d[0]; ans.clear(); ans.add(i); } Pair r = new Pair(d[1], d[2]); addToMap(map, r, d[0], i); } System.out.println(ans.size()); for (Integer i : ans) { System.out.print((i + 1) + " "); } } public static void main(String[] args) { new D().work(); } }
Java
["6\n5 5 5\n3 2 4\n1 4 1\n2 1 3\n3 2 4\n3 3 4", "7\n10 7 8\n5 10 3\n4 2 6\n5 5 5\n10 2 8\n4 2 1\n7 7 7"]
3 seconds
["1\n1", "2\n1 5"]
NoteIn the first example we can connect the pairs of stones: 2 and 4, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 2 and 5, the size of the parallelepiped: 3 × 2 × 8 or 6 × 2 × 4 or 3 × 4 × 4, the radius of the inscribed sphere 1, or 1, or 1.5 respectively. 2 and 6, the size of the parallelepiped: 3 × 5 × 4, the radius of the inscribed sphere 1.5 4 and 5, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 5 and 6, the size of the parallelepiped: 3 × 4 × 5, the radius of the inscribed sphere 1.5 Or take only one stone: 1 the size of the parallelepiped: 5 × 5 × 5, the radius of the inscribed sphere 2.5 2 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 3 the size of the parallelepiped: 1 × 4 × 1, the radius of the inscribed sphere 0.5 4 the size of the parallelepiped: 2 × 1 × 3, the radius of the inscribed sphere 0.5 5 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 6 the size of the parallelepiped: 3 × 3 × 4, the radius of the inscribed sphere 1.5 It is most profitable to take only the first stone.
Java 8
standard input
[ "data structures", "hashing" ]
ef82292a6591de818ddda9f426208291
The first line contains the integer n (1 ≀ n ≀ 105). n lines follow, in the i-th of which there are three integers ai, bi and ci (1 ≀ ai, bi, ci ≀ 109)Β β€” the lengths of edges of the i-th stone. Note, that two stones may have exactly the same sizes, but they still will be considered two different stones.
1,600
In the first line print k (1 ≀ k ≀ 2) the number of stones which Zahar has chosen. In the second line print k distinct integers from 1 to nΒ β€” the numbers of stones which Zahar needs to choose. Consider that stones are numbered from 1 to n in the order as they are given in the input data. You can print the stones in arbitrary order. If there are several answers print any of them.
standard output
PASSED
ce89179843b614f5a6a3a62cda010b08
train_004.jsonl
1477922700
Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere. Zahar has n stones which are rectangular parallelepipeds. The edges sizes of the i-th of them are ai, bi and ci. He can take no more than two stones and present them to Kostya. If Zahar takes two stones, he should glue them together on one of the faces in order to get a new piece of rectangular parallelepiped of marble. Thus, it is possible to glue a pair of stones together if and only if two faces on which they are glued together match as rectangles. In such gluing it is allowed to rotate and flip the stones in any way. Help Zahar choose such a present so that Kostya can carve a sphere of the maximum possible volume and present it to Zahar.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Map; import java.util.Map.Entry; import java.util.Scanner; import java.util.HashMap; import java.util.TreeSet; /** * Built using CHelper plug-in * Actual solution is at the top * * @author zodiacLeo */ 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); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(); int result = 0; int index1 = -1; int index2 = -1; HashMap<Pair, TreeSet<IndexPair>> map = new HashMap<>(); for (int i = 0; i < n; i++) { int a = in.nextInt(); int b = in.nextInt(); int c = in.nextInt(); if (result < min3(a, b, c)) { result = min3(a, b, c); index1 = i + 1; } Pair one = new Pair(a, b); IndexPair two = new IndexPair(c, i + 1); put(map, one, two); one = new Pair(Math.min(b, c), Math.max(b, c)); two = new IndexPair(a, i + 1); put(map, one, two); one = new Pair(Math.min(a, c), Math.max(a, c)); two = new IndexPair(b, i + 1); put(map, one, two); } for (Map.Entry<Pair, TreeSet<IndexPair>> entry : map.entrySet()) { Pair ab = entry.getKey(); TreeSet<IndexPair> c = entry.getValue(); if (c.size() > 1) { IndexPair max1 = c.pollLast(); IndexPair max2 = c.pollLast(); if (result < min3(ab.a, ab.b, max1.value + max2.value)) { index1 = max1.index; index2 = max2.index; result = min3(ab.a, ab.b, max1.value + max2.value); } } } if (index2 == -1) { out.println(1); out.println(index1); } else { out.println(2); out.println(index1 + " " + index2); } } public Integer min3(int a, int b, int c) { return Math.min(a, Math.min(b, c)); } public void put(HashMap<Pair, TreeSet<IndexPair>> map, Pair key, IndexPair value) { if (map.containsKey(key)) { map.get(key).add(value); } else { TreeSet<IndexPair> list = new TreeSet<IndexPair>(); list.add(value); map.put(key, list); } } class Pair { int a; int b; public Pair(int a, int b) { this.a = Math.min(a, b); this.b = Math.max(a, b); } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair pair = (Pair) o; if (a != pair.a) return false; return b == pair.b; } public int hashCode() { int result = a; result = 31 * result + b; return result; } } class IndexPair implements Comparable<IndexPair> { int value; int index; public IndexPair(int value, int index) { this.value = value; this.index = index; } public int compareTo(IndexPair that) { if (this.value != that.value) { return Integer.compare(this.value, that.value); } return Integer.compare(this.index, that.index); } } } }
Java
["6\n5 5 5\n3 2 4\n1 4 1\n2 1 3\n3 2 4\n3 3 4", "7\n10 7 8\n5 10 3\n4 2 6\n5 5 5\n10 2 8\n4 2 1\n7 7 7"]
3 seconds
["1\n1", "2\n1 5"]
NoteIn the first example we can connect the pairs of stones: 2 and 4, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 2 and 5, the size of the parallelepiped: 3 × 2 × 8 or 6 × 2 × 4 or 3 × 4 × 4, the radius of the inscribed sphere 1, or 1, or 1.5 respectively. 2 and 6, the size of the parallelepiped: 3 × 5 × 4, the radius of the inscribed sphere 1.5 4 and 5, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 5 and 6, the size of the parallelepiped: 3 × 4 × 5, the radius of the inscribed sphere 1.5 Or take only one stone: 1 the size of the parallelepiped: 5 × 5 × 5, the radius of the inscribed sphere 2.5 2 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 3 the size of the parallelepiped: 1 × 4 × 1, the radius of the inscribed sphere 0.5 4 the size of the parallelepiped: 2 × 1 × 3, the radius of the inscribed sphere 0.5 5 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 6 the size of the parallelepiped: 3 × 3 × 4, the radius of the inscribed sphere 1.5 It is most profitable to take only the first stone.
Java 8
standard input
[ "data structures", "hashing" ]
ef82292a6591de818ddda9f426208291
The first line contains the integer n (1 ≀ n ≀ 105). n lines follow, in the i-th of which there are three integers ai, bi and ci (1 ≀ ai, bi, ci ≀ 109)Β β€” the lengths of edges of the i-th stone. Note, that two stones may have exactly the same sizes, but they still will be considered two different stones.
1,600
In the first line print k (1 ≀ k ≀ 2) the number of stones which Zahar has chosen. In the second line print k distinct integers from 1 to nΒ β€” the numbers of stones which Zahar needs to choose. Consider that stones are numbered from 1 to n in the order as they are given in the input data. You can print the stones in arbitrary order. If there are several answers print any of them.
standard output
PASSED
02b693060401dc36ac39cf7f7a29df61
train_004.jsonl
1477922700
Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere. Zahar has n stones which are rectangular parallelepipeds. The edges sizes of the i-th of them are ai, bi and ci. He can take no more than two stones and present them to Kostya. If Zahar takes two stones, he should glue them together on one of the faces in order to get a new piece of rectangular parallelepiped of marble. Thus, it is possible to glue a pair of stones together if and only if two faces on which they are glued together match as rectangles. In such gluing it is allowed to rotate and flip the stones in any way. Help Zahar choose such a present so that Kostya can carve a sphere of the maximum possible volume and present it to Zahar.
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.PriorityQueue; import java.util.InputMismatchException; import java.util.HashMap; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.io.InputStream; /** * Built using CHelper plug-in Actual solution is at the top * * @author MaxHeap */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); DKostyaTheSculptor solver = new DKostyaTheSculptor(); solver.solve(1, in, out); out.close(); } static class DKostyaTheSculptor { int n; int[][] arr; Map<IntPair, PriorityQueue<DKostyaTheSculptor.Rectangle>> map = new HashMap<>(200); public void solve(int testNumber, InputReader in, PrintWriter out) { n = in.nextInt(); arr = new int[n][3]; double best = 0; List<Integer> ans = new ArrayList<>(2); for (int i = 0; i < n; i++) { arr[i][0] = in.nextInt(); arr[i][1] = in.nextInt(); arr[i][2] = in.nextInt(); double min = Math.min( arr[i][0], Math.min( arr[i][1], arr[i][2] ) ); if (min * 2 > best) { best = min * 2; ans.clear(); ans.add(i); } Arrays.sort(arr[i]); } for (int i = 1; i < 8; ++i) { int f = -1, s = -1; for (int j = 0; j <= 4; ++j) { if (Bits.isSet(i, j)) { if (f == -1) { f = j; } else if (s == -1) { s = j; } else { s = -1; break; } } } if (f != -1 && s != -1) { map.clear(); for (int j = 0; j < n; ++j) { IntPair was = Factories.makeIntPair(arr[j][f], arr[j][s]); int other = other(f, s); PriorityQueue<DKostyaTheSculptor.Rectangle> pairs = map.get(was); DKostyaTheSculptor.Rectangle cur = new DKostyaTheSculptor.Rectangle(j, arr[j][other], arr[j][f], arr[j][s]); if (pairs == null) { pairs = new PriorityQueue<>(); pairs.add(cur); } else if (pairs.size() < 2) { pairs.add(cur); } else { DKostyaTheSculptor.Rectangle peek = pairs.peek(); if (peek.minimum() < cur.minimum()) { pairs.poll(); pairs.add(cur); } } map.put(was, pairs); } for (Entry<IntPair, PriorityQueue<DKostyaTheSculptor.Rectangle>> pairs : map.entrySet()) { PriorityQueue<DKostyaTheSculptor.Rectangle> value = pairs.getValue(); int size = value.size(); if (size == 2) { DKostyaTheSculptor.Rectangle first = value.poll(); DKostyaTheSculptor.Rectangle second = value.poll(); if (first.b != second.b) { throw new RuntimeException(); } if (first.c != second.c) { throw new RuntimeException(); } long possible = Math.min( first.a + second.a, Math.min( first.b, first.c ) ); if (possible * 2 > best) { best = possible * 2; ans.clear(); ans.add(first.index); ans.add(second.index); } } } } } out.println(ans.size()); for (int i = 0; i < ans.size(); ++i) { if (i > 0) { out.print(" "); } out.print(ans.get(i) + 1); } } int other(int i, int j) { for (int k = 0; k < 3; ++k) { if (k != i && k != j) { return k; } } throw new RuntimeException(); } static class Rectangle implements Comparable<DKostyaTheSculptor.Rectangle> { int a; int b; int c; int index; public Rectangle(int index, int a, int b, int c) { this.index = index; this.a = a; this.b = b; this.c = c; } public int minimum() { return Math.min( a, Math.min( c, b ) ); } public int compareTo(DKostyaTheSculptor.Rectangle o) { return Integer.compare(minimum(), o.minimum()); } } } static class InputReader implements FastIO { private InputStream stream; private static final int DEFAULT_BUFFER_SIZE = 1 << 16; private static final int EOF = -1; private byte[] buf = new byte[DEFAULT_BUFFER_SIZE]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (this.numChars == EOF) { throw new UnknownError(); } else { if (this.curChar >= this.numChars) { this.curChar = 0; try { this.numChars = this.stream.read(this.buf); } catch (IOException ex) { throw new InputMismatchException(); } if (this.numChars <= 0) { return EOF; } } return this.buf[this.curChar++]; } } public int nextInt() { int c; for (c = this.read(); isSpaceChar(c); c = this.read()) { } byte sgn = 1; if (c == 45) { sgn = -1; c = this.read(); } int res = 0; while (c >= 48 && c <= 57) { res *= 10; res += c - 48; c = this.read(); if (isSpaceChar(c)) { return res * sgn; } } throw new InputMismatchException(); } public static boolean isSpaceChar(int c) { return c == 32 || c == 10 || c == 13 || c == 9 || c == EOF; } } static final class Factories { private Factories() { } public static IntPair makeIntPair(int first, int second) { return new IntPair(first, second); } } static interface FastIO { } static final class Bits { private Bits() { throw new UnsupportedOperationException("cannot instantiate Bits class"); } public static boolean isSet(int mask, int i) { return (mask & (1 << i)) > 0; } } static class IntPair implements Comparable<IntPair> { public int first; public int second; public IntPair() { first = second = 0; } public IntPair(int first, int second) { this.first = first; this.second = second; } public int compareTo(IntPair a) { if (first == a.first) { return Integer.compare(second, a.second); } return Integer.compare(first, a.first); } public String toString() { return "<" + first + ", " + second + ">"; } public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } IntPair a = (IntPair) o; if (first != a.first) { return false; } return second == a.second; } public int hashCode() { int result = first; result = 31 * result + second; return result; } } }
Java
["6\n5 5 5\n3 2 4\n1 4 1\n2 1 3\n3 2 4\n3 3 4", "7\n10 7 8\n5 10 3\n4 2 6\n5 5 5\n10 2 8\n4 2 1\n7 7 7"]
3 seconds
["1\n1", "2\n1 5"]
NoteIn the first example we can connect the pairs of stones: 2 and 4, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 2 and 5, the size of the parallelepiped: 3 × 2 × 8 or 6 × 2 × 4 or 3 × 4 × 4, the radius of the inscribed sphere 1, or 1, or 1.5 respectively. 2 and 6, the size of the parallelepiped: 3 × 5 × 4, the radius of the inscribed sphere 1.5 4 and 5, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 5 and 6, the size of the parallelepiped: 3 × 4 × 5, the radius of the inscribed sphere 1.5 Or take only one stone: 1 the size of the parallelepiped: 5 × 5 × 5, the radius of the inscribed sphere 2.5 2 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 3 the size of the parallelepiped: 1 × 4 × 1, the radius of the inscribed sphere 0.5 4 the size of the parallelepiped: 2 × 1 × 3, the radius of the inscribed sphere 0.5 5 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 6 the size of the parallelepiped: 3 × 3 × 4, the radius of the inscribed sphere 1.5 It is most profitable to take only the first stone.
Java 8
standard input
[ "data structures", "hashing" ]
ef82292a6591de818ddda9f426208291
The first line contains the integer n (1 ≀ n ≀ 105). n lines follow, in the i-th of which there are three integers ai, bi and ci (1 ≀ ai, bi, ci ≀ 109)Β β€” the lengths of edges of the i-th stone. Note, that two stones may have exactly the same sizes, but they still will be considered two different stones.
1,600
In the first line print k (1 ≀ k ≀ 2) the number of stones which Zahar has chosen. In the second line print k distinct integers from 1 to nΒ β€” the numbers of stones which Zahar needs to choose. Consider that stones are numbered from 1 to n in the order as they are given in the input data. You can print the stones in arbitrary order. If there are several answers print any of them.
standard output
PASSED
ed3eb65edc23396dbaf59b08f54c22bf
train_004.jsonl
1477922700
Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere. Zahar has n stones which are rectangular parallelepipeds. The edges sizes of the i-th of them are ai, bi and ci. He can take no more than two stones and present them to Kostya. If Zahar takes two stones, he should glue them together on one of the faces in order to get a new piece of rectangular parallelepiped of marble. Thus, it is possible to glue a pair of stones together if and only if two faces on which they are glued together match as rectangles. In such gluing it is allowed to rotate and flip the stones in any way. Help Zahar choose such a present so that Kostya can carve a sphere of the maximum possible volume and present it to Zahar.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.SortedSet; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; /** * # * @author pttrung */ public class D_Round_378_Div2 { public static long MOD = 1000000007; public static void main(String[] args) throws FileNotFoundException { // PrintWriter out = new PrintWriter(new FileOutputStream(new File( // "output.txt"))); PrintWriter out = new PrintWriter(System.out); Scanner in = new Scanner(); int n = in.nextInt(); long[][] data = new long[n][3]; for (int i = 0; i < n; i++) { for (int j = 0; j < 3; j++) { data[i][j] = in.nextInt(); } } HashMap<Point, Integer> map = new HashMap(); long max = 0; int x = -1, y = -1; for (int i = 0; i < n; i++) { for (int j = 0; j < 3; j++) { for (int k = j + 1; k < 3; k++) { Point p; if (data[i][j] <= data[i][k]) { p = new Point(data[i][j], data[i][k]); } else { p = new Point(data[i][k], data[i][j]); } if (map.containsKey(p)) { int v = map.get(p); if (v == i) { continue; } long other = left(data[v], p.x, p.y); long tmp = min(p.x, p.y, data[i][3 - j - k] + other); if (max < tmp) { max = tmp; x = i; y = v; } if (other < data[i][3 - j - k]) { map.put(p, i); } } else { long tmp = min(p.x, p.y, data[i][3 - j - k]); if (max < tmp) { max = tmp; x = i; y = -1; } map.put(p, i); } } } } out.println((y != -1 ? 2 : 1)); out.println((x + 1) + (y != -1 ? " " + (y + 1) : "")); out.close(); } static long min(long a, long b, long c) { return Long.min(a, Long.min(b, c)); } static long left(long[] data, long a, long b) { for (int i = 0; i < 3; i++) { for (int j = i + 1; j < 3; j++) { if (data[i] == a && data[j] == b) { return data[3 - i - j]; } else if (data[i] == b && data[j] == a) { return data[3 - i - j]; } } } return -1; } public static int[] KMP(String val) { int i = 0; int j = -1; int[] result = new int[val.length() + 1]; result[0] = -1; while (i < val.length()) { while (j >= 0 && val.charAt(j) != val.charAt(i)) { j = result[j]; } j++; i++; result[i] = j; } return result; } public static boolean nextPer(int[] data) { int i = data.length - 1; while (i > 0 && data[i] < data[i - 1]) { i--; } if (i == 0) { return false; } int j = data.length - 1; while (data[j] < data[i - 1]) { j--; } int temp = data[i - 1]; data[i - 1] = data[j]; data[j] = temp; Arrays.sort(data, i, data.length); return true; } public static int digit(long n) { int result = 0; while (n > 0) { n /= 10; result++; } return result; } public static double dist(long a, long b, long x, long y) { double val = (b - a) * (b - a) + (x - y) * (x - y); val = Math.sqrt(val); double other = x * x + a * a; other = Math.sqrt(other); return val + other; } public static class Point implements Comparable<Point> { long x, y; public Point(long start, long end) { this.x = start; this.y = end; } @Override public String toString() { return "Point{" + "x=" + x + ", y=" + y + '}'; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Point other = (Point) obj; if (this.x != other.x) { return false; } if (this.y != other.y) { return false; } return true; } @Override public int hashCode() { int hash = 7; hash = 89 * hash + (int) (this.x ^ (this.x >>> 32)); hash = 89 * hash + (int) (this.y ^ (this.y >>> 32)); return hash; } @Override public int compareTo(Point o) { return Long.compare(x, o.x); } } public static class FT { long[] data; FT(int n) { data = new long[n]; } public void update(int index, long value) { while (index < data.length) { data[index] += value; index += (index & (-index)); } } public long get(int index) { long result = 0; while (index > 0) { result += data[index]; index -= (index & (-index)); } return result; } } public static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } public static long pow(long a, long b, long MOD) { if (b == 0) { return 1; } if (b == 1) { return a; } long val = pow(a, b / 2, MOD); if (b % 2 == 0) { return val * val % MOD; } else { return val * (val * a % MOD) % MOD; } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() throws FileNotFoundException { // System.setOut(new PrintStream(new BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt")))); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
Java
["6\n5 5 5\n3 2 4\n1 4 1\n2 1 3\n3 2 4\n3 3 4", "7\n10 7 8\n5 10 3\n4 2 6\n5 5 5\n10 2 8\n4 2 1\n7 7 7"]
3 seconds
["1\n1", "2\n1 5"]
NoteIn the first example we can connect the pairs of stones: 2 and 4, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 2 and 5, the size of the parallelepiped: 3 × 2 × 8 or 6 × 2 × 4 or 3 × 4 × 4, the radius of the inscribed sphere 1, or 1, or 1.5 respectively. 2 and 6, the size of the parallelepiped: 3 × 5 × 4, the radius of the inscribed sphere 1.5 4 and 5, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 5 and 6, the size of the parallelepiped: 3 × 4 × 5, the radius of the inscribed sphere 1.5 Or take only one stone: 1 the size of the parallelepiped: 5 × 5 × 5, the radius of the inscribed sphere 2.5 2 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 3 the size of the parallelepiped: 1 × 4 × 1, the radius of the inscribed sphere 0.5 4 the size of the parallelepiped: 2 × 1 × 3, the radius of the inscribed sphere 0.5 5 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 6 the size of the parallelepiped: 3 × 3 × 4, the radius of the inscribed sphere 1.5 It is most profitable to take only the first stone.
Java 8
standard input
[ "data structures", "hashing" ]
ef82292a6591de818ddda9f426208291
The first line contains the integer n (1 ≀ n ≀ 105). n lines follow, in the i-th of which there are three integers ai, bi and ci (1 ≀ ai, bi, ci ≀ 109)Β β€” the lengths of edges of the i-th stone. Note, that two stones may have exactly the same sizes, but they still will be considered two different stones.
1,600
In the first line print k (1 ≀ k ≀ 2) the number of stones which Zahar has chosen. In the second line print k distinct integers from 1 to nΒ β€” the numbers of stones which Zahar needs to choose. Consider that stones are numbered from 1 to n in the order as they are given in the input data. You can print the stones in arbitrary order. If there are several answers print any of them.
standard output
PASSED
2353ccb91ddd41bd3bcdbef61873c546
train_004.jsonl
1477922700
Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere. Zahar has n stones which are rectangular parallelepipeds. The edges sizes of the i-th of them are ai, bi and ci. He can take no more than two stones and present them to Kostya. If Zahar takes two stones, he should glue them together on one of the faces in order to get a new piece of rectangular parallelepiped of marble. Thus, it is possible to glue a pair of stones together if and only if two faces on which they are glued together match as rectangles. In such gluing it is allowed to rotate and flip the stones in any way. Help Zahar choose such a present so that Kostya can carve a sphere of the maximum possible volume and present it to Zahar.
256 megabytes
import java.util.*; import java.io.*; public class KostyatheSculptor { /************************ SOLUTION STARTS HERE ***********************/ static class Dimension { int a , b; Dimension(int a , int b){ this.a = a; this.b = b; } @Override public boolean equals(Object obj) { Dimension that = (Dimension)obj; return a == that.a && b == that.b; } @Override public int hashCode() { return Objects.hash(a,b); } @Override public String toString() { return "ln " + a + " bt " + b; } } static class Pair implements Comparable<Pair> { int index , h; Pair(int i , int k) { index = i; h = k; } @Override public int compareTo(Pair o) { return Integer.compare(h, o.h); } @Override public String toString() { return "index " + index + " ht " + h; } @Override public boolean equals(Object obj) { Pair p = (Pair)obj; return index == p.index && h == p.h; } @Override public int hashCode() { return Objects.hash(index , h); } } static void addToMap(int l , int b , int h , int idx , HashMap<Dimension , HashSet<Pair>> map) { Dimension d = new Dimension(l, b); HashSet<Pair> arl = map.getOrDefault(d, new HashSet<>()); arl.add(new Pair(idx, h)); map.put(d, arl); } private static void solve(FastScanner s1, PrintWriter out){ int N = s1.nextInt(); HashMap<Dimension , HashSet<Pair>> map = new HashMap<>(); for(int i=1;i<=N;i++) { int arr[] = s1.nextIntArray(3); Arrays.sort(arr); addToMap(arr[0], arr[1], arr[2], i, map); addToMap(arr[1], arr[2], arr[0], i, map); addToMap(arr[0], arr[2], arr[1], i, map); } long maxDiameter = 0; int pos1 = -1 , pos2 = -1; for(Map.Entry<Dimension, HashSet<Pair>> e : map.entrySet()) { ArrayList<Pair> arl = new ArrayList<>(e.getValue()); Dimension d = e.getKey(); Collections.sort(arl,Collections.reverseOrder()); // out.println(d + " ==> " + arl); long h1 = arl.get(0).h; long h2 = arl.size() > 1 ? arl.get(1).h : 0; long diam = Math.min(Math.min(d.a,d.b),h1 + h2); if(diam > maxDiameter) { maxDiameter = diam; pos1 = arl.get(0).index; pos2 = arl.size() > 1 ? arl.get(1).index : -1; } } out.println(pos2 != -1 ? 2 : 1); out.println(pos1 + " " + ((pos2 != -1) ? pos2 : "")); } /************************ SOLUTION ENDS HERE ************************/ /************************ TEMPLATE STARTS HERE *********************/ public static void main(String []args) throws IOException { FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), false); solve(in, out); in.close(); out.close(); } static class FastScanner{ BufferedReader reader; StringTokenizer st; FastScanner(InputStream stream){reader=new BufferedReader(new InputStreamReader(stream));st=null;} String next() {while(st == null || !st.hasMoreTokens()){try{String line = reader.readLine();if(line == null){return null;} st = new StringTokenizer(line);}catch (Exception e){throw new RuntimeException();}}return st.nextToken();} String nextLine() {String s=null;try{s=reader.readLine();}catch(IOException e){e.printStackTrace();}return s;} int nextInt() {return Integer.parseInt(next());} long nextLong() {return Long.parseLong(next());} double nextDouble(){return Double.parseDouble(next());} char nextChar() {return next().charAt(0);} int[] nextIntArray(int n) {int[] arr= new int[n]; int i=0;while(i<n){arr[i++]=nextInt();} return arr;} long[] nextLongArray(int n) {long[]arr= new long[n]; int i=0;while(i<n){arr[i++]=nextLong();} return arr;} int[] nextIntArrayOneBased(int n) {int[] arr= new int[n+1]; int i=1;while(i<=n){arr[i++]=nextInt();} return arr;} long[] nextLongArrayOneBased(int n){long[]arr= new long[n+1];int i=1;while(i<=n){arr[i++]=nextLong();}return arr;} void close(){try{reader.close();}catch(IOException e){e.printStackTrace();}} } /************************ TEMPLATE ENDS HERE ************************/ }
Java
["6\n5 5 5\n3 2 4\n1 4 1\n2 1 3\n3 2 4\n3 3 4", "7\n10 7 8\n5 10 3\n4 2 6\n5 5 5\n10 2 8\n4 2 1\n7 7 7"]
3 seconds
["1\n1", "2\n1 5"]
NoteIn the first example we can connect the pairs of stones: 2 and 4, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 2 and 5, the size of the parallelepiped: 3 × 2 × 8 or 6 × 2 × 4 or 3 × 4 × 4, the radius of the inscribed sphere 1, or 1, or 1.5 respectively. 2 and 6, the size of the parallelepiped: 3 × 5 × 4, the radius of the inscribed sphere 1.5 4 and 5, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 5 and 6, the size of the parallelepiped: 3 × 4 × 5, the radius of the inscribed sphere 1.5 Or take only one stone: 1 the size of the parallelepiped: 5 × 5 × 5, the radius of the inscribed sphere 2.5 2 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 3 the size of the parallelepiped: 1 × 4 × 1, the radius of the inscribed sphere 0.5 4 the size of the parallelepiped: 2 × 1 × 3, the radius of the inscribed sphere 0.5 5 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 6 the size of the parallelepiped: 3 × 3 × 4, the radius of the inscribed sphere 1.5 It is most profitable to take only the first stone.
Java 8
standard input
[ "data structures", "hashing" ]
ef82292a6591de818ddda9f426208291
The first line contains the integer n (1 ≀ n ≀ 105). n lines follow, in the i-th of which there are three integers ai, bi and ci (1 ≀ ai, bi, ci ≀ 109)Β β€” the lengths of edges of the i-th stone. Note, that two stones may have exactly the same sizes, but they still will be considered two different stones.
1,600
In the first line print k (1 ≀ k ≀ 2) the number of stones which Zahar has chosen. In the second line print k distinct integers from 1 to nΒ β€” the numbers of stones which Zahar needs to choose. Consider that stones are numbered from 1 to n in the order as they are given in the input data. You can print the stones in arbitrary order. If there are several answers print any of them.
standard output
PASSED
4f462103aa3bfc1f70262d8f4142e99a
train_004.jsonl
1477922700
Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere. Zahar has n stones which are rectangular parallelepipeds. The edges sizes of the i-th of them are ai, bi and ci. He can take no more than two stones and present them to Kostya. If Zahar takes two stones, he should glue them together on one of the faces in order to get a new piece of rectangular parallelepiped of marble. Thus, it is possible to glue a pair of stones together if and only if two faces on which they are glued together match as rectangles. In such gluing it is allowed to rotate and flip the stones in any way. Help Zahar choose such a present so that Kostya can carve a sphere of the maximum possible volume and present it to Zahar.
256 megabytes
import java.io.*; import java.util.*; public class Main { static class Stone implements Comparable<Stone>{ int a,b,c,position; Stone(int a,int b,int c,int d){ this.a=a; this.b=b; this.c=c; this.position=d; } Stone(){ } @Override public int compareTo(Stone s) { if(this.c<s.c) return -1; else if(this.c>s.c) return 1; else if(this.b<s.b) return -1; else if(this.b>s.b) return 1; else if(this.a<s.a) return -1; else if(this.a>s.a) return 1; else return 0; } //ι•Ώζ–Ήδ½“ζŽ’εΊηš„εŸΊη‘€ } public static void main(String[] args) { Scanner sc=new Scanner(System.in); while(sc.hasNext()){ int n=sc.nextInt(); int max=-1; int index=0; Stone []s=new Stone[n]; int flag=0; int jg1=0; int jg2=0; int shu[]=new int[3]; for(int i=0;i<n;i++){ shu[0]=sc.nextInt(); shu[1]=sc.nextInt(); shu[2]=sc.nextInt(); Arrays.sort(shu); //ε°†ι•Ώζ–Ήδ½“ηš„δΈ‰ζ‘θΎΉζŒ‰δ»Žε°εˆ°ε€§ζŽ’εΊ s[i]=new Stone(shu[0],shu[1],shu[2],i+1); if(max<shu[0]){ index=i+1; max=shu[0]; } //ιεŽ†ζ‰Ύεͺ用一δΈͺι•Ώζ–Ήδ½“ζ—Άζœ€ηŸ­ηš„εŠεΎ„ } Arrays.sort(s); for(int i=0;i<n-1;i++){ if(s[i].b==s[i+1].b&&s[i].c==s[i+1].c){ //当一δΈͺι•Ώζ–Ήδ½“θƒ½εˆεΉΆ int[] bj=new int [3]; bj[0]=s[i].a+s[i+1].a; bj[1]=s[i].b; bj[2]=s[i].c; Arrays.sort(bj); //ζ‰Ύε‡ΊεˆεΉΆεŽηš„ζœ€ηŸ­θΎΉι•Ώ if(bj[0]>max){ flag=1; max=bj[0]; jg1=s[i].position; jg2=s[i+1].position; } } } if(flag==1){ System.out.println(2); System.out.println(jg1+" "+jg2); } else { System.out.println(1); System.out.println(index); } } } }
Java
["6\n5 5 5\n3 2 4\n1 4 1\n2 1 3\n3 2 4\n3 3 4", "7\n10 7 8\n5 10 3\n4 2 6\n5 5 5\n10 2 8\n4 2 1\n7 7 7"]
3 seconds
["1\n1", "2\n1 5"]
NoteIn the first example we can connect the pairs of stones: 2 and 4, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 2 and 5, the size of the parallelepiped: 3 × 2 × 8 or 6 × 2 × 4 or 3 × 4 × 4, the radius of the inscribed sphere 1, or 1, or 1.5 respectively. 2 and 6, the size of the parallelepiped: 3 × 5 × 4, the radius of the inscribed sphere 1.5 4 and 5, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 5 and 6, the size of the parallelepiped: 3 × 4 × 5, the radius of the inscribed sphere 1.5 Or take only one stone: 1 the size of the parallelepiped: 5 × 5 × 5, the radius of the inscribed sphere 2.5 2 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 3 the size of the parallelepiped: 1 × 4 × 1, the radius of the inscribed sphere 0.5 4 the size of the parallelepiped: 2 × 1 × 3, the radius of the inscribed sphere 0.5 5 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 6 the size of the parallelepiped: 3 × 3 × 4, the radius of the inscribed sphere 1.5 It is most profitable to take only the first stone.
Java 8
standard input
[ "data structures", "hashing" ]
ef82292a6591de818ddda9f426208291
The first line contains the integer n (1 ≀ n ≀ 105). n lines follow, in the i-th of which there are three integers ai, bi and ci (1 ≀ ai, bi, ci ≀ 109)Β β€” the lengths of edges of the i-th stone. Note, that two stones may have exactly the same sizes, but they still will be considered two different stones.
1,600
In the first line print k (1 ≀ k ≀ 2) the number of stones which Zahar has chosen. In the second line print k distinct integers from 1 to nΒ β€” the numbers of stones which Zahar needs to choose. Consider that stones are numbered from 1 to n in the order as they are given in the input data. You can print the stones in arbitrary order. If there are several answers print any of them.
standard output
PASSED
0efe10ec91ca94fd17deb3be44d559f7
train_004.jsonl
1477922700
Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere. Zahar has n stones which are rectangular parallelepipeds. The edges sizes of the i-th of them are ai, bi and ci. He can take no more than two stones and present them to Kostya. If Zahar takes two stones, he should glue them together on one of the faces in order to get a new piece of rectangular parallelepiped of marble. Thus, it is possible to glue a pair of stones together if and only if two faces on which they are glued together match as rectangles. In such gluing it is allowed to rotate and flip the stones in any way. Help Zahar choose such a present so that Kostya can carve a sphere of the maximum possible volume and present it to Zahar.
256 megabytes
import java.io.*; import java.util.*; import java.text.*; import java.lang.*; import java.math.*; public class Main{ static ArrayList a[]=new ArrayList[200001]; static pair f(pair p[]) { double ans=0.0; pair got=new pair(0L,-1L,-1L,0); for(int i=1;i<p.length;i++) { double val1=( Math.min(p[i].z,Math.min(p[i].x, p[i].y)))/(2.0); if(val1>ans) { ans=val1; got=new pair(p[i].id,-1L,-1L,0); } if(p[i].x.equals(p[i-1].x) && p[i].y.equals(p[i-1].y) && !p[i].id.equals(p[i-1].id)) { double val=( Math.min(p[i].z+p[i-1].z,Math.min(p[i].x, p[i].y)))/(2.0); if(val>ans) { ans=val; got=new pair(p[i].id,p[i-1].id,0L,0); } } } return got; } public void solve () { InputReader in = new InputReader(System.in); PrintWriter pw = new PrintWriter(System.out); int n=in.nextInt(); pair p[]=new pair [6*n]; int j=0; for(int i=0;j<n;i+=6,j++) { p[i]=new pair(in.nextLong(),in.nextLong(),in.nextLong(),j); p[i+1]=new pair(p[i].x,p[i].z,p[i].y,j); p[i+2]=new pair(p[i].y,p[i].z,p[i].x,j); p[i+3]=new pair(p[i].y,p[i].x,p[i].z,j); p[i+4]=new pair(p[i].z,p[i].x,p[i].y,j); p[i+5]=new pair(p[i].z,p[i].y,p[i].x,j); } Arrays.sort(p,new Comparator<pair>() { public int compare(pair p1,pair p2) { if(p1.x>p2.x) return 1; if(p1.x<p2.x) return -1; if(p1.y>p2.y) return 1; if(p1.y<p2.y) return -1; if(p1.z>p2.z) return 1; if(p1.z<p2.z) return -1; return 0; } }); pair ans=f(p); if(ans.y!=-1) { pw.println(2); pw.println((ans.x+1)+" "+(ans.y+1)); } else { pw.println(1); pw.println((ans.x+1)); } pw.flush(); pw.close(); } public static void main(String[] args) throws Exception { new Thread(null,new Runnable() { public void run() { new Main().solve(); } },"1",1<<23).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 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 int GCD(int a,int b) { if(b==0) return a; else return GCD(b,a%b); } static class pair implements Comparable<pair> { Long x,y,z; Integer id; pair(long x,long y,long z,int id) { this.x=x; this.y=y; this.z=z; this.id=id; } 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 == x && p.y == y ; } return false; } public int hashCode() { return new Long(x).hashCode()*31 + new Long(y).hashCode(); } } }
Java
["6\n5 5 5\n3 2 4\n1 4 1\n2 1 3\n3 2 4\n3 3 4", "7\n10 7 8\n5 10 3\n4 2 6\n5 5 5\n10 2 8\n4 2 1\n7 7 7"]
3 seconds
["1\n1", "2\n1 5"]
NoteIn the first example we can connect the pairs of stones: 2 and 4, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 2 and 5, the size of the parallelepiped: 3 × 2 × 8 or 6 × 2 × 4 or 3 × 4 × 4, the radius of the inscribed sphere 1, or 1, or 1.5 respectively. 2 and 6, the size of the parallelepiped: 3 × 5 × 4, the radius of the inscribed sphere 1.5 4 and 5, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 5 and 6, the size of the parallelepiped: 3 × 4 × 5, the radius of the inscribed sphere 1.5 Or take only one stone: 1 the size of the parallelepiped: 5 × 5 × 5, the radius of the inscribed sphere 2.5 2 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 3 the size of the parallelepiped: 1 × 4 × 1, the radius of the inscribed sphere 0.5 4 the size of the parallelepiped: 2 × 1 × 3, the radius of the inscribed sphere 0.5 5 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 6 the size of the parallelepiped: 3 × 3 × 4, the radius of the inscribed sphere 1.5 It is most profitable to take only the first stone.
Java 8
standard input
[ "data structures", "hashing" ]
ef82292a6591de818ddda9f426208291
The first line contains the integer n (1 ≀ n ≀ 105). n lines follow, in the i-th of which there are three integers ai, bi and ci (1 ≀ ai, bi, ci ≀ 109)Β β€” the lengths of edges of the i-th stone. Note, that two stones may have exactly the same sizes, but they still will be considered two different stones.
1,600
In the first line print k (1 ≀ k ≀ 2) the number of stones which Zahar has chosen. In the second line print k distinct integers from 1 to nΒ β€” the numbers of stones which Zahar needs to choose. Consider that stones are numbered from 1 to n in the order as they are given in the input data. You can print the stones in arbitrary order. If there are several answers print any of them.
standard output
PASSED
bb7eaf6a85572fabafb0382186f1bba2
train_004.jsonl
1477922700
Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere. Zahar has n stones which are rectangular parallelepipeds. The edges sizes of the i-th of them are ai, bi and ci. He can take no more than two stones and present them to Kostya. If Zahar takes two stones, he should glue them together on one of the faces in order to get a new piece of rectangular parallelepiped of marble. Thus, it is possible to glue a pair of stones together if and only if two faces on which they are glued together match as rectangles. In such gluing it is allowed to rotate and flip the stones in any way. Help Zahar choose such a present so that Kostya can carve a sphere of the maximum possible volume and present it to Zahar.
256 megabytes
/* Did I say something wrong? Did you hear what I was thinking? Did I talk way too long when I told you all my feelings that night? Is it you? Is it me? Did you find somebody better? Someone who isn't me, 'cause I know that I was never your type Never really your type Overthinking's got me drinking Messing with my head, whoa Tell me what you hate about me Whatever it is, I'm sorry Yeah, yeah, yeah, yeah, yeah, yeah I know I can be dramatic But everybody said we had it Yeah, yeah, yeah, yeah, yeah, yeah I'm coming to terms with a broken heart I guess that sometimes good things fall apart When you said it was real, guess I really did believe you Did you fake how you feel when we parked down by the river that night? That night? That night when we fogged up the windows in your best friend's car 'Cause we couldn't leave the windows down in December Whoa Tell me what you hate about me Whatever it is, I'm sorry Yeah, yeah, yeah, yeah, yeah, yeah I know I can be dramatic But everybody said we had it Yeah, yeah, yeah, yeah, yeah, yeah I'm coming to terms with a broken heart I guess that sometimes good things fall apart Overthinking's got me drinking Messing with my head, oh Tell me what you hate about me (about me) Whatever it is, I'm sorry (oh, I'm sorry) Yeah, yeah, yeah (oh, I'm sorry), yeah, yeah, yeah I know I can be dramatic (I know I can be) Everybody said we had it Yeah, yeah, yeah, yeah, yeah, yeah I'm coming to terms with a broken heart I guess that sometimes good things fall apart */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; import java.util.*; import java.math.*; public class Main { static ArrayList<Integer> a[]; static boolean vis[]=new boolean[2000009]; static int time=0; static int ans[]=new int[2000009]; static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { FastReader sc=new FastReader(); StringBuilder sb=new StringBuilder(); //hashmap implementations ***yuckkk*** int n = sc.nextInt(); int max = 0, a= -1, b= -1; HashMap<String, Pair> map = new HashMap<>(); int arr[] = new int[3]; for(int i=0; i<n; i++) { int temp = Integer.MAX_VALUE; for(int j=0; j<3; j++) { arr[j] = sc.nextInt(); } Arrays.sort(arr); temp=arr[0]; if(temp > max) { max = temp; a = i; b= -1; } int val = arr[2], pos = i; if(map.containsKey(arr[0]+" "+arr[1])) { Pair pp = map.get(arr[0] +" "+arr[1]); temp = Math.min(pp.x + arr[2], Math.min(arr[0], arr[1])); if(pos != pp.y && temp > max) { max = temp; a = i; b = pp.y; } if(pp.x > val) { val = pp.x; pos = pp.y; } } map.put(arr[0]+" "+arr[1], new Pair(val,pos)); val = arr[0]; pos = i; if(map.containsKey(arr[1]+" "+arr[2])) { Pair pp = map.get(arr[1] +" "+arr[2]); temp = Math.min(pp.x + arr[0], Math.min(arr[1], arr[2])); if(pos != pp.y && temp > max) { max = temp; a = i; b = pp.y; } if(pp.x > val) { val = pp.x; pos = pp.y; } } map.put(arr[1]+" "+arr[2], new Pair(val,pos)); val = arr[1]; pos = i; if(map.containsKey(arr[0]+" "+arr[2])) { Pair pp = map.get(arr[0] +" "+arr[2]); temp = Math.min(pp.x + arr[1], Math.min(arr[0], arr[2])); if(pos != pp.y && temp > max) { max = temp; a = i; b = pp.y; } if(pp.x > val) { val = pp.x; pos = pp.y; } } map.put(arr[0]+" "+arr[2], new Pair(val,pos)); } if(b==-1) { System.out.println(1); System.out.println(a+1); } else { System.out.println(2); System.out.println((a+1)+" "+(b+1)); } } } class Pair implements Comparable{ int x,y; Pair(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(Object o) { Pair pp = (Pair)o; if(pp.x == x) return 0; else if (x>pp.x) return 1; else return -1; } }
Java
["6\n5 5 5\n3 2 4\n1 4 1\n2 1 3\n3 2 4\n3 3 4", "7\n10 7 8\n5 10 3\n4 2 6\n5 5 5\n10 2 8\n4 2 1\n7 7 7"]
3 seconds
["1\n1", "2\n1 5"]
NoteIn the first example we can connect the pairs of stones: 2 and 4, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 2 and 5, the size of the parallelepiped: 3 × 2 × 8 or 6 × 2 × 4 or 3 × 4 × 4, the radius of the inscribed sphere 1, or 1, or 1.5 respectively. 2 and 6, the size of the parallelepiped: 3 × 5 × 4, the radius of the inscribed sphere 1.5 4 and 5, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 5 and 6, the size of the parallelepiped: 3 × 4 × 5, the radius of the inscribed sphere 1.5 Or take only one stone: 1 the size of the parallelepiped: 5 × 5 × 5, the radius of the inscribed sphere 2.5 2 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 3 the size of the parallelepiped: 1 × 4 × 1, the radius of the inscribed sphere 0.5 4 the size of the parallelepiped: 2 × 1 × 3, the radius of the inscribed sphere 0.5 5 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 6 the size of the parallelepiped: 3 × 3 × 4, the radius of the inscribed sphere 1.5 It is most profitable to take only the first stone.
Java 8
standard input
[ "data structures", "hashing" ]
ef82292a6591de818ddda9f426208291
The first line contains the integer n (1 ≀ n ≀ 105). n lines follow, in the i-th of which there are three integers ai, bi and ci (1 ≀ ai, bi, ci ≀ 109)Β β€” the lengths of edges of the i-th stone. Note, that two stones may have exactly the same sizes, but they still will be considered two different stones.
1,600
In the first line print k (1 ≀ k ≀ 2) the number of stones which Zahar has chosen. In the second line print k distinct integers from 1 to nΒ β€” the numbers of stones which Zahar needs to choose. Consider that stones are numbered from 1 to n in the order as they are given in the input data. You can print the stones in arbitrary order. If there are several answers print any of them.
standard output
PASSED
16dd60c241571e90b19f74ac25c46fec
train_004.jsonl
1477922700
Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere. Zahar has n stones which are rectangular parallelepipeds. The edges sizes of the i-th of them are ai, bi and ci. He can take no more than two stones and present them to Kostya. If Zahar takes two stones, he should glue them together on one of the faces in order to get a new piece of rectangular parallelepiped of marble. Thus, it is possible to glue a pair of stones together if and only if two faces on which they are glued together match as rectangles. In such gluing it is allowed to rotate and flip the stones in any way. Help Zahar choose such a present so that Kostya can carve a sphere of the maximum possible volume and present it to Zahar.
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.Comparator; import java.util.Optional; public class _733D { public static class Box { public final int a; public final int b; public final int c; public final int index; public Box(int x, int y, int z, int index, boolean sortDir) { if (x > y) { int t = x; x = y; y = t; } if (y > z) { int t = y; y = z; z = t; } if (x > y) { int t = x; x = y; y = t; } if (sortDir) { a = x; b = y; c = z; } else { a = z; b = y; c = x; } this.index = index; } @Override public String toString() { return String.format("[%d %d %d]", a, b, c); } } public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(reader.readLine()); ArrayList<Box> boxes1 = new ArrayList<>(n); ArrayList<Box> boxes2 = new ArrayList<>(n); for (int i = 0; i < n; i++) { String s[] = reader.readLine().split("\\s+"); int x = Integer.parseInt(s[0]); int y = Integer.parseInt(s[1]); int z = Integer.parseInt(s[2]); boxes1.add(new Box(x, y, z, i + 1, true)); boxes2.add(new Box(x, y, z, i + 1, false)); } Comparator<Box> comparator = new Comparator<Box>() { @Override public int compare(Box o1, Box o2) { if (o1.a == o2.a) { if (o1.b == o2.b) { return o1.c - o2.c; } else return o1.b - o2.b; } else return o1.a - o2.a; } }; Collections.sort(boxes1, comparator); Collections.sort(boxes2, comparator); int maxP = 0; int bestP1 = 0, bestP2 = 0; ArrayList<Box> span = new ArrayList<>(); for (int i = 0; i < n; i++) { Box box = boxes1.get(i); if (span.isEmpty()) span.add(box); else if (span.get(0).a == box.a && span.get(0).b == box.b) span.add(box); else { if (span.size() >= 2) { Box p1 = span.get(span.size() - 1); Box p2 = span.get(span.size() - 2); int r = Math.min(p1.a, Math.min(p1.b, p1.c + p2.c)); if (r > maxP) { maxP = r; bestP1 = p1.index; bestP2 = p2.index; } } span.clear(); span.add(box); } } if (span.size() >= 2) { Box p1 = span.get(span.size() - 1); Box p2 = span.get(span.size() - 2); int r = Math.min(p1.a, Math.min(p1.b, p1.c + p2.c)); if (r > maxP) { maxP = r; bestP1 = p1.index; bestP2 = p2.index; } } span.clear(); for (int i = 0; i < n; i++) { Box box = boxes2.get(i); if (span.isEmpty()) span.add(box); else if (span.get(0).a == box.a && span.get(0).b == box.b) span.add(box); else { if (span.size() >= 2) { Box p1 = span.get(span.size() - 1); Box p2 = span.get(span.size() - 2); int r = Math.min(p1.a, Math.min(p1.b, p1.c + p2.c)); if (r > maxP) { maxP = r; bestP1 = p1.index; bestP2 = p2.index; } } span.clear(); span.add(box); } } if (span.size() >= 2) { Box p1 = span.get(span.size() - 1); Box p2 = span.get(span.size() - 2); int r = Math.min(p1.a, Math.min(p1.b, p1.c + p2.c)); if (r > maxP) { maxP = r; bestP1 = p1.index; bestP2 = p2.index; } } int maxS = boxes1.get(boxes1.size() - 1).a; if (maxS > maxP) { System.out.println(1); System.out.println(boxes1.get(boxes1.size() - 1).index); } else { System.out.println(2); System.out.println(bestP1); System.out.println(bestP2); } } }
Java
["6\n5 5 5\n3 2 4\n1 4 1\n2 1 3\n3 2 4\n3 3 4", "7\n10 7 8\n5 10 3\n4 2 6\n5 5 5\n10 2 8\n4 2 1\n7 7 7"]
3 seconds
["1\n1", "2\n1 5"]
NoteIn the first example we can connect the pairs of stones: 2 and 4, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 2 and 5, the size of the parallelepiped: 3 × 2 × 8 or 6 × 2 × 4 or 3 × 4 × 4, the radius of the inscribed sphere 1, or 1, or 1.5 respectively. 2 and 6, the size of the parallelepiped: 3 × 5 × 4, the radius of the inscribed sphere 1.5 4 and 5, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 5 and 6, the size of the parallelepiped: 3 × 4 × 5, the radius of the inscribed sphere 1.5 Or take only one stone: 1 the size of the parallelepiped: 5 × 5 × 5, the radius of the inscribed sphere 2.5 2 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 3 the size of the parallelepiped: 1 × 4 × 1, the radius of the inscribed sphere 0.5 4 the size of the parallelepiped: 2 × 1 × 3, the radius of the inscribed sphere 0.5 5 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 6 the size of the parallelepiped: 3 × 3 × 4, the radius of the inscribed sphere 1.5 It is most profitable to take only the first stone.
Java 8
standard input
[ "data structures", "hashing" ]
ef82292a6591de818ddda9f426208291
The first line contains the integer n (1 ≀ n ≀ 105). n lines follow, in the i-th of which there are three integers ai, bi and ci (1 ≀ ai, bi, ci ≀ 109)Β β€” the lengths of edges of the i-th stone. Note, that two stones may have exactly the same sizes, but they still will be considered two different stones.
1,600
In the first line print k (1 ≀ k ≀ 2) the number of stones which Zahar has chosen. In the second line print k distinct integers from 1 to nΒ β€” the numbers of stones which Zahar needs to choose. Consider that stones are numbered from 1 to n in the order as they are given in the input data. You can print the stones in arbitrary order. If there are several answers print any of them.
standard output
PASSED
6ca72a2993918ee768c859bd5e719cf9
train_004.jsonl
1477922700
Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere. Zahar has n stones which are rectangular parallelepipeds. The edges sizes of the i-th of them are ai, bi and ci. He can take no more than two stones and present them to Kostya. If Zahar takes two stones, he should glue them together on one of the faces in order to get a new piece of rectangular parallelepiped of marble. Thus, it is possible to glue a pair of stones together if and only if two faces on which they are glued together match as rectangles. In such gluing it is allowed to rotate and flip the stones in any way. Help Zahar choose such a present so that Kostya can carve a sphere of the maximum possible volume and present it to Zahar.
256 megabytes
import java.awt.Point; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.StringTokenizer; public class D378 { public static void main(String[] args) { MyScanner scan = new MyScanner(); int N = scan.nextInt(); HashMap<Point, Point> map = new HashMap<>(); ArrayList<Integer> idx = new ArrayList<>(); long bestR= 0; for(int i=0;i<N;i++){ int[] dim = new int[3]; for(int j=0;j<3;j++){ dim[j]=scan.nextInt(); } for(int j=0;j<3;j++){ for(int k=j+1;k<3;k++){ for(int x = 0;x<3;x++){ if(x==j||x==k)continue; Point p = new Point(Math.min(dim[j], dim[k]),Math.max(dim[j], dim[k])); if(!map.containsKey(p)){ map.put(p, new Point(dim[x],i)); long r = Math.min(dim[j], Math.min(dim[k], dim[x])); if(r>bestR){ bestR=r; idx = new ArrayList<>(); idx.add(i); } }else{ long r = Math.min(dim[j], Math.min(dim[k], dim[x]+map.get(p).x)); if(r>bestR){ bestR=r; idx = new ArrayList<>(); idx.add(i); idx.add(map.get(p).y); } if(map.get(p).x<dim[x]){ map.put(p, new Point(dim[x],i)); } } } } } } System.out.println(idx.size()); for(int i : idx){ System.out.print((i+1)+" "); }System.out.println(); } private 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());} } }
Java
["6\n5 5 5\n3 2 4\n1 4 1\n2 1 3\n3 2 4\n3 3 4", "7\n10 7 8\n5 10 3\n4 2 6\n5 5 5\n10 2 8\n4 2 1\n7 7 7"]
3 seconds
["1\n1", "2\n1 5"]
NoteIn the first example we can connect the pairs of stones: 2 and 4, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 2 and 5, the size of the parallelepiped: 3 × 2 × 8 or 6 × 2 × 4 or 3 × 4 × 4, the radius of the inscribed sphere 1, or 1, or 1.5 respectively. 2 and 6, the size of the parallelepiped: 3 × 5 × 4, the radius of the inscribed sphere 1.5 4 and 5, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 5 and 6, the size of the parallelepiped: 3 × 4 × 5, the radius of the inscribed sphere 1.5 Or take only one stone: 1 the size of the parallelepiped: 5 × 5 × 5, the radius of the inscribed sphere 2.5 2 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 3 the size of the parallelepiped: 1 × 4 × 1, the radius of the inscribed sphere 0.5 4 the size of the parallelepiped: 2 × 1 × 3, the radius of the inscribed sphere 0.5 5 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 6 the size of the parallelepiped: 3 × 3 × 4, the radius of the inscribed sphere 1.5 It is most profitable to take only the first stone.
Java 8
standard input
[ "data structures", "hashing" ]
ef82292a6591de818ddda9f426208291
The first line contains the integer n (1 ≀ n ≀ 105). n lines follow, in the i-th of which there are three integers ai, bi and ci (1 ≀ ai, bi, ci ≀ 109)Β β€” the lengths of edges of the i-th stone. Note, that two stones may have exactly the same sizes, but they still will be considered two different stones.
1,600
In the first line print k (1 ≀ k ≀ 2) the number of stones which Zahar has chosen. In the second line print k distinct integers from 1 to nΒ β€” the numbers of stones which Zahar needs to choose. Consider that stones are numbered from 1 to n in the order as they are given in the input data. You can print the stones in arbitrary order. If there are several answers print any of them.
standard output
PASSED
67348ebc24f5534ffa3a1428cc6040bf
train_004.jsonl
1477922700
Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere. Zahar has n stones which are rectangular parallelepipeds. The edges sizes of the i-th of them are ai, bi and ci. He can take no more than two stones and present them to Kostya. If Zahar takes two stones, he should glue them together on one of the faces in order to get a new piece of rectangular parallelepiped of marble. Thus, it is possible to glue a pair of stones together if and only if two faces on which they are glued together match as rectangles. In such gluing it is allowed to rotate and flip the stones in any way. Help Zahar choose such a present so that Kostya can carve a sphere of the maximum possible volume and present it to Zahar.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class D { private static int n; private static ArrayList<Stone> stones; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; n = Integer.parseInt(br.readLine()); stones = new ArrayList<>(); for (int i = 0; i < n; i++) { st = new StringTokenizer(br.readLine()); stones.add(new Stone(i + 1, Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()))); } Pair max = new Pair(); Pair temp = getMaxSphere(new int[]{ 0, 1, 2 }); if (max.max < temp.max) { max = temp; } temp = getMaxSphere(new int[]{ 0, 2, 1 }); if (max.max < temp.max) { max = temp; } temp = getMaxSphere(new int[]{ 1, 2, 0 }); if (max.max < temp.max) { max = temp; } max.print(); } private static Pair getMaxSphere(final int[] pos) { Collections.sort(stones, new Comparator<Stone>() { @Override public int compare(Stone o1, Stone o2) { for (int i = 0; i < 3; i++) { int diff = o1.sides[pos[i]] - o2.sides[pos[i]]; if (diff != 0) { return diff; } } return 0; } }); return getMax(pos[0], pos[1], pos[2]); } private static class Stone { int pos; int[] sides; Stone(int pos, int a, int b, int c) { this.pos = pos; this.sides = new int[]{ a, b, c }; Arrays.sort(sides); } } private static class Pair { int n = -1; int max = -1; int stone1 = -1; int stone2 = -1; public void set(int n, int max, int stone1, int stone2) { this.n = n; this.max = max; this.stone1 = stone1; this.stone2 = stone2; } public void reset(int stone1) { n = 1; max = -1; this.stone1 = stone1; stone2 = -1; } private void print() { System.out.println(n); System.out.print(stone1); if (stone2 != -1) { System.out.print(" " + stone2); } System.out.println(); } } private static Pair getMax(int a, int b, int c) { int max = 0; Pair maxPair = new Pair(); Pair currentPair = new Pair(); int side1 = -1; int side2 = -1; int side3 = -1; int tempMin = -1; Stone tempStone = null; for (int i = 0; i < n; i++) { tempStone = stones.get(i); if (side1 == tempStone.sides[a] && side2 == tempStone.sides[b]) { side3 += tempStone.sides[c]; tempMin = side1 < side2 ? side1 : side2; tempMin = tempMin < side3 ? tempMin : side3; if (max < tempMin) { max = tempMin; maxPair.set(2, max, currentPair.stone1, tempStone.pos); } side3 = tempStone.sides[c]; } else { side1 = tempStone.sides[a]; side2 = tempStone.sides[b]; side3 = tempStone.sides[c]; } currentPair.reset(tempStone.pos); tempMin = Integer.MAX_VALUE; for (int j = 0; j < 3; j++) { tempMin = Math.min(tempMin, tempStone.sides[j]); } if (max < tempMin) { max = tempMin; maxPair.set(1, max, tempStone.pos, -1); } } return maxPair; } }
Java
["6\n5 5 5\n3 2 4\n1 4 1\n2 1 3\n3 2 4\n3 3 4", "7\n10 7 8\n5 10 3\n4 2 6\n5 5 5\n10 2 8\n4 2 1\n7 7 7"]
3 seconds
["1\n1", "2\n1 5"]
NoteIn the first example we can connect the pairs of stones: 2 and 4, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 2 and 5, the size of the parallelepiped: 3 × 2 × 8 or 6 × 2 × 4 or 3 × 4 × 4, the radius of the inscribed sphere 1, or 1, or 1.5 respectively. 2 and 6, the size of the parallelepiped: 3 × 5 × 4, the radius of the inscribed sphere 1.5 4 and 5, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 5 and 6, the size of the parallelepiped: 3 × 4 × 5, the radius of the inscribed sphere 1.5 Or take only one stone: 1 the size of the parallelepiped: 5 × 5 × 5, the radius of the inscribed sphere 2.5 2 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 3 the size of the parallelepiped: 1 × 4 × 1, the radius of the inscribed sphere 0.5 4 the size of the parallelepiped: 2 × 1 × 3, the radius of the inscribed sphere 0.5 5 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 6 the size of the parallelepiped: 3 × 3 × 4, the radius of the inscribed sphere 1.5 It is most profitable to take only the first stone.
Java 8
standard input
[ "data structures", "hashing" ]
ef82292a6591de818ddda9f426208291
The first line contains the integer n (1 ≀ n ≀ 105). n lines follow, in the i-th of which there are three integers ai, bi and ci (1 ≀ ai, bi, ci ≀ 109)Β β€” the lengths of edges of the i-th stone. Note, that two stones may have exactly the same sizes, but they still will be considered two different stones.
1,600
In the first line print k (1 ≀ k ≀ 2) the number of stones which Zahar has chosen. In the second line print k distinct integers from 1 to nΒ β€” the numbers of stones which Zahar needs to choose. Consider that stones are numbered from 1 to n in the order as they are given in the input data. You can print the stones in arbitrary order. If there are several answers print any of them.
standard output
PASSED
a71997cfec7e65e42c2e57c3fca21d50
train_004.jsonl
1477922700
Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere. Zahar has n stones which are rectangular parallelepipeds. The edges sizes of the i-th of them are ai, bi and ci. He can take no more than two stones and present them to Kostya. If Zahar takes two stones, he should glue them together on one of the faces in order to get a new piece of rectangular parallelepiped of marble. Thus, it is possible to glue a pair of stones together if and only if two faces on which they are glued together match as rectangles. In such gluing it is allowed to rotate and flip the stones in any way. Help Zahar choose such a present so that Kostya can carve a sphere of the maximum possible volume and present it to Zahar.
256 megabytes
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import java.util.Objects; import java.util.StringTokenizer; 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); Task solver = new Task(); solver.solve(in, out); out.close(); } } class Task { private long n; private long m; private long k; private long x; private long s; public void solve(Scanner in, PrintWriter out) { int n = in.nextInt(); Triple[] a = new Triple[n]; for (int i = 0; i < n; i++) { a[i] = new Triple(in.nextInt(), in.nextInt(), in.nextInt(), i); } Arrays.sort(a); int max = 0; int r1 = -1; int r2 = -1; for (int i = 0; i < n; i++) { if (a[i].e[2] > max) { max = a[i].e[2]; r1 = a[i].i; r2 = -1; } if (i != n - 1 && Objects.equals(a[i].e[0], a[i + 1].e[0]) && Objects.equals(a[i].e[1], a[i + 1].e[1])) { int q = Math.min(a[i].e[1], a[i + 1].e[2] + a[i].e[2]); if (q > max) { max = q; r1 = a[i].i; r2 = a[i + 1].i; } } } if (r2 == -1) { System.out.println(1); System.out.println(r1 + 1); } else { System.out.println(2); System.out.println(r1 + 1 + " " + (r2 + 1)); } } } class Triple implements Comparable<Triple> { public Integer[] e = new Integer[3]; public int i; public Triple(int a, int b, int c, int i) { this.i = i; e[0] = a; e[1] = b; e[2] = c; Arrays.sort(e, (o1, o2) -> o2 - o1); } @Override public int compareTo(Triple o) { if (!Objects.equals(e[0], o.e[0])) { return e[0] - o.e[0]; } if (!Objects.equals(e[1], o.e[1])) { return e[1] - o.e[1]; } if (!Objects.equals(e[2], o.e[2])) { return e[2] - o.e[2]; } return 0; } } class Scanner { BufferedReader in; StringTokenizer tok; public Scanner(InputStream in) { this.in = new BufferedReader(new InputStreamReader(in)); tok = new StringTokenizer(""); } private String tryReadNextLine() { try { return in.readLine(); } catch (Exception e) { throw new InputMismatchException(); } } public String nextToken() { while (!tok.hasMoreTokens()) { tok = new StringTokenizer(next()); } return tok.nextToken(); } public String next() { String newLine = tryReadNextLine(); if (newLine == null) throw new InputMismatchException(); return newLine; } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } }
Java
["6\n5 5 5\n3 2 4\n1 4 1\n2 1 3\n3 2 4\n3 3 4", "7\n10 7 8\n5 10 3\n4 2 6\n5 5 5\n10 2 8\n4 2 1\n7 7 7"]
3 seconds
["1\n1", "2\n1 5"]
NoteIn the first example we can connect the pairs of stones: 2 and 4, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 2 and 5, the size of the parallelepiped: 3 × 2 × 8 or 6 × 2 × 4 or 3 × 4 × 4, the radius of the inscribed sphere 1, or 1, or 1.5 respectively. 2 and 6, the size of the parallelepiped: 3 × 5 × 4, the radius of the inscribed sphere 1.5 4 and 5, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 5 and 6, the size of the parallelepiped: 3 × 4 × 5, the radius of the inscribed sphere 1.5 Or take only one stone: 1 the size of the parallelepiped: 5 × 5 × 5, the radius of the inscribed sphere 2.5 2 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 3 the size of the parallelepiped: 1 × 4 × 1, the radius of the inscribed sphere 0.5 4 the size of the parallelepiped: 2 × 1 × 3, the radius of the inscribed sphere 0.5 5 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 6 the size of the parallelepiped: 3 × 3 × 4, the radius of the inscribed sphere 1.5 It is most profitable to take only the first stone.
Java 8
standard input
[ "data structures", "hashing" ]
ef82292a6591de818ddda9f426208291
The first line contains the integer n (1 ≀ n ≀ 105). n lines follow, in the i-th of which there are three integers ai, bi and ci (1 ≀ ai, bi, ci ≀ 109)Β β€” the lengths of edges of the i-th stone. Note, that two stones may have exactly the same sizes, but they still will be considered two different stones.
1,600
In the first line print k (1 ≀ k ≀ 2) the number of stones which Zahar has chosen. In the second line print k distinct integers from 1 to nΒ β€” the numbers of stones which Zahar needs to choose. Consider that stones are numbered from 1 to n in the order as they are given in the input data. You can print the stones in arbitrary order. If there are several answers print any of them.
standard output
PASSED
9ab2d4a482cd28d5ed884737545193aa
train_004.jsonl
1477922700
Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere. Zahar has n stones which are rectangular parallelepipeds. The edges sizes of the i-th of them are ai, bi and ci. He can take no more than two stones and present them to Kostya. If Zahar takes two stones, he should glue them together on one of the faces in order to get a new piece of rectangular parallelepiped of marble. Thus, it is possible to glue a pair of stones together if and only if two faces on which they are glued together match as rectangles. In such gluing it is allowed to rotate and flip the stones in any way. Help Zahar choose such a present so that Kostya can carve a sphere of the maximum possible volume and present it to Zahar.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.HashMap; import java.util.InputMismatchException; import java.util.Map; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { static class Pair { int x; int y; Pair(int x, int y) { this.x = x; this.y = y; } } public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); int max = 0; int[][] a = new int[n][3]; Pair res = new Pair(-1, -1); Map<Long, Pair> map = new HashMap<>(); for (int i = 0; i < n; i++) for (int j = 0; j < 3; j++) a[i][j] = in.readInt(); for (int i = 0; i < n; i++) { for (int j = 0; j < 3; j++) { for (int k = 0; k < 3; k++) { if (j == k) continue; long key = get(a[i][j], a[i][k]); if (map.get(key) != null) { int id = 3 - j - k; Pair tmp = map.get(key); int now = Math.min(tmp.x + a[i][id], Math.min(a[i][j], a[i][k])); if (now > max) { max = now; res = new Pair(i + 1, tmp.y + 1); } } } } for (int j = 0; j < 3; j++) { for (int k = 0; k < 3; k++) { if (j == k) continue; int id = 3 - j - k; long key = get(a[i][j], a[i][k]); if (map.get(key) == null) { map.put(key, new Pair(a[i][id], i)); } else if (map.get(key).x < a[i][id]) { map.put(key, new Pair(a[i][id], i)); } } } } for (int i = 0; i < n; i++) { int min = Math.min(a[i][0], Math.min(a[i][1], a[i][2])); if (min > max) { max = min; res = new Pair(i + 1, -1); } } if (res.y == -1) { out.printLine(1); out.printLine(res.x); } else { out.printLine(2); out.printLine(res.x + " " + res.y); } } private long get(int x, int y) { return 1000000010L * x + y; } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } 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 printLine(int i) { writer.println(i); } } }
Java
["6\n5 5 5\n3 2 4\n1 4 1\n2 1 3\n3 2 4\n3 3 4", "7\n10 7 8\n5 10 3\n4 2 6\n5 5 5\n10 2 8\n4 2 1\n7 7 7"]
3 seconds
["1\n1", "2\n1 5"]
NoteIn the first example we can connect the pairs of stones: 2 and 4, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 2 and 5, the size of the parallelepiped: 3 × 2 × 8 or 6 × 2 × 4 or 3 × 4 × 4, the radius of the inscribed sphere 1, or 1, or 1.5 respectively. 2 and 6, the size of the parallelepiped: 3 × 5 × 4, the radius of the inscribed sphere 1.5 4 and 5, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 5 and 6, the size of the parallelepiped: 3 × 4 × 5, the radius of the inscribed sphere 1.5 Or take only one stone: 1 the size of the parallelepiped: 5 × 5 × 5, the radius of the inscribed sphere 2.5 2 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 3 the size of the parallelepiped: 1 × 4 × 1, the radius of the inscribed sphere 0.5 4 the size of the parallelepiped: 2 × 1 × 3, the radius of the inscribed sphere 0.5 5 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 6 the size of the parallelepiped: 3 × 3 × 4, the radius of the inscribed sphere 1.5 It is most profitable to take only the first stone.
Java 8
standard input
[ "data structures", "hashing" ]
ef82292a6591de818ddda9f426208291
The first line contains the integer n (1 ≀ n ≀ 105). n lines follow, in the i-th of which there are three integers ai, bi and ci (1 ≀ ai, bi, ci ≀ 109)Β β€” the lengths of edges of the i-th stone. Note, that two stones may have exactly the same sizes, but they still will be considered two different stones.
1,600
In the first line print k (1 ≀ k ≀ 2) the number of stones which Zahar has chosen. In the second line print k distinct integers from 1 to nΒ β€” the numbers of stones which Zahar needs to choose. Consider that stones are numbered from 1 to n in the order as they are given in the input data. You can print the stones in arbitrary order. If there are several answers print any of them.
standard output
PASSED
3ca3591d990fe0890c85c10afc3de8cc
train_004.jsonl
1477922700
Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere. Zahar has n stones which are rectangular parallelepipeds. The edges sizes of the i-th of them are ai, bi and ci. He can take no more than two stones and present them to Kostya. If Zahar takes two stones, he should glue them together on one of the faces in order to get a new piece of rectangular parallelepiped of marble. Thus, it is possible to glue a pair of stones together if and only if two faces on which they are glued together match as rectangles. In such gluing it is allowed to rotate and flip the stones in any way. Help Zahar choose such a present so that Kostya can carve a sphere of the maximum possible volume and present it to Zahar.
256 megabytes
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.Comparator; import java.util.InputMismatchException; public class D { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(); int[][] cs = new int[n][]; for(int i = 0;i < n;i++){ cs[i] = na(3); } int maxr = 0; int arg1 = -1, arg2 = -1; for(int i = 0;i < n;i++){ int r = Math.min(Math.min(cs[i][0], cs[i][1]), cs[i][2]); if(r > maxr){ maxr = r; arg1 = i; } } int[][] rs = new int[3*n][]; int p = 0; for(int i = 0;i < n;i++){ int[] c = cs[i]; rs[p++] = new int[]{Math.min(c[0], c[1]), Math.max(c[0], c[1]), c[2], i}; rs[p++] = new int[]{Math.min(c[1], c[2]), Math.max(c[1], c[2]), c[0], i}; rs[p++] = new int[]{Math.min(c[0], c[2]), Math.max(c[0], c[2]), c[1], i}; } Arrays.sort(rs, new Comparator<int[]>() { public int compare(int[] a, int[] b) { if(a[0] != b[0])return a[0] - b[0]; return a[1] - b[1]; } }); for(int i = 0;i < 3*n;){ int j = i; while(j < 3*n && rs[i][0] == rs[j][0] && rs[i][1] == rs[j][1])j++; int best1 = 0, who1 = -1; int best2 = 0, who2 = -1; for(int k = i;k < j;k++){ if(rs[k][2] > best1){ best2 = best1; who2 = who1; best1 = rs[k][2]; who1 = rs[k][3]; }else if(rs[k][2] == best1 && who1 == rs[k][3]){ continue; }else if(rs[k][2] > best2){ best2 = rs[k][2]; who2 = rs[k][3]; } } assert who1 != who2; if(who2 != -1){ int r = Math.min(Math.min(rs[i][0], rs[i][1]), best1+best2); if(r > maxr){ maxr = r; arg1 = who1; arg2 = who2; } } i = j; } if(arg2 == -1){ out.println(1); out.println(arg1 + 1); }else{ out.println(2); if(arg1 > arg2){ int u = arg1; arg1 = arg2; arg2 = u; } out.print(arg1 + 1); out.print(" "); out.println(arg2 + 1); } } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new D().run(); } private byte[] inbuf = new byte[1024]; private int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["6\n5 5 5\n3 2 4\n1 4 1\n2 1 3\n3 2 4\n3 3 4", "7\n10 7 8\n5 10 3\n4 2 6\n5 5 5\n10 2 8\n4 2 1\n7 7 7"]
3 seconds
["1\n1", "2\n1 5"]
NoteIn the first example we can connect the pairs of stones: 2 and 4, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 2 and 5, the size of the parallelepiped: 3 × 2 × 8 or 6 × 2 × 4 or 3 × 4 × 4, the radius of the inscribed sphere 1, or 1, or 1.5 respectively. 2 and 6, the size of the parallelepiped: 3 × 5 × 4, the radius of the inscribed sphere 1.5 4 and 5, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 5 and 6, the size of the parallelepiped: 3 × 4 × 5, the radius of the inscribed sphere 1.5 Or take only one stone: 1 the size of the parallelepiped: 5 × 5 × 5, the radius of the inscribed sphere 2.5 2 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 3 the size of the parallelepiped: 1 × 4 × 1, the radius of the inscribed sphere 0.5 4 the size of the parallelepiped: 2 × 1 × 3, the radius of the inscribed sphere 0.5 5 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 6 the size of the parallelepiped: 3 × 3 × 4, the radius of the inscribed sphere 1.5 It is most profitable to take only the first stone.
Java 8
standard input
[ "data structures", "hashing" ]
ef82292a6591de818ddda9f426208291
The first line contains the integer n (1 ≀ n ≀ 105). n lines follow, in the i-th of which there are three integers ai, bi and ci (1 ≀ ai, bi, ci ≀ 109)Β β€” the lengths of edges of the i-th stone. Note, that two stones may have exactly the same sizes, but they still will be considered two different stones.
1,600
In the first line print k (1 ≀ k ≀ 2) the number of stones which Zahar has chosen. In the second line print k distinct integers from 1 to nΒ β€” the numbers of stones which Zahar needs to choose. Consider that stones are numbered from 1 to n in the order as they are given in the input data. You can print the stones in arbitrary order. If there are several answers print any of them.
standard output
PASSED
01ed3dc3c367544af26a1cf8bfba6f53
train_004.jsonl
1477922700
Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere. Zahar has n stones which are rectangular parallelepipeds. The edges sizes of the i-th of them are ai, bi and ci. He can take no more than two stones and present them to Kostya. If Zahar takes two stones, he should glue them together on one of the faces in order to get a new piece of rectangular parallelepiped of marble. Thus, it is possible to glue a pair of stones together if and only if two faces on which they are glued together match as rectangles. In such gluing it is allowed to rotate and flip the stones in any way. Help Zahar choose such a present so that Kostya can carve a sphere of the maximum possible volume and present it to Zahar.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; import java.util.concurrent.ArrayBlockingQueue; public class D { String line; StringTokenizer inputParser; BufferedReader is; FileInputStream fstream; DataInputStream in; void openInput(String file) { if(file==null)is = new BufferedReader(new InputStreamReader(System.in));//stdin else { try{ fstream = new FileInputStream(file); in = new DataInputStream(fstream); is = new BufferedReader(new InputStreamReader(in)); }catch(Exception e) { System.err.println(e); } } } void readNextLine() { try { line = is.readLine(); if(line!=null)inputParser = new StringTokenizer(line, " "); //System.err.println("Input: " + line); } catch (IOException e) { System.err.println("Unexpected IO ERROR: " + e); } } int NextInt() { String n = inputParser.nextToken(); int val = Integer.parseInt(n); //System.out.println("I read this number: " + val); return val; } double NextDouble() { String n = inputParser.nextToken(); double val = Double.parseDouble(n); //System.out.println("I read this number: " + val); return val; } long NextLong() { String n = inputParser.nextToken(); long val = Long.parseLong(n); return val; } String NextString() { String n = inputParser.nextToken(); return n; } void closeInput() { try { is.close(); } catch (IOException e) { System.err.println("Unexpected IO ERROR: " + e); } } public static void main(String [] argv) { String filePath=null; if(argv.length>0)filePath=argv[0]; new D(filePath); } public D(String inputFile) { openInput(inputFile); //readNextLine(); int T=1;//NextInt(); StringBuilder sb = new StringBuilder(); for(int t=1; t<=T; t++) { readNextLine(); int N=NextInt(); int[] x = new int[3]; HashMap <Long, Integer> m = new HashMap<Long, Integer>(); HashMap <Long, Integer> id = new HashMap<Long, Integer>(); long best = 0; String ret = ""; for(int i=0; i<N; i++) { readNextLine(); x[0]=NextInt(); x[1]=NextInt(); x[2]=NextInt(); Arrays.sort(x); long code = x[2]*111111111L+x[1]; if(x[0]>best) { best = x[0]; ret = "1\n"+(i+1); } if(m.containsKey(code)) { int now = m.get(code); int nowid=id.get(code); if(x[0]>now) { m.put(code, x[0]); id.put(code, i+1); } now+=x[0]; if(now>x[1])now=x[1]; if(now>best) { best = now; ret = "2\n"+(i+1)+" "+nowid; } } else { m.put(code, x[0]); id.put(code, i+1); } } sb.append(ret); } System.out.print(sb); closeInput(); } }
Java
["6\n5 5 5\n3 2 4\n1 4 1\n2 1 3\n3 2 4\n3 3 4", "7\n10 7 8\n5 10 3\n4 2 6\n5 5 5\n10 2 8\n4 2 1\n7 7 7"]
3 seconds
["1\n1", "2\n1 5"]
NoteIn the first example we can connect the pairs of stones: 2 and 4, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 2 and 5, the size of the parallelepiped: 3 × 2 × 8 or 6 × 2 × 4 or 3 × 4 × 4, the radius of the inscribed sphere 1, or 1, or 1.5 respectively. 2 and 6, the size of the parallelepiped: 3 × 5 × 4, the radius of the inscribed sphere 1.5 4 and 5, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 5 and 6, the size of the parallelepiped: 3 × 4 × 5, the radius of the inscribed sphere 1.5 Or take only one stone: 1 the size of the parallelepiped: 5 × 5 × 5, the radius of the inscribed sphere 2.5 2 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 3 the size of the parallelepiped: 1 × 4 × 1, the radius of the inscribed sphere 0.5 4 the size of the parallelepiped: 2 × 1 × 3, the radius of the inscribed sphere 0.5 5 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 6 the size of the parallelepiped: 3 × 3 × 4, the radius of the inscribed sphere 1.5 It is most profitable to take only the first stone.
Java 8
standard input
[ "data structures", "hashing" ]
ef82292a6591de818ddda9f426208291
The first line contains the integer n (1 ≀ n ≀ 105). n lines follow, in the i-th of which there are three integers ai, bi and ci (1 ≀ ai, bi, ci ≀ 109)Β β€” the lengths of edges of the i-th stone. Note, that two stones may have exactly the same sizes, but they still will be considered two different stones.
1,600
In the first line print k (1 ≀ k ≀ 2) the number of stones which Zahar has chosen. In the second line print k distinct integers from 1 to nΒ β€” the numbers of stones which Zahar needs to choose. Consider that stones are numbered from 1 to n in the order as they are given in the input data. You can print the stones in arbitrary order. If there are several answers print any of them.
standard output
PASSED
a5b456fd5e9627e5a3bd1f6d2735e6aa
train_004.jsonl
1477922700
Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere. Zahar has n stones which are rectangular parallelepipeds. The edges sizes of the i-th of them are ai, bi and ci. He can take no more than two stones and present them to Kostya. If Zahar takes two stones, he should glue them together on one of the faces in order to get a new piece of rectangular parallelepiped of marble. Thus, it is possible to glue a pair of stones together if and only if two faces on which they are glued together match as rectangles. In such gluing it is allowed to rotate and flip the stones in any way. Help Zahar choose such a present so that Kostya can carve a sphere of the maximum possible volume and present it to Zahar.
256 megabytes
//lol import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import java.util.*; import java.io.*; import java.math.*; public class D { public static long CONS = 1000000007L; public static void main(String hi[]) throws Exception { BufferedReader infile = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(infile.readLine()); int N = Integer.parseInt(st.nextToken()); Triple[] arr = new Triple[N]; for(int i=0; i < N; i++) { st = new StringTokenizer(infile.readLine()); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); int c = Integer.parseInt(st.nextToken()); arr[i] = new Triple(a, b, c); } id1 = new HashMap<Long, Integer>(); id2 = new HashMap<Long, Integer>(); HashMap<Long, Integer> max1 = new HashMap<Long, Integer>(); HashMap<Long, Integer> max2 = new HashMap<Long, Integer>(); for(int i=0; i < N; i++) { Triple p = arr[i]; ArrayDeque<Long> seen = new ArrayDeque<Long>(); int min = min(p.x, p.y); int max = max(p.x, p.y); long key = min*CONS+max; put(max1, max2, key, p.z, i); seen.add(key); min = min(p.x, p.z); max = max(p.x, p.z); key = min*CONS+max; if((long)seen.peekFirst() != key && (long)seen.peekLast() != key) { seen.add(key); put(max1, max2, key, p.y, i); } min = min(p.y, p.z); max = max(p.y, p.z); key = min*CONS+max; if((long)seen.peekFirst() != key && (long)seen.peekLast() != key) put(max1, max2, key, p.x, i); } long res = 0; int[] choice = new int[2]; for(long key: max2.keySet()) { long x = key/CONS; long y = key%CONS; long z = max2.get(key)+max1.get(key); long temp = min(x, min(y, z)); if(res < temp) { res = temp; choice[0] = id1.get(key)+1; choice[1] = id2.get(key)+1; } } int singleres = 0; for(Triple t: arr) singleres = max(singleres, min(t.x, min(t.y, t.z))); if(res > singleres) { System.out.println(2); System.out.println(choice[0]+" "+choice[1]); } else { System.out.println(1); for(int i=0; i < N; i++) { Triple t = arr[i]; int temp = min(t.x, min(t.y, t.z)); if(temp == singleres) { System.out.println(i+1); return; } } } } static HashMap<Long, Integer> id1; static HashMap<Long, Integer> id2; public static void put(HashMap<Long, Integer> max1, HashMap<Long, Integer> max2, long key, int val, int id) { if(!max1.containsKey(key)) { max1.put(key, val); id1.put(key, id); } else if(!max2.containsKey(key)) { if(max1.get(key) >= val) { max2.put(key, val); id2.put(key, id); } else { int old = max1.get(key); int oldid = id1.get(key); max1.put(key, val); id1.put(key, id); max2.put(key, old); id2.put(key, oldid); } } else if(max1.get(key) <= val) { int old = max1.get(key); int oldid = id1.get(key); max1.put(key, val); id1.put(key, id); max2.put(key, old); id2.put(key, oldid); } else if(max2.get(key) < val) { max2.put(key, val); id2.put(key, id); } } } class Triple { public int x; public int y; public int z; public Triple(int a, int b, int c) { x = a; y = b; z = c; } }
Java
["6\n5 5 5\n3 2 4\n1 4 1\n2 1 3\n3 2 4\n3 3 4", "7\n10 7 8\n5 10 3\n4 2 6\n5 5 5\n10 2 8\n4 2 1\n7 7 7"]
3 seconds
["1\n1", "2\n1 5"]
NoteIn the first example we can connect the pairs of stones: 2 and 4, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 2 and 5, the size of the parallelepiped: 3 × 2 × 8 or 6 × 2 × 4 or 3 × 4 × 4, the radius of the inscribed sphere 1, or 1, or 1.5 respectively. 2 and 6, the size of the parallelepiped: 3 × 5 × 4, the radius of the inscribed sphere 1.5 4 and 5, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 5 and 6, the size of the parallelepiped: 3 × 4 × 5, the radius of the inscribed sphere 1.5 Or take only one stone: 1 the size of the parallelepiped: 5 × 5 × 5, the radius of the inscribed sphere 2.5 2 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 3 the size of the parallelepiped: 1 × 4 × 1, the radius of the inscribed sphere 0.5 4 the size of the parallelepiped: 2 × 1 × 3, the radius of the inscribed sphere 0.5 5 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 6 the size of the parallelepiped: 3 × 3 × 4, the radius of the inscribed sphere 1.5 It is most profitable to take only the first stone.
Java 8
standard input
[ "data structures", "hashing" ]
ef82292a6591de818ddda9f426208291
The first line contains the integer n (1 ≀ n ≀ 105). n lines follow, in the i-th of which there are three integers ai, bi and ci (1 ≀ ai, bi, ci ≀ 109)Β β€” the lengths of edges of the i-th stone. Note, that two stones may have exactly the same sizes, but they still will be considered two different stones.
1,600
In the first line print k (1 ≀ k ≀ 2) the number of stones which Zahar has chosen. In the second line print k distinct integers from 1 to nΒ β€” the numbers of stones which Zahar needs to choose. Consider that stones are numbered from 1 to n in the order as they are given in the input data. You can print the stones in arbitrary order. If there are several answers print any of them.
standard output
PASSED
8e4e2e318a1b87cfd8127078c5c5c4e1
train_004.jsonl
1477922700
Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere. Zahar has n stones which are rectangular parallelepipeds. The edges sizes of the i-th of them are ai, bi and ci. He can take no more than two stones and present them to Kostya. If Zahar takes two stones, he should glue them together on one of the faces in order to get a new piece of rectangular parallelepiped of marble. Thus, it is possible to glue a pair of stones together if and only if two faces on which they are glued together match as rectangles. In such gluing it is allowed to rotate and flip the stones in any way. Help Zahar choose such a present so that Kostya can carve a sphere of the maximum possible volume and present it to Zahar.
256 megabytes
import java.io.*; import java.util.*; /** * * @author aboragab */ public class D_KostyaTheSculptor { static rock[] rocks; public static void main(String[] args) { InputStream inputStream = System.in; InputReader in = new InputReader(inputStream); int n = in.nextInt(); rocks = new rock[n]; for (int i = 0; i < n; i++) { int x = in.nextInt(); int y = in.nextInt(); int z = in.nextInt(); int xyz = x + y + z; int a = Math.min(x, Math.min(y, z)); int c = Math.max(x, Math.max(y, z)); int b = xyz - a - c; rocks[i] = new rock(a, b, c, i + 1); } Arrays.sort(rocks); long maxLen = 0; int f = -1, s = -1; for (int i = 0; i < n - 1; i++) { if (rocks[i].b == rocks[i + 1].b && rocks[i].c == rocks[i + 1].c) { long min = Math.min(rocks[i].a + rocks[i + 1].a, Math.min(rocks[i].b, rocks[i].c)); if (min > maxLen) { f = rocks[i].ind; s = rocks[i+1].ind; maxLen = min; } } else { long min = Math.min(rocks[i].a, Math.min(rocks[i].b, rocks[i].c)); if (min > maxLen) { f = rocks[i].ind; s = -1; maxLen = min; } } } long min = Math.min(rocks[n-1].a, Math.min(rocks[n-1].b, rocks[n-1].c)); if (min > maxLen) { f = rocks[n-1].ind; s = -1; maxLen = min; } if (s != -1) { System.out.println("2"); System.out.println(f + " " + s); } else { System.out.println("1"); System.out.println(f); } } static class rock implements Comparable<rock> { int a, b, c, ind; public rock(int a, int b, int c, int ind) { this.a = a; this.b = b; this.c = c; this.ind = ind; } @Override public int compareTo(rock t) { if (this.c != t.c) { return t.c - this.c; } else if (this.b != t.b) { return t.b - this.b; } else { return t.a - this.a; } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["6\n5 5 5\n3 2 4\n1 4 1\n2 1 3\n3 2 4\n3 3 4", "7\n10 7 8\n5 10 3\n4 2 6\n5 5 5\n10 2 8\n4 2 1\n7 7 7"]
3 seconds
["1\n1", "2\n1 5"]
NoteIn the first example we can connect the pairs of stones: 2 and 4, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 2 and 5, the size of the parallelepiped: 3 × 2 × 8 or 6 × 2 × 4 or 3 × 4 × 4, the radius of the inscribed sphere 1, or 1, or 1.5 respectively. 2 and 6, the size of the parallelepiped: 3 × 5 × 4, the radius of the inscribed sphere 1.5 4 and 5, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 5 and 6, the size of the parallelepiped: 3 × 4 × 5, the radius of the inscribed sphere 1.5 Or take only one stone: 1 the size of the parallelepiped: 5 × 5 × 5, the radius of the inscribed sphere 2.5 2 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 3 the size of the parallelepiped: 1 × 4 × 1, the radius of the inscribed sphere 0.5 4 the size of the parallelepiped: 2 × 1 × 3, the radius of the inscribed sphere 0.5 5 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 6 the size of the parallelepiped: 3 × 3 × 4, the radius of the inscribed sphere 1.5 It is most profitable to take only the first stone.
Java 8
standard input
[ "data structures", "hashing" ]
ef82292a6591de818ddda9f426208291
The first line contains the integer n (1 ≀ n ≀ 105). n lines follow, in the i-th of which there are three integers ai, bi and ci (1 ≀ ai, bi, ci ≀ 109)Β β€” the lengths of edges of the i-th stone. Note, that two stones may have exactly the same sizes, but they still will be considered two different stones.
1,600
In the first line print k (1 ≀ k ≀ 2) the number of stones which Zahar has chosen. In the second line print k distinct integers from 1 to nΒ β€” the numbers of stones which Zahar needs to choose. Consider that stones are numbered from 1 to n in the order as they are given in the input data. You can print the stones in arbitrary order. If there are several answers print any of them.
standard output
PASSED
ef86b114c053fabae440e6f879350acc
train_004.jsonl
1477922700
Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere. Zahar has n stones which are rectangular parallelepipeds. The edges sizes of the i-th of them are ai, bi and ci. He can take no more than two stones and present them to Kostya. If Zahar takes two stones, he should glue them together on one of the faces in order to get a new piece of rectangular parallelepiped of marble. Thus, it is possible to glue a pair of stones together if and only if two faces on which they are glued together match as rectangles. In such gluing it is allowed to rotate and flip the stones in any way. Help Zahar choose such a present so that Kostya can carve a sphere of the maximum possible volume and present it to Zahar.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.HashMap; import java.util.InputMismatchException; import java.util.Map; import java.io.OutputStreamWriter; import java.util.NoSuchElementException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Iterator; import java.io.BufferedWriter; import java.io.IOException; import java.util.Map.Entry; import java.io.Writer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Rustam Musin (PloadyFree@gmail.com) */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); Figure[] figures = new Figure[n]; for (int i = 0; i < n; i++) { int a = in.readInt(); int b = in.readInt(); int c = in.readInt(); figures[i] = new Figure(a, b, c); } Map<IntIntPair, IntList> bySize = new HashMap<>(); for (int i = 0; i < n; i++) { for (int x = 0; x < 3; x++) { for (int y = x + 1; y < 3; y++) { bySize.computeIfAbsent(sorted(figures[i].size[x], figures[i].size[y]), key -> new IntArrayList()) .add(i); } } } int maxSize = -1; int maxIdx1 = -1; int maxIdx2 = -1; for (Map.Entry<IntIntPair, IntList> e : bySize.entrySet()) { IntIntPair size = e.getKey(); IntList indexes = e.getValue(); int idx1 = indexes.get(0); for (int idx : indexes) { if (idx1 == -1 || figures[idx].third(size) > figures[idx1].third(size)) { idx1 = idx; } } int idx2 = -1; for (int idx : indexes) { if (idx != idx1 && (idx2 == -1 || figures[idx].third(size) > figures[idx2].third(size))) { idx2 = idx; } } int s1 = figures[idx1].third(size) + (idx2 == -1 ? 0 : figures[idx2].third(size)); int s2 = size.first; int s3 = size.second; int min = min(s1, s2, s3); if (min > maxSize) { maxSize = min; maxIdx1 = idx1; maxIdx2 = idx2; } } IntList ans = new IntArrayList(); ans.add(maxIdx1 + 1); if (maxIdx2 != -1) { ans.add(maxIdx2 + 1); } out.printLine(ans.size()); for (int i : ans) { out.printLine(i); } } private static IntIntPair sorted(int a, int b) { if (a > b) { return sorted(b, a); } return IntIntPair.makePair(a, b); } private static final int min(int a, int b, int c) { return Math.min(a, Math.min(b, c)); } } static class IntIntPair implements Comparable<IntIntPair> { public final int first; public final int second; public static IntIntPair makePair(int first, int second) { return new IntIntPair(first, second); } public IntIntPair(int first, int second) { this.first = first; this.second = second; } public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } IntIntPair pair = (IntIntPair) o; return first == pair.first && second == pair.second; } public int hashCode() { int result = first; result = 31 * result + second; return result; } public String toString() { return "(" + first + "," + second + ")"; } @SuppressWarnings({"unchecked"}) public int compareTo(IntIntPair o) { int value = Integer.compare(first, o.first); if (value != 0) { return value; } return Integer.compare(second, o.second); } } static interface IntList extends IntReversableCollection { public abstract int get(int index); public abstract void addAt(int index, int value); public abstract void removeAt(int index); default public IntIterator intIterator() { return new IntIterator() { private int at; private boolean removed; public int value() { if (removed) { throw new IllegalStateException(); } return get(at); } public boolean advance() { at++; removed = false; return isValid(); } public boolean isValid() { return !removed && at < size(); } public void remove() { removeAt(at); at--; removed = true; } }; } default public void add(int value) { addAt(size(), value); } } static class Figure { public final int[] size; public Figure(int a, int b, int c) { size = new int[]{a, b, c}; Arrays.sort(size); } public int third(int x, int y) { if (x > y) { return third(y, x); } if (size[0] != x) { return size[0]; } if (size[1] != y) { return size[1]; } return size[2]; } public int third(IntIntPair p) { return third(p.first, p.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 close() { writer.close(); } public void printLine(int i) { writer.println(i); } } static interface IntIterator { public int value() throws NoSuchElementException; public boolean advance(); public boolean isValid(); } static interface IntReversableCollection extends IntCollection { } static class IntArrayList extends IntAbstractStream implements IntList { private int size; private int[] data; public IntArrayList() { this(3); } public IntArrayList(int capacity) { data = new int[capacity]; } public IntArrayList(IntCollection c) { this(c.size()); addAll(c); } public IntArrayList(IntStream c) { this(); if (c instanceof IntCollection) { ensureCapacity(((IntCollection) c).size()); } addAll(c); } public IntArrayList(IntArrayList c) { size = c.size(); data = c.data.clone(); } public IntArrayList(int[] arr) { size = arr.length; data = arr.clone(); } public int size() { return size; } public int get(int at) { if (at >= size) { throw new IndexOutOfBoundsException("at = " + at + ", size = " + size); } return data[at]; } private void ensureCapacity(int capacity) { if (data.length >= capacity) { return; } capacity = Math.max(2 * data.length, capacity); data = Arrays.copyOf(data, capacity); } public void addAt(int index, int value) { ensureCapacity(size + 1); if (index > size || index < 0) { throw new IndexOutOfBoundsException("at = " + index + ", size = " + size); } if (index != size) { System.arraycopy(data, index, data, index + 1, size - index); } data[index] = value; size++; } public void removeAt(int index) { if (index >= size || index < 0) { throw new IndexOutOfBoundsException("at = " + index + ", size = " + size); } if (index != size - 1) { System.arraycopy(data, index + 1, data, index, size - index - 1); } size--; } } static interface IntCollection extends IntStream { public int size(); default public void add(int value) { throw new UnsupportedOperationException(); } default public IntCollection addAll(IntStream values) { for (IntIterator it = values.intIterator(); it.isValid(); it.advance()) { add(it.value()); } return this; } } static interface IntStream extends Iterable<Integer>, Comparable<IntStream> { public IntIterator intIterator(); default public Iterator<Integer> iterator() { return new Iterator<Integer>() { private IntIterator it = intIterator(); public boolean hasNext() { return it.isValid(); } public Integer next() { int result = it.value(); it.advance(); return result; } }; } default public int compareTo(IntStream c) { IntIterator it = intIterator(); IntIterator jt = c.intIterator(); while (it.isValid() && jt.isValid()) { int i = it.value(); int j = jt.value(); if (i < j) { return -1; } else if (i > j) { return 1; } it.advance(); jt.advance(); } if (it.isValid()) { return 1; } if (jt.isValid()) { return -1; } return 0; } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static abstract class IntAbstractStream implements IntStream { public String toString() { StringBuilder builder = new StringBuilder(); boolean first = true; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { if (first) { first = false; } else { builder.append(' '); } builder.append(it.value()); } return builder.toString(); } public boolean equals(Object o) { if (!(o instanceof IntStream)) { return false; } IntStream c = (IntStream) o; IntIterator it = intIterator(); IntIterator jt = c.intIterator(); while (it.isValid() && jt.isValid()) { if (it.value() != jt.value()) { return false; } it.advance(); jt.advance(); } return !it.isValid() && !jt.isValid(); } public int hashCode() { int result = 0; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { result *= 31; result += it.value(); } return result; } } }
Java
["6\n5 5 5\n3 2 4\n1 4 1\n2 1 3\n3 2 4\n3 3 4", "7\n10 7 8\n5 10 3\n4 2 6\n5 5 5\n10 2 8\n4 2 1\n7 7 7"]
3 seconds
["1\n1", "2\n1 5"]
NoteIn the first example we can connect the pairs of stones: 2 and 4, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 2 and 5, the size of the parallelepiped: 3 × 2 × 8 or 6 × 2 × 4 or 3 × 4 × 4, the radius of the inscribed sphere 1, or 1, or 1.5 respectively. 2 and 6, the size of the parallelepiped: 3 × 5 × 4, the radius of the inscribed sphere 1.5 4 and 5, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 5 and 6, the size of the parallelepiped: 3 × 4 × 5, the radius of the inscribed sphere 1.5 Or take only one stone: 1 the size of the parallelepiped: 5 × 5 × 5, the radius of the inscribed sphere 2.5 2 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 3 the size of the parallelepiped: 1 × 4 × 1, the radius of the inscribed sphere 0.5 4 the size of the parallelepiped: 2 × 1 × 3, the radius of the inscribed sphere 0.5 5 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 6 the size of the parallelepiped: 3 × 3 × 4, the radius of the inscribed sphere 1.5 It is most profitable to take only the first stone.
Java 8
standard input
[ "data structures", "hashing" ]
ef82292a6591de818ddda9f426208291
The first line contains the integer n (1 ≀ n ≀ 105). n lines follow, in the i-th of which there are three integers ai, bi and ci (1 ≀ ai, bi, ci ≀ 109)Β β€” the lengths of edges of the i-th stone. Note, that two stones may have exactly the same sizes, but they still will be considered two different stones.
1,600
In the first line print k (1 ≀ k ≀ 2) the number of stones which Zahar has chosen. In the second line print k distinct integers from 1 to nΒ β€” the numbers of stones which Zahar needs to choose. Consider that stones are numbered from 1 to n in the order as they are given in the input data. You can print the stones in arbitrary order. If there are several answers print any of them.
standard output
PASSED
e30f64b2f44f08e91ca5bd2bea097495
train_004.jsonl
1477922700
Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere. Zahar has n stones which are rectangular parallelepipeds. The edges sizes of the i-th of them are ai, bi and ci. He can take no more than two stones and present them to Kostya. If Zahar takes two stones, he should glue them together on one of the faces in order to get a new piece of rectangular parallelepiped of marble. Thus, it is possible to glue a pair of stones together if and only if two faces on which they are glued together match as rectangles. In such gluing it is allowed to rotate and flip the stones in any way. Help Zahar choose such a present so that Kostya can carve a sphere of the maximum possible volume and present it to Zahar.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.util.HashMap; import java.util.InputMismatchException; import java.io.IOException; import java.util.Map; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Rustam Musin (t.me/musin_acm) */ 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); DSkulptorKostya solver = new DSkulptorKostya(); solver.solve(1, in, out); out.close(); } static class DSkulptorKostya { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); int answer = -1; int[] result = null; Map<IntIntPair, IntIntPair> variants = new HashMap<>(); for (int i = 0; i < n; i++) { int[] p = in.readIntArray(3); Arrays.sort(p); if (answer < min(p)) { answer = min(p); result = new int[]{i}; } int[][] pVariants = getVariants(p); for (int[] var : pVariants) { IntIntPair cur = variants.get(IntIntPair.makePair(var[0], var[1])); if (cur == null) { continue; } int ans = min(var[0], var[1], var[2] + cur.first); if (answer < ans) { answer = ans; result = new int[]{cur.second, i}; } } for (int[] var : pVariants) { variants.merge(IntIntPair.makePair(var[0], var[1]), IntIntPair.makePair(var[2], i), (p1, p2) -> p1.first > p2.first ? p1 : p2); } } out.printLine(result.length); for (int x : result) { out.print(x + 1 + " "); } } int min(int... a) { int m = a[0]; for (int x : a) { m = Math.min(m, x); } return m; } int[][] getVariants(int[] p) { return new int[][]{ new int[]{p[0], p[1], p[2]}, new int[]{p[0], p[2], p[1]}, new int[]{p[1], p[2], p[0]} }; } } 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[] readIntArray(int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = readInt(); } return array; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class IntIntPair implements Comparable<IntIntPair> { public final int first; public final int second; public static IntIntPair makePair(int first, int second) { return new IntIntPair(first, second); } public IntIntPair(int first, int second) { this.first = first; this.second = second; } public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } IntIntPair pair = (IntIntPair) o; return first == pair.first && second == pair.second; } public int hashCode() { int result = first; result = 31 * result + second; return result; } public String toString() { return "(" + first + "," + second + ")"; } public int compareTo(IntIntPair o) { int value = Integer.compare(first, o.first); if (value != 0) { return value; } return Integer.compare(second, o.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 close() { writer.close(); } public void printLine(int i) { writer.println(i); } } }
Java
["6\n5 5 5\n3 2 4\n1 4 1\n2 1 3\n3 2 4\n3 3 4", "7\n10 7 8\n5 10 3\n4 2 6\n5 5 5\n10 2 8\n4 2 1\n7 7 7"]
3 seconds
["1\n1", "2\n1 5"]
NoteIn the first example we can connect the pairs of stones: 2 and 4, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 2 and 5, the size of the parallelepiped: 3 × 2 × 8 or 6 × 2 × 4 or 3 × 4 × 4, the radius of the inscribed sphere 1, or 1, or 1.5 respectively. 2 and 6, the size of the parallelepiped: 3 × 5 × 4, the radius of the inscribed sphere 1.5 4 and 5, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 5 and 6, the size of the parallelepiped: 3 × 4 × 5, the radius of the inscribed sphere 1.5 Or take only one stone: 1 the size of the parallelepiped: 5 × 5 × 5, the radius of the inscribed sphere 2.5 2 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 3 the size of the parallelepiped: 1 × 4 × 1, the radius of the inscribed sphere 0.5 4 the size of the parallelepiped: 2 × 1 × 3, the radius of the inscribed sphere 0.5 5 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 6 the size of the parallelepiped: 3 × 3 × 4, the radius of the inscribed sphere 1.5 It is most profitable to take only the first stone.
Java 8
standard input
[ "data structures", "hashing" ]
ef82292a6591de818ddda9f426208291
The first line contains the integer n (1 ≀ n ≀ 105). n lines follow, in the i-th of which there are three integers ai, bi and ci (1 ≀ ai, bi, ci ≀ 109)Β β€” the lengths of edges of the i-th stone. Note, that two stones may have exactly the same sizes, but they still will be considered two different stones.
1,600
In the first line print k (1 ≀ k ≀ 2) the number of stones which Zahar has chosen. In the second line print k distinct integers from 1 to nΒ β€” the numbers of stones which Zahar needs to choose. Consider that stones are numbered from 1 to n in the order as they are given in the input data. You can print the stones in arbitrary order. If there are several answers print any of them.
standard output
PASSED
fefbb6af5910a52cffe2efe6420e3018
train_004.jsonl
1477922700
Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere. Zahar has n stones which are rectangular parallelepipeds. The edges sizes of the i-th of them are ai, bi and ci. He can take no more than two stones and present them to Kostya. If Zahar takes two stones, he should glue them together on one of the faces in order to get a new piece of rectangular parallelepiped of marble. Thus, it is possible to glue a pair of stones together if and only if two faces on which they are glued together match as rectangles. In such gluing it is allowed to rotate and flip the stones in any way. Help Zahar choose such a present so that Kostya can carve a sphere of the maximum possible volume and present it to Zahar.
256 megabytes
import java.util.*; import java.io.*; public class KostyaTheSculptor { public static InputReader in; public static PrintWriter out; public static final int MOD = (int) (1e9 + 7); public static void main(String[] args) { in = new InputReader(System.in); out = new PrintWriter(System.out); int n = in.nextInt(); long[] a = new long[n]; long[] b = new long[n]; long[] c = new long[n]; int k = 0, ans1 = 0, ans2 = 0; long max = -1; HashMap<String, ArrayList<Node>> maxValue = new HashMap<String, ArrayList<Node>>(); for (int i = 0; i < n; i++) { a[i] = in.nextLong(); b[i] = in.nextLong(); c[i] = in.nextLong(); long minValue = Math.min(Math.min(a[i], b[i]), c[i]); if(minValue > max) { k = 1; ans1 = i + 1; max = minValue; } String s = Math.min(a[i], b[i]) + " " + Math.max(a[i], b[i]); if(!maxValue.containsKey(s)) { maxValue.put(s, new ArrayList<Node>()); } maxValue.get(s).add(new Node(i + 1, c[i])); s = Math.min(b[i], c[i]) + " " + Math.max(b[i], c[i]); if(!maxValue.containsKey(s)) { maxValue.put(s, new ArrayList<Node>()); } maxValue.get(s).add(new Node(i + 1, a[i])); s = Math.min(c[i], a[i]) + " " + Math.max(c[i], a[i]); if(!maxValue.containsKey(s)) { maxValue.put(s, new ArrayList<Node>()); } maxValue.get(s).add(new Node(i + 1, b[i])); } boolean found = false; for (String s : maxValue.keySet()) { int idx1 = -1, idx2 = -1; String[] tmp = s.split(" "); long x = Long.parseLong(tmp[0]); long y = Long.parseLong(tmp[1]); ArrayList<Node> list = maxValue.get(s); Collections.sort(list); long z = 0; for (int i = 0; i < Math.min(10, list.size()); i++) { for (int j = i + 1; j < Math.min(10, list.size()); j++) { if(list.get(i).index != list.get(j).index) { if(list.get(i).value + list.get(j).value > z) { z = list.get(i).value + list.get(j).value; idx1 = list.get(i).index; idx2 = list.get(j).index; found = true; } } } } if(found) { long minValue = Math.min(Math.min(x, y), z); if(minValue > max) { k = 2; ans1 = idx1; ans2 = idx2; max = minValue; } } } out.println(k); out.println(k == 1 ? (ans1 + "") : (ans1 + " " + ans2 + "")); out.close(); } static class Node implements Comparable<Node> { long value; int index; public Node(int u, long v) { this.index = u; this.value = v; } public void print() { out.println(index + " " + value + " "); } public int compareTo(Node that) { if(this.value == that.value) { return Integer.compare(this.index, that.index); } return Long.compare(-this.value, -that.value); } } static class InputReader { private InputStream stream; private 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 boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["6\n5 5 5\n3 2 4\n1 4 1\n2 1 3\n3 2 4\n3 3 4", "7\n10 7 8\n5 10 3\n4 2 6\n5 5 5\n10 2 8\n4 2 1\n7 7 7"]
3 seconds
["1\n1", "2\n1 5"]
NoteIn the first example we can connect the pairs of stones: 2 and 4, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 2 and 5, the size of the parallelepiped: 3 × 2 × 8 or 6 × 2 × 4 or 3 × 4 × 4, the radius of the inscribed sphere 1, or 1, or 1.5 respectively. 2 and 6, the size of the parallelepiped: 3 × 5 × 4, the radius of the inscribed sphere 1.5 4 and 5, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 5 and 6, the size of the parallelepiped: 3 × 4 × 5, the radius of the inscribed sphere 1.5 Or take only one stone: 1 the size of the parallelepiped: 5 × 5 × 5, the radius of the inscribed sphere 2.5 2 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 3 the size of the parallelepiped: 1 × 4 × 1, the radius of the inscribed sphere 0.5 4 the size of the parallelepiped: 2 × 1 × 3, the radius of the inscribed sphere 0.5 5 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 6 the size of the parallelepiped: 3 × 3 × 4, the radius of the inscribed sphere 1.5 It is most profitable to take only the first stone.
Java 8
standard input
[ "data structures", "hashing" ]
ef82292a6591de818ddda9f426208291
The first line contains the integer n (1 ≀ n ≀ 105). n lines follow, in the i-th of which there are three integers ai, bi and ci (1 ≀ ai, bi, ci ≀ 109)Β β€” the lengths of edges of the i-th stone. Note, that two stones may have exactly the same sizes, but they still will be considered two different stones.
1,600
In the first line print k (1 ≀ k ≀ 2) the number of stones which Zahar has chosen. In the second line print k distinct integers from 1 to nΒ β€” the numbers of stones which Zahar needs to choose. Consider that stones are numbered from 1 to n in the order as they are given in the input data. You can print the stones in arbitrary order. If there are several answers print any of them.
standard output
PASSED
680260d326bb5b8545a3581c9bc84711
train_004.jsonl
1477922700
Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere. Zahar has n stones which are rectangular parallelepipeds. The edges sizes of the i-th of them are ai, bi and ci. He can take no more than two stones and present them to Kostya. If Zahar takes two stones, he should glue them together on one of the faces in order to get a new piece of rectangular parallelepiped of marble. Thus, it is possible to glue a pair of stones together if and only if two faces on which they are glued together match as rectangles. In such gluing it is allowed to rotate and flip the stones in any way. Help Zahar choose such a present so that Kostya can carve a sphere of the maximum possible volume and present it to Zahar.
256 megabytes
import java.util.*; import java.io.*; public class KostyaTheSculptor { public static InputReader in; public static PrintWriter out; public static final int MOD = (int) (1e9 + 7); public static void main(String[] args) { in = new InputReader(System.in); out = new PrintWriter(System.out); int n = in.nextInt(); long[] a = new long[n]; long[] b = new long[n]; long[] c = new long[n]; int k = 0, ans1 = 0, ans2 = 0; long max = -1; HashMap<String, ArrayList<Node>> maxValue = new HashMap<String, ArrayList<Node>>(); for (int i = 0; i < n; i++) { a[i] = in.nextLong(); b[i] = in.nextLong(); c[i] = in.nextLong(); long minValue = Math.min(Math.min(a[i], b[i]), c[i]); if(minValue > max) { k = 1; ans1 = i + 1; max = minValue; } String s = Math.min(a[i], b[i]) + " " + Math.max(a[i], b[i]); if(!maxValue.containsKey(s)) { maxValue.put(s, new ArrayList<Node>()); } maxValue.get(s).add(new Node(i + 1, c[i])); s = Math.min(b[i], c[i]) + " " + Math.max(b[i], c[i]); if(!maxValue.containsKey(s)) { maxValue.put(s, new ArrayList<Node>()); } maxValue.get(s).add(new Node(i + 1, a[i])); s = Math.min(c[i], a[i]) + " " + Math.max(c[i], a[i]); if(!maxValue.containsKey(s)) { maxValue.put(s, new ArrayList<Node>()); } maxValue.get(s).add(new Node(i + 1, b[i])); } boolean found = false; for (String s : maxValue.keySet()) { int idx1 = -1, idx2 = -1; String[] tmp = s.split(" "); long x = Long.parseLong(tmp[0]); long y = Long.parseLong(tmp[1]); ArrayList<Node> list = maxValue.get(s); Collections.sort(list); long z = 0; for (int i = 0; i < Math.min(5, list.size()); i++) { for (int j = i + 1; j < Math.min(5, list.size()); j++) { if(list.get(i).index != list.get(j).index && list.get(i).value + list.get(j).value > z) { z = list.get(i).value + list.get(j).value; idx1 = list.get(i).index; idx2 = list.get(j).index; found = true; } } } if(found) { long minValue = Math.min(Math.min(x, y), z); if(minValue > max) { k = 2; ans1 = idx1; ans2 = idx2; max = minValue; } } } out.println(k); out.println(k == 1 ? (ans1 + "") : (ans1 + " " + ans2 + "")); out.close(); } static class Node implements Comparable<Node> { long value; int index; public Node(int u, long v) { this.index = u; this.value = v; } public void print() { out.println(index + " " + value + " "); } public int compareTo(Node that) { if(this.value == that.value) { return Integer.compare(this.index, that.index); } return Long.compare(-this.value, -that.value); } } static class InputReader { private InputStream stream; private 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 boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["6\n5 5 5\n3 2 4\n1 4 1\n2 1 3\n3 2 4\n3 3 4", "7\n10 7 8\n5 10 3\n4 2 6\n5 5 5\n10 2 8\n4 2 1\n7 7 7"]
3 seconds
["1\n1", "2\n1 5"]
NoteIn the first example we can connect the pairs of stones: 2 and 4, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 2 and 5, the size of the parallelepiped: 3 × 2 × 8 or 6 × 2 × 4 or 3 × 4 × 4, the radius of the inscribed sphere 1, or 1, or 1.5 respectively. 2 and 6, the size of the parallelepiped: 3 × 5 × 4, the radius of the inscribed sphere 1.5 4 and 5, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 5 and 6, the size of the parallelepiped: 3 × 4 × 5, the radius of the inscribed sphere 1.5 Or take only one stone: 1 the size of the parallelepiped: 5 × 5 × 5, the radius of the inscribed sphere 2.5 2 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 3 the size of the parallelepiped: 1 × 4 × 1, the radius of the inscribed sphere 0.5 4 the size of the parallelepiped: 2 × 1 × 3, the radius of the inscribed sphere 0.5 5 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 6 the size of the parallelepiped: 3 × 3 × 4, the radius of the inscribed sphere 1.5 It is most profitable to take only the first stone.
Java 8
standard input
[ "data structures", "hashing" ]
ef82292a6591de818ddda9f426208291
The first line contains the integer n (1 ≀ n ≀ 105). n lines follow, in the i-th of which there are three integers ai, bi and ci (1 ≀ ai, bi, ci ≀ 109)Β β€” the lengths of edges of the i-th stone. Note, that two stones may have exactly the same sizes, but they still will be considered two different stones.
1,600
In the first line print k (1 ≀ k ≀ 2) the number of stones which Zahar has chosen. In the second line print k distinct integers from 1 to nΒ β€” the numbers of stones which Zahar needs to choose. Consider that stones are numbered from 1 to n in the order as they are given in the input data. You can print the stones in arbitrary order. If there are several answers print any of them.
standard output
PASSED
4571d4769f018785c6191b3c678a56cd
train_004.jsonl
1477922700
Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere. Zahar has n stones which are rectangular parallelepipeds. The edges sizes of the i-th of them are ai, bi and ci. He can take no more than two stones and present them to Kostya. If Zahar takes two stones, he should glue them together on one of the faces in order to get a new piece of rectangular parallelepiped of marble. Thus, it is possible to glue a pair of stones together if and only if two faces on which they are glued together match as rectangles. In such gluing it is allowed to rotate and flip the stones in any way. Help Zahar choose such a present so that Kostya can carve a sphere of the maximum possible volume and present it to Zahar.
256 megabytes
import java.awt.*; import java.awt.List; import java.io.*; import java.util.*; public class Main { static Main.MyScanner sc = new Main.MyScanner(); // static PrintWriter out = new PrintWriter(System.out); static PrintStream out = System.out; public static void main(String[] args) { int n = sc.nextInt() ; long arr[][] = new long[n][3] ; HashMap<Point,ArrayList<Point>> hm = new HashMap<Point,ArrayList<Point>>() ; for(int i = 0 ; i < n ; i++) { HashSet<Point> temp = new HashSet<Point>() ; arr[i][0] = sc.nextInt() ; arr[i][1] = sc.nextInt() ; arr[i][2] = sc.nextInt() ; Arrays.sort(arr[i]); Point p ; p = new Point((int)arr[i][0], (int)arr[i][1]) ; if(!hm.containsKey(p)) hm.put(p,new ArrayList<Point>()) ; hm.get(p).add(new Point((int)arr[i][2], i)) ; temp.add(p) ; p = new Point((int)arr[i][1], (int)arr[i][2]) ; if(!hm.containsKey(p)) hm.put(p,new ArrayList<Point>()) ; if(!temp.contains(p))hm.get(p).add(new Point((int)arr[i][0], i)) ; temp.add(p) ; p = new Point((int)arr[i][0], (int)arr[i][2]) ; if(!hm.containsKey(p)) hm.put(p,new ArrayList<Point>()) ; if(!temp.contains(p))hm.get(p).add(new Point((int)arr[i][1], i)) ; } long max = 0 ; int ans[] = {-1,-1} ; for(Map.Entry<Point, ArrayList<Point>> x : hm.entrySet()) { ArrayList<Point> temp = x.getValue() ; Collections.sort(temp, new Comparator<Point>() { @Override public int compare(Point o1, Point o2) { return o1.x - o2.x; } }); long a1 = 0,a2 = 0 ; int a1pos = -1,a2pos = -1 ; if(temp.size() >= 1) { a1 = temp.get(temp.size()-1).x ; a1pos = temp.get(temp.size()-1).y ; } if(temp.size() >= 2) { a2 = temp.get(temp.size()-2).x ; a2pos = temp.get(temp.size()-2).y ; } if(max < Math.min(x.getKey().x, Math.min(x.getKey().y, a1 + a2))) { max = Math.min(x.getKey().x, Math.min(x.getKey().y, a1 + a2)) ; ans = new int[]{a1pos, a2pos}; } } if(ans[1] == -1) { out.println("1\n" + (ans[0]+1) ); } else { out.println("2\n" + (1+ans[0]) + " " + (1+ans[1]) ); } out.close(); } static private class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public long mod(long x) { // TODO Auto-generated method stub 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()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public long nextLong() { return Long.parseLong(next()); } } }
Java
["6\n5 5 5\n3 2 4\n1 4 1\n2 1 3\n3 2 4\n3 3 4", "7\n10 7 8\n5 10 3\n4 2 6\n5 5 5\n10 2 8\n4 2 1\n7 7 7"]
3 seconds
["1\n1", "2\n1 5"]
NoteIn the first example we can connect the pairs of stones: 2 and 4, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 2 and 5, the size of the parallelepiped: 3 × 2 × 8 or 6 × 2 × 4 or 3 × 4 × 4, the radius of the inscribed sphere 1, or 1, or 1.5 respectively. 2 and 6, the size of the parallelepiped: 3 × 5 × 4, the radius of the inscribed sphere 1.5 4 and 5, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 5 and 6, the size of the parallelepiped: 3 × 4 × 5, the radius of the inscribed sphere 1.5 Or take only one stone: 1 the size of the parallelepiped: 5 × 5 × 5, the radius of the inscribed sphere 2.5 2 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 3 the size of the parallelepiped: 1 × 4 × 1, the radius of the inscribed sphere 0.5 4 the size of the parallelepiped: 2 × 1 × 3, the radius of the inscribed sphere 0.5 5 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 6 the size of the parallelepiped: 3 × 3 × 4, the radius of the inscribed sphere 1.5 It is most profitable to take only the first stone.
Java 8
standard input
[ "data structures", "hashing" ]
ef82292a6591de818ddda9f426208291
The first line contains the integer n (1 ≀ n ≀ 105). n lines follow, in the i-th of which there are three integers ai, bi and ci (1 ≀ ai, bi, ci ≀ 109)Β β€” the lengths of edges of the i-th stone. Note, that two stones may have exactly the same sizes, but they still will be considered two different stones.
1,600
In the first line print k (1 ≀ k ≀ 2) the number of stones which Zahar has chosen. In the second line print k distinct integers from 1 to nΒ β€” the numbers of stones which Zahar needs to choose. Consider that stones are numbered from 1 to n in the order as they are given in the input data. You can print the stones in arbitrary order. If there are several answers print any of them.
standard output
PASSED
6ef6c620b5aaf34ebcdb80342b4ea00c
train_004.jsonl
1477922700
Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere. Zahar has n stones which are rectangular parallelepipeds. The edges sizes of the i-th of them are ai, bi and ci. He can take no more than two stones and present them to Kostya. If Zahar takes two stones, he should glue them together on one of the faces in order to get a new piece of rectangular parallelepiped of marble. Thus, it is possible to glue a pair of stones together if and only if two faces on which they are glued together match as rectangles. In such gluing it is allowed to rotate and flip the stones in any way. Help Zahar choose such a present so that Kostya can carve a sphere of the maximum possible volume and present it to Zahar.
256 megabytes
/* Keep solving problems. */ import java.util.*; import java.io.*; public class CFA { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; final long MOD = 1000L * 1000L * 1000L + 7; int[] dx = {0, -1, 0, 1}; int[] dy = {1, 0, -1, 0}; class Pair implements Comparable<Pair> { int x; int y; public Pair(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(Pair o) { if(x != o.x) { return Integer.compare(x, o.x); } else { return Integer.compare(y, o.y); } } @Override public int hashCode() { int res = 13; res = 37 * res + x; res = 37 * res + y; return res; } @Override public boolean equals(Object obj) { if(obj == null) { return false; } if(!(obj instanceof Pair)) { return false; } Pair o = (Pair) obj; return this.x == o.x && this.y == o.y; } } Map<Pair, Integer> hm = new HashMap<>(); Map<Pair, Integer> idx = new HashMap<>(); int res = -1; int id1 = -1; int id2 = -1; int max = -1; void solve() throws IOException { int n = nextInt(); for (int i = 0; i < n; i++) { int[] arr = nextIntArr(3); Arrays.sort(arr); if (arr[0] > max) { max = arr[0]; res = 1; id1 = i; id2 = -1; } check(arr[0], arr[1], arr[2], i); check(arr[0], arr[2], arr[1], i); check(arr[1], arr[2], arr[0], i); add(arr[0], arr[1], arr[2], i); add(arr[0], arr[2], arr[1], i); add(arr[1], arr[2], arr[0], i); } if (res == 1) { outln(1); out(id1 + 1); } else { outln(2); out((id2 + 1) + " " + (id1 + 1)); } } void check(int a1, int a2, int a3, int i) { Pair p1 = new Pair(a1, a2); if (hm.containsKey(p1)) { int len = hm.get(p1) + a3; int min = Math.min(a1, a2); min = Math.min(min, len); if (max < min) { max = min; res = 2; id1 = i; id2 = idx.get(p1); } } } void add(int a1, int a2, int a3, int i) { Pair p1 = new Pair(a1, a2); if (hm.containsKey(p1)) { if (hm.get(p1) < a3) { hm.put(p1, a3); idx.put(p1, i); } } else { hm.put(p1, a3); idx.put(p1, i); } } void shuffle(int[] a) { int n = a.length; for(int i = 0; i < n; i++) { int r = i + (int) (Math.random() * (n - i)); int tmp = a[i]; a[i] = a[r]; a[r] = tmp; } } long gcd(long a, long b) { while(a != 0 && b != 0) { long c = b; b = a % b; a = c; } return a + b; } private void outln(Object o) { out.println(o); } private void out(Object o) { out.print(o); } public CFA() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } public static void main(String[] args) throws IOException { new CFA(); } public long[] nextLongArr(int n) throws IOException{ long[] res = new long[n]; for(int i = 0; i < n; i++) res[i] = nextLong(); return res; } public int[] nextIntArr(int n) throws IOException { int[] res = new int[n]; for(int i = 0; i < n; i++) res[i] = nextInt(); return res; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } public String nextString() { try { return br.readLine(); } catch (IOException e) { eof = true; return null; } } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
Java
["6\n5 5 5\n3 2 4\n1 4 1\n2 1 3\n3 2 4\n3 3 4", "7\n10 7 8\n5 10 3\n4 2 6\n5 5 5\n10 2 8\n4 2 1\n7 7 7"]
3 seconds
["1\n1", "2\n1 5"]
NoteIn the first example we can connect the pairs of stones: 2 and 4, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 2 and 5, the size of the parallelepiped: 3 × 2 × 8 or 6 × 2 × 4 or 3 × 4 × 4, the radius of the inscribed sphere 1, or 1, or 1.5 respectively. 2 and 6, the size of the parallelepiped: 3 × 5 × 4, the radius of the inscribed sphere 1.5 4 and 5, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 5 and 6, the size of the parallelepiped: 3 × 4 × 5, the radius of the inscribed sphere 1.5 Or take only one stone: 1 the size of the parallelepiped: 5 × 5 × 5, the radius of the inscribed sphere 2.5 2 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 3 the size of the parallelepiped: 1 × 4 × 1, the radius of the inscribed sphere 0.5 4 the size of the parallelepiped: 2 × 1 × 3, the radius of the inscribed sphere 0.5 5 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 6 the size of the parallelepiped: 3 × 3 × 4, the radius of the inscribed sphere 1.5 It is most profitable to take only the first stone.
Java 8
standard input
[ "data structures", "hashing" ]
ef82292a6591de818ddda9f426208291
The first line contains the integer n (1 ≀ n ≀ 105). n lines follow, in the i-th of which there are three integers ai, bi and ci (1 ≀ ai, bi, ci ≀ 109)Β β€” the lengths of edges of the i-th stone. Note, that two stones may have exactly the same sizes, but they still will be considered two different stones.
1,600
In the first line print k (1 ≀ k ≀ 2) the number of stones which Zahar has chosen. In the second line print k distinct integers from 1 to nΒ β€” the numbers of stones which Zahar needs to choose. Consider that stones are numbered from 1 to n in the order as they are given in the input data. You can print the stones in arbitrary order. If there are several answers print any of them.
standard output
PASSED
f13554f2db32867c50b8170c0481378d
train_004.jsonl
1477922700
Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere. Zahar has n stones which are rectangular parallelepipeds. The edges sizes of the i-th of them are ai, bi and ci. He can take no more than two stones and present them to Kostya. If Zahar takes two stones, he should glue them together on one of the faces in order to get a new piece of rectangular parallelepiped of marble. Thus, it is possible to glue a pair of stones together if and only if two faces on which they are glued together match as rectangles. In such gluing it is allowed to rotate and flip the stones in any way. Help Zahar choose such a present so that Kostya can carve a sphere of the maximum possible volume and present it to Zahar.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Task733D { static Map<String, Long> firstMaxVal = new HashMap<>(); static Map<String, Long> firstKeyNum = new HashMap<>(); static Map<String, Integer> firstNum = new HashMap<>(); static Map<String, Long> secondMaxVal = new HashMap<>(); static Map<String, Long> secondKeyNum = new HashMap<>(); static Map<String, Integer> secondNum = new HashMap<>(); public static void main(String[] args) throws IOException { InputScanner is = new InputScanner(); int n = is.nextInt(); long[] tab = new long[3]; for (int i = 0; i < n; i++) { tab[0] = is.nextLong(); tab[1] = is.nextLong(); tab[2] = is.nextLong(); Arrays.sort(tab); String key1 = tab[0] + "#" + tab[1]; String key2 = tab[1] + "#" + tab[2]; String key3 = tab[0] + "#" + tab[2]; firstKeyNum.put(key1, tab[0]); firstKeyNum.put(key2, tab[1]); firstKeyNum.put(key3, tab[0]); secondKeyNum.put(key1, tab[1]); secondKeyNum.put(key2, tab[2]); secondKeyNum.put(key3, tab[2]); updateMaps(i, key1, tab[2]); if (!key1.equals(key2)) updateMaps(i, key2, tab[0]); if (!key1.equals(key3) && !key2.equals(key3)) updateMaps(i, key3, tab[1]); } int firstAnsVal = -1, secondAnsVal = -1; Long currentMax = Long.MIN_VALUE; for (String s : firstMaxVal.keySet()) { long currentVal = 0; if (secondMaxVal.containsKey(s)) { currentVal = Math.min((firstMaxVal.get(s) + secondMaxVal.get(s)), Math.min(firstKeyNum.get(s), secondKeyNum.get(s))); if (currentVal > currentMax) { currentMax = currentVal; firstAnsVal = firstNum.get(s); secondAnsVal = secondNum.get(s); } } else { currentVal = Math.min(firstMaxVal.get(s), Math.min(firstKeyNum.get(s), secondKeyNum.get(s))); if (currentVal > currentMax) { currentMax = currentVal; firstAnsVal = firstNum.get(s); secondAnsVal = -1; } } } firstAnsVal++; secondAnsVal++; if (secondAnsVal > 0) { System.out.println(2); System.out.println(firstAnsVal + " " + secondAnsVal); } else { System.out.println(1); System.out.println(firstAnsVal); } } private static void updateMaps(int i, String key, long value) { if (!firstMaxVal.containsKey(key)) { firstMaxVal.put(key, value); firstNum.put(key, i); } else if (!secondMaxVal.containsKey(key)) { secondMaxVal.put(key, value); secondNum.put(key, i); } else { if (firstMaxVal.get(key) < secondMaxVal.get(key) && firstMaxVal.get(key) < value) { firstMaxVal.put(key, value); firstNum.put(key, i); } else if (firstMaxVal.get(key) > secondMaxVal.get(key) && secondMaxVal.get(key) < value) { secondMaxVal.put(key, value); secondNum.put(key, i); } } } static class InputScanner { BufferedReader br; StringTokenizer st; public InputScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public String next() throws IOException { if (st == null || !st.hasMoreTokens()) { String line = br.readLine(); st = new StringTokenizer(line); } return st.nextToken(); } public int nextInt() throws IOException { String next = next(); return Integer.parseInt(next); } public long nextLong() throws IOException { String next = next(); return Long.parseLong(next); } } }
Java
["6\n5 5 5\n3 2 4\n1 4 1\n2 1 3\n3 2 4\n3 3 4", "7\n10 7 8\n5 10 3\n4 2 6\n5 5 5\n10 2 8\n4 2 1\n7 7 7"]
3 seconds
["1\n1", "2\n1 5"]
NoteIn the first example we can connect the pairs of stones: 2 and 4, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 2 and 5, the size of the parallelepiped: 3 × 2 × 8 or 6 × 2 × 4 or 3 × 4 × 4, the radius of the inscribed sphere 1, or 1, or 1.5 respectively. 2 and 6, the size of the parallelepiped: 3 × 5 × 4, the radius of the inscribed sphere 1.5 4 and 5, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 5 and 6, the size of the parallelepiped: 3 × 4 × 5, the radius of the inscribed sphere 1.5 Or take only one stone: 1 the size of the parallelepiped: 5 × 5 × 5, the radius of the inscribed sphere 2.5 2 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 3 the size of the parallelepiped: 1 × 4 × 1, the radius of the inscribed sphere 0.5 4 the size of the parallelepiped: 2 × 1 × 3, the radius of the inscribed sphere 0.5 5 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 6 the size of the parallelepiped: 3 × 3 × 4, the radius of the inscribed sphere 1.5 It is most profitable to take only the first stone.
Java 8
standard input
[ "data structures", "hashing" ]
ef82292a6591de818ddda9f426208291
The first line contains the integer n (1 ≀ n ≀ 105). n lines follow, in the i-th of which there are three integers ai, bi and ci (1 ≀ ai, bi, ci ≀ 109)Β β€” the lengths of edges of the i-th stone. Note, that two stones may have exactly the same sizes, but they still will be considered two different stones.
1,600
In the first line print k (1 ≀ k ≀ 2) the number of stones which Zahar has chosen. In the second line print k distinct integers from 1 to nΒ β€” the numbers of stones which Zahar needs to choose. Consider that stones are numbered from 1 to n in the order as they are given in the input data. You can print the stones in arbitrary order. If there are several answers print any of them.
standard output
PASSED
6dd4fc047c0db95973f932135e99526b
train_004.jsonl
1477922700
Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere. Zahar has n stones which are rectangular parallelepipeds. The edges sizes of the i-th of them are ai, bi and ci. He can take no more than two stones and present them to Kostya. If Zahar takes two stones, he should glue them together on one of the faces in order to get a new piece of rectangular parallelepiped of marble. Thus, it is possible to glue a pair of stones together if and only if two faces on which they are glued together match as rectangles. In such gluing it is allowed to rotate and flip the stones in any way. Help Zahar choose such a present so that Kostya can carve a sphere of the maximum possible volume and present it to Zahar.
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.TreeMap; import java.io.IOException; import java.util.Comparator; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Aman Kumar Singh */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); DKostyaTheSculptor solver = new DKostyaTheSculptor(); solver.solve(1, in, out); out.close(); } static class DKostyaTheSculptor { int MAXN = 200005; PrintWriter out; InputReader in; final Comparator<Tuple> com = new Comparator<Tuple>() { public int compare(Tuple t1, Tuple t2) { if (t1.x != t2.x) return Integer.compare(t1.x, t2.x); else return Integer.compare(t1.y, t2.y); } }; public void solve(int testNumber, InputReader in, PrintWriter out) { this.out = out; this.in = in; int n = ni(); int[][] max = new int[MAXN * 20][2]; TreeMap<Tuple, Integer> tmap = new TreeMap<>(com); int i = 0; double mx = -1.0; int[] indexes = new int[2]; Arrays.fill(indexes, -1); int[][] hola = new int[n][3]; int c = 0; for (i = 0; i < n; i++) { TreeMap<Tuple, Integer> local = new TreeMap<>(com); hola[i][0] = ni(); hola[i][1] = ni(); hola[i][2] = ni(); if (tmap.containsKey(new Tuple(Math.min(hola[i][0], hola[i][1]), Math.max(hola[i][0], hola[i][1])))) { int ind = tmap.get(new Tuple(Math.min(hola[i][0], hola[i][1]), Math.max(hola[i][0], hola[i][1]))); double p = Math.min(max[ind][0] + hola[i][2], Math.min(hola[i][0], hola[i][1])); if (mx < p / 2.0) { mx = p / 2.0; indexes = new int[]{max[ind][1] + 1, i + 1}; } } if (tmap.containsKey(new Tuple(Math.min(hola[i][0], hola[i][2]), Math.max(hola[i][0], hola[i][2])))) { int ind = tmap.get(new Tuple(Math.min(hola[i][0], hola[i][2]), Math.max(hola[i][0], hola[i][2]))); double p = Math.min(max[ind][0] + hola[i][1], Math.min(hola[i][0], hola[i][2])); if (mx < p / 2.0) { mx = p / 2.0; indexes = new int[]{max[ind][1] + 1, i + 1}; } } if (tmap.containsKey(new Tuple(Math.min(hola[i][1], hola[i][2]), Math.max(hola[i][1], hola[i][2])))) { int ind = tmap.get(new Tuple(Math.min(hola[i][1], hola[i][2]), Math.max(hola[i][1], hola[i][2]))); double p = Math.min(max[ind][0] + hola[i][0], Math.min(hola[i][1], hola[i][2])); if (mx < p / 2.0) { mx = p / 2.0; indexes = new int[]{max[ind][1] + 1, i + 1}; } } Integer x = local.get(new Tuple(Math.min(hola[i][0], hola[i][1]), Math.max(hola[i][0], hola[i][1]))); if (x == null) local.put(new Tuple(Math.min(hola[i][0], hola[i][1]), Math.max(hola[i][0], hola[i][1])), hola[i][2]); else local.put(new Tuple(Math.min(hola[i][0], hola[i][1]), Math.max(hola[i][0], hola[i][1])), Math.max(hola[i][2], x)); x = local.get(new Tuple(Math.min(hola[i][0], hola[i][2]), Math.max(hola[i][0], hola[i][2]))); if (x == null) local.put(new Tuple(Math.min(hola[i][0], hola[i][2]), Math.max(hola[i][0], hola[i][2])), hola[i][1]); else local.put(new Tuple(Math.min(hola[i][0], hola[i][2]), Math.max(hola[i][0], hola[i][2])), Math.max(hola[i][1], x)); x = local.get(new Tuple(Math.min(hola[i][1], hola[i][2]), Math.max(hola[i][1], hola[i][2]))); if (x == null) local.put(new Tuple(Math.min(hola[i][1], hola[i][2]), Math.max(hola[i][1], hola[i][2])), hola[i][0]); else local.put(new Tuple(Math.min(hola[i][1], hola[i][2]), Math.max(hola[i][1], hola[i][2])), Math.max(hola[i][0], x)); for (Tuple lol : local.keySet()) { x = local.get(lol); if (tmap.containsKey(lol)) { int ind = tmap.get(lol); if (max[ind][0] < x) { max[ind][0] = x; max[ind][1] = i; } } else { tmap.put(lol, c++); int ind = tmap.get(lol); if (max[ind][0] < x) { max[ind][0] = x; max[ind][1] = i; } } } } double mx1 = -1.0; int mn_ind = -1; for (i = 0; i < n; i++) { double p = Math.min(hola[i][0], Math.min(hola[i][1], hola[i][2])); if (mx1 < p / 2.0) { mx1 = p / 2.0; mn_ind = i + 1; } } if (mx > mx1) { pn(2); pn(indexes[0] + " " + indexes[1]); } else { pn(1); pn(mn_ind); } } int ni() { return in.nextInt(); } void pn(long zx) { out.println(zx); } void pn(String zx) { out.println(zx); } class Tuple { int x; int y; Tuple(int a, int b) { x = a; y = b; } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new UnknownError(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new UnknownError(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { return Integer.parseInt(next()); } public String next() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["6\n5 5 5\n3 2 4\n1 4 1\n2 1 3\n3 2 4\n3 3 4", "7\n10 7 8\n5 10 3\n4 2 6\n5 5 5\n10 2 8\n4 2 1\n7 7 7"]
3 seconds
["1\n1", "2\n1 5"]
NoteIn the first example we can connect the pairs of stones: 2 and 4, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 2 and 5, the size of the parallelepiped: 3 × 2 × 8 or 6 × 2 × 4 or 3 × 4 × 4, the radius of the inscribed sphere 1, or 1, or 1.5 respectively. 2 and 6, the size of the parallelepiped: 3 × 5 × 4, the radius of the inscribed sphere 1.5 4 and 5, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 5 and 6, the size of the parallelepiped: 3 × 4 × 5, the radius of the inscribed sphere 1.5 Or take only one stone: 1 the size of the parallelepiped: 5 × 5 × 5, the radius of the inscribed sphere 2.5 2 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 3 the size of the parallelepiped: 1 × 4 × 1, the radius of the inscribed sphere 0.5 4 the size of the parallelepiped: 2 × 1 × 3, the radius of the inscribed sphere 0.5 5 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 6 the size of the parallelepiped: 3 × 3 × 4, the radius of the inscribed sphere 1.5 It is most profitable to take only the first stone.
Java 8
standard input
[ "data structures", "hashing" ]
ef82292a6591de818ddda9f426208291
The first line contains the integer n (1 ≀ n ≀ 105). n lines follow, in the i-th of which there are three integers ai, bi and ci (1 ≀ ai, bi, ci ≀ 109)Β β€” the lengths of edges of the i-th stone. Note, that two stones may have exactly the same sizes, but they still will be considered two different stones.
1,600
In the first line print k (1 ≀ k ≀ 2) the number of stones which Zahar has chosen. In the second line print k distinct integers from 1 to nΒ β€” the numbers of stones which Zahar needs to choose. Consider that stones are numbered from 1 to n in the order as they are given in the input data. You can print the stones in arbitrary order. If there are several answers print any of them.
standard output
PASSED
4de46c87209f8b06e1428c9197b4daa6
train_004.jsonl
1477922700
Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere. Zahar has n stones which are rectangular parallelepipeds. The edges sizes of the i-th of them are ai, bi and ci. He can take no more than two stones and present them to Kostya. If Zahar takes two stones, he should glue them together on one of the faces in order to get a new piece of rectangular parallelepiped of marble. Thus, it is possible to glue a pair of stones together if and only if two faces on which they are glued together match as rectangles. In such gluing it is allowed to rotate and flip the stones in any way. Help Zahar choose such a present so that Kostya can carve a sphere of the maximum possible volume and present it to Zahar.
256 megabytes
import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.PriorityQueue; import java.util.Scanner; public class D378 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int n = sc.nextInt(); Map<K, PriorityQueue<V>> map = new HashMap<K, PriorityQueue<V>>(); long cin = Long.MIN_VALUE; int in = 0; for(int i=0;i<n;i++){ long[] a = new long[3]; a[0] = sc.nextLong(); a[1] = sc.nextLong(); a[2] = sc.nextLong(); Arrays.sort(a); long ct = Math.min(a[0], Math.min(a[1],a[2])); if(ct>cin){ cin = ct; in = i+1; } K k1 = new K(a[0],a[1]); K k2 = new K(a[0],a[2]); K k3 = new K(a[1],a[2]); if(!map.containsKey(k1)){ PriorityQueue<V> q = new PriorityQueue<V>((o1,o2)->(o2.a3>o1.a3?1:-1)); map.put(k1, q); } map.get(k1).add(new V(i+1,a[2])); if(!map.containsKey(k2)){ PriorityQueue<V> q = new PriorityQueue<V>((o1,o2)->(o2.a3>o1.a3?1:-1)); map.put(k2, q); } map.get(k2).add(new V(i+1,a[1])); if(!map.containsKey(k3)){ PriorityQueue<V> q = new PriorityQueue<V>((o1,o2)->(o2.a3>o1.a3?1:-1)); map.put(k3, q); } map.get(k3).add(new V(i+1,a[0])); } long val = Long.MIN_VALUE; int a0 = 0; int a1 = 0; for(Map.Entry<K, PriorityQueue<V>> e:map.entrySet()){ K k = e.getKey(); PriorityQueue<V> q = e.getValue(); if(q.size()<2) continue; V v1 = q.poll(); V v2 = q.poll(); long c = Math.min(v1.a3+v2.a3, Math.min(k.a1, k.a2)); if(c>val){ a0=v1.index; a1 = v2.index; val = c; } } if(val>cin){ System.out.println(2); System.out.println(a0+" "+a1); }else{ System.out.println(1); System.out.println(in); } } private static class K{ long a1; long a2; K(long a1, long a2){ this.a1 = a1; this.a2 = a2; } public boolean equals(Object o){ K k = (K) o; return k.a1 == a1 && k.a2 == a2; } public int hashCode(){ return (String.valueOf(a1)+"|"+String.valueOf(a2)).hashCode(); } } private static class V{ int index; long a3; V(int index, long a3){ this.index = index; this.a3 = a3; } } }
Java
["6\n5 5 5\n3 2 4\n1 4 1\n2 1 3\n3 2 4\n3 3 4", "7\n10 7 8\n5 10 3\n4 2 6\n5 5 5\n10 2 8\n4 2 1\n7 7 7"]
3 seconds
["1\n1", "2\n1 5"]
NoteIn the first example we can connect the pairs of stones: 2 and 4, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 2 and 5, the size of the parallelepiped: 3 × 2 × 8 or 6 × 2 × 4 or 3 × 4 × 4, the radius of the inscribed sphere 1, or 1, or 1.5 respectively. 2 and 6, the size of the parallelepiped: 3 × 5 × 4, the radius of the inscribed sphere 1.5 4 and 5, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 5 and 6, the size of the parallelepiped: 3 × 4 × 5, the radius of the inscribed sphere 1.5 Or take only one stone: 1 the size of the parallelepiped: 5 × 5 × 5, the radius of the inscribed sphere 2.5 2 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 3 the size of the parallelepiped: 1 × 4 × 1, the radius of the inscribed sphere 0.5 4 the size of the parallelepiped: 2 × 1 × 3, the radius of the inscribed sphere 0.5 5 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 6 the size of the parallelepiped: 3 × 3 × 4, the radius of the inscribed sphere 1.5 It is most profitable to take only the first stone.
Java 8
standard input
[ "data structures", "hashing" ]
ef82292a6591de818ddda9f426208291
The first line contains the integer n (1 ≀ n ≀ 105). n lines follow, in the i-th of which there are three integers ai, bi and ci (1 ≀ ai, bi, ci ≀ 109)Β β€” the lengths of edges of the i-th stone. Note, that two stones may have exactly the same sizes, but they still will be considered two different stones.
1,600
In the first line print k (1 ≀ k ≀ 2) the number of stones which Zahar has chosen. In the second line print k distinct integers from 1 to nΒ β€” the numbers of stones which Zahar needs to choose. Consider that stones are numbered from 1 to n in the order as they are given in the input data. You can print the stones in arbitrary order. If there are several answers print any of them.
standard output
PASSED
cc2961401122f1b101d738b05188c7cd
train_004.jsonl
1477922700
Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere. Zahar has n stones which are rectangular parallelepipeds. The edges sizes of the i-th of them are ai, bi and ci. He can take no more than two stones and present them to Kostya. If Zahar takes two stones, he should glue them together on one of the faces in order to get a new piece of rectangular parallelepiped of marble. Thus, it is possible to glue a pair of stones together if and only if two faces on which they are glued together match as rectangles. In such gluing it is allowed to rotate and flip the stones in any way. Help Zahar choose such a present so that Kostya can carve a sphere of the maximum possible volume and present it to Zahar.
256 megabytes
import java.io.*; import java.util.*; public class A implements Runnable { private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; private BufferedReader in; private PrintWriter out; private StringTokenizer tok = new StringTokenizer(""); private void init() throws FileNotFoundException { Locale.setDefault(Locale.US); String fileName = ""; if (ONLINE_JUDGE && fileName.isEmpty()) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { if (fileName.isEmpty()) { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } else { in = new BufferedReader(new FileReader(fileName + ".in")); out = new PrintWriter(fileName + ".out"); } } } String readString() { while (!tok.hasMoreTokens()) { try { tok = new StringTokenizer(in.readLine()); } catch (Exception e) { return null; } } return tok.nextToken(); } int readInt() { return Integer.parseInt(readString()); } long readLong() { return Long.parseLong(readString()); } double readDouble() { return Double.parseDouble(readString()); } int[] readIntArray(int size) { int[] a = new int[size]; for (int i = 0; i < size; i++) { a[i] = readInt(); } return a; } public static void main(String[] args) { //new Thread(null, new A(), "", 128 * (1L << 20)).start(); new A().run(); } long timeBegin, timeEnd; void time() { timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } @Override public void run() { try { timeBegin = System.currentTimeMillis(); init(); solve(); out.close(); time(); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } int aiverson(boolean x) { return x ? 1 : 0; } Pair readPair() { return new Pair(readInt(), readInt()); } int gcd(int a, int b) { return a == 0 ? b : gcd(b % a, a); } boolean cw(int x1, int y1, int x2, int y2, int x3, int y3) { return (x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1) < 0; } long getDistSqr(int x1, int y1, int x2, int y2) { long dx = x1 - x2; long dy = y1 - y2; return dx * dx + dy * dy; } long getLong(long x, long y) { if (x > y) { long swap = x; x = y; y = swap; } return (x << 32) + y; } Map<Long, TreeSet<Pair>> maxMap = new HashMap<>(); void add(long key, Pair value) { TreeSet<Pair> map = maxMap.get(key); if (map == null) { maxMap.put(key, map = new TreeSet<>()); } map.add(value); } void remove(long key, Pair value) { TreeSet<Pair> map = maxMap.get(key); map.remove(value); } Pair getMax(long key) { TreeSet<Pair> map = maxMap.get(key); return map.isEmpty() ? null : map.last(); } int min(int a, int b, int c) { return Math.min(a, Math.min(b, c)); } class Pair implements Comparable<Pair> { int value, id; public Pair(int value, int id) { this.value = value; this.id = id; } @Override public int compareTo(Pair o) { if (value == o.value) return Integer.compare(id, o.id); return Integer.compare(value, o.value); } } private void solve() throws IOException { int n = readInt(); int[][] b = new int[n][]; for (int i = 0; i < n; i++) { b[i] = readIntArray(3); int[] a = b[i]; add(getLong(a[0], a[1]), new Pair(a[2], i)); add(getLong(a[1], a[2]), new Pair(a[0], i)); add(getLong(a[2], a[0]), new Pair(a[1], i)); } long maxD = 0; int countAns = 0; int[] ans = new int[2]; for (int i = 0; i < n; i++) { int[] a = b[i]; if (maxD < min(a[0], a[1], a[2])) { maxD = min(a[0], a[1], a[2]); countAns = 1; ans[0] = i + 1; } remove(getLong(a[0], a[1]), new Pair(a[2], i)); Pair maxPair = getMax(getLong(a[0], a[1])); if (maxPair != null) { if (maxD < min(a[0], a[1], maxPair.value + a[2])) { maxD = min(a[0], a[1], maxPair.value + a[2]); countAns = 2; ans[0] = i + 1; ans[1] = maxPair.id + 1; } } add(getLong(a[0], a[1]), new Pair(a[2], i)); remove(getLong(a[1], a[2]), new Pair(a[0], i)); maxPair = getMax(getLong(a[1], a[2])); if (maxPair != null) { if (maxD < min(a[1], a[2], maxPair.value + a[0])) { maxD = min(a[1], a[2], maxPair.value + a[0]); countAns = 2; ans[0] = i + 1; ans[1] = maxPair.id + 1; } } add(getLong(a[1], a[2]), new Pair(a[0], i)); remove(getLong(a[2], a[0]), new Pair(a[1], i)); maxPair = getMax(getLong(a[2], a[0])); if (maxPair != null) { if (maxD < min(a[2], a[0], maxPair.value + a[1])) { maxD = min(a[2], a[0], maxPair.value + a[1]); countAns = 2; ans[0] = i + 1; ans[1] = maxPair.id + 1; } } add(getLong(a[2], a[0]), new Pair(a[1], i)); } out.println(countAns); for (int i = 0; i < countAns; i++) { out.print(ans[i] + " "); } } }
Java
["6\n5 5 5\n3 2 4\n1 4 1\n2 1 3\n3 2 4\n3 3 4", "7\n10 7 8\n5 10 3\n4 2 6\n5 5 5\n10 2 8\n4 2 1\n7 7 7"]
3 seconds
["1\n1", "2\n1 5"]
NoteIn the first example we can connect the pairs of stones: 2 and 4, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 2 and 5, the size of the parallelepiped: 3 × 2 × 8 or 6 × 2 × 4 or 3 × 4 × 4, the radius of the inscribed sphere 1, or 1, or 1.5 respectively. 2 and 6, the size of the parallelepiped: 3 × 5 × 4, the radius of the inscribed sphere 1.5 4 and 5, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 5 and 6, the size of the parallelepiped: 3 × 4 × 5, the radius of the inscribed sphere 1.5 Or take only one stone: 1 the size of the parallelepiped: 5 × 5 × 5, the radius of the inscribed sphere 2.5 2 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 3 the size of the parallelepiped: 1 × 4 × 1, the radius of the inscribed sphere 0.5 4 the size of the parallelepiped: 2 × 1 × 3, the radius of the inscribed sphere 0.5 5 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 6 the size of the parallelepiped: 3 × 3 × 4, the radius of the inscribed sphere 1.5 It is most profitable to take only the first stone.
Java 8
standard input
[ "data structures", "hashing" ]
ef82292a6591de818ddda9f426208291
The first line contains the integer n (1 ≀ n ≀ 105). n lines follow, in the i-th of which there are three integers ai, bi and ci (1 ≀ ai, bi, ci ≀ 109)Β β€” the lengths of edges of the i-th stone. Note, that two stones may have exactly the same sizes, but they still will be considered two different stones.
1,600
In the first line print k (1 ≀ k ≀ 2) the number of stones which Zahar has chosen. In the second line print k distinct integers from 1 to nΒ β€” the numbers of stones which Zahar needs to choose. Consider that stones are numbered from 1 to n in the order as they are given in the input data. You can print the stones in arbitrary order. If there are several answers print any of them.
standard output
PASSED
9f573d622e1c838dc82da119e100e5ef
train_004.jsonl
1477922700
Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere. Zahar has n stones which are rectangular parallelepipeds. The edges sizes of the i-th of them are ai, bi and ci. He can take no more than two stones and present them to Kostya. If Zahar takes two stones, he should glue them together on one of the faces in order to get a new piece of rectangular parallelepiped of marble. Thus, it is possible to glue a pair of stones together if and only if two faces on which they are glued together match as rectangles. In such gluing it is allowed to rotate and flip the stones in any way. Help Zahar choose such a present so that Kostya can carve a sphere of the maximum possible volume and present it to Zahar.
256 megabytes
import java.util.*; import java.math.*; import java.io.*; import java.text.DecimalFormat; import java.math.BigInteger; public class Main{ //static int d=20; static long mod=1000000007 ; static long mod3=1000000009 ; static long mod2=mod-1; //static HashMap<String,Integer> hm=new HashMap<>(); static ArrayList<ArrayList<Integer>> arr; static int size; static long[][] fac; static long[][] dp; static int num,max; static int ans=0; static HashMap<Integer,Integer> hm; public static void main(String[] args) throws IOException { boolean online =false; String fileName = "C-large"; PrintWriter out; if (online) { s.init(new FileInputStream(new File(fileName + ".in"))); out= new PrintWriter(new FileWriter(fileName + "out.txt")); } else { s.init(System.in); out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); } int n=s.ni(); long[][] a=new long[n][3]; HashMap<String,ArrayList<Integer>> hm=new HashMap<>(); HashMap<String,ArrayList<Long>> hm2=new HashMap<>(); ArrayList<Integer> arr=new ArrayList<>(); long max=0; for(int i=0;i<n;i++){ a[i][0]=s.nl(); a[i][1]=s.nl(); a[i][2]=s.nl(); Arrays.sort(a[i]); String[] xx=new String[]{a[i][0]+" "+a[i][1],a[i][1]+" "+a[i][2],a[i][0]+" "+a[i][2]};; for(int j=0;j<xx.length;j++){ long a1,a2,a3; if(j==0){ a1=a[i][0]; a2=a[i][1]; a3=a[i][2]; } else if(j==1){ a1=a[i][1]; a2=a[i][2]; a3=a[i][0]; } else{ a1=a[i][0]; a2=a[i][2]; a3=a[i][1]; } if(a1<=a3 || a2<=a3) continue; String x=xx[j]; if(hm.containsKey(x)){ if(hm.get(x).size()==1 && hm.get(x).get(0)!=i){ hm.get(x).add(i); hm2.get(x).add(a3); } else{ if(a3>hm2.get(x).get(0) && hm.get(x).get(0)!=i && hm2.get(x).get(0)<hm2.get(x).get(1)){ hm2.get(x).remove(0); hm2.get(x).add(a3); hm.get(x).remove(0); hm.get(x).add(i); } else if(a3>hm2.get(x).get(1) && hm.get(x).get(1)!=i){ hm2.get(x).remove(1); hm2.get(x).add(a3); hm.get(x).remove(1); hm.get(x).add(i); } } } else{ ArrayList<Integer> ar=new ArrayList<>(); ArrayList<Long> ar2=new ArrayList<>(); ar2.add(a3); ar.add(i); hm.put(x,ar); hm2.put(x,ar2); } } long curr=Math.min(a[i][0],Math.min(a[i][1],a[i][2])); if(curr>max){ arr.clear(); arr.add(i+1); max=curr; } } for(int i=0;i<n;i++){ String[] xx=new String[]{a[i][0]+" "+a[i][1],a[i][1]+" "+a[i][2],a[i][0]+" "+a[i][2]};; for(int j=0;j<xx.length;j++){ String x=xx[j]; if(!hm.containsKey(x) || !hm.get(x).contains(i)) continue; hm.get(x).remove(hm.get(x).indexOf(i)); //out.println(x); for(Integer z:hm.get(x)){ long a1,a2,a3; if(j==0){ a1=a[i][0]; a2=a[i][1]; a3=a[i][2]; } else if(j==1){ a1=a[i][1]; a2=a[i][2]; a3=a[i][0]; } else{ a1=a[i][0]; a2=a[i][2]; a3=a[i][1]; } if(a[z][0]==a1 && a[z][1]==a2 ) a3+=a[z][2]; else if(a[z][1]==a1 && a[z][2]==a2 ) a3+=a[z][0]; else a3+=a[z][1]; //out.println(a1+" "+a2+" "+a3); long curr=Math.min(a1,Math.min(a2,a3)); if(curr>max){ arr.clear(); arr.add(i+1); arr.add(z+1); max=curr; } } } } Collections.sort(arr); out.println(arr.size()); for(int w:arr) out.print(w+" "); out.close(); } static class bulb implements Comparable<bulb>{ long cost,ecost; int id; boolean on; int count; public bulb(long x,long y,int idd,int c){ cost=x; ecost=y; id=idd; count=c; on=true; } public int compareTo(bulb o){ return (int)Math.signum(ecost-o.ecost); } } public static long pow(long a,long b,long mod){ long ans=1; while(b>0){ if(b%2==1) ans=(a*ans)%mod; a=(a*a)%mod; b/=2; } return ans; } public static long pow2(long a,long b){ long ans=1; while(b>0){ if(b%2==1) ans=(a*ans); a=(a*a); b/=2; } return ans; } public static class s { static BufferedReader reader; static StringTokenizer tokenizer; /** call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input) ); tokenizer = new StringTokenizer(""); } /** get next word */ static String ns() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } static int ni() throws IOException { return Integer.parseInt( ns() ); } static double nd() throws IOException { return Double.parseDouble( ns() ); } static long nl() throws IOException { return Long.parseLong( ns() ); } } }
Java
["6\n5 5 5\n3 2 4\n1 4 1\n2 1 3\n3 2 4\n3 3 4", "7\n10 7 8\n5 10 3\n4 2 6\n5 5 5\n10 2 8\n4 2 1\n7 7 7"]
3 seconds
["1\n1", "2\n1 5"]
NoteIn the first example we can connect the pairs of stones: 2 and 4, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 2 and 5, the size of the parallelepiped: 3 × 2 × 8 or 6 × 2 × 4 or 3 × 4 × 4, the radius of the inscribed sphere 1, or 1, or 1.5 respectively. 2 and 6, the size of the parallelepiped: 3 × 5 × 4, the radius of the inscribed sphere 1.5 4 and 5, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 5 and 6, the size of the parallelepiped: 3 × 4 × 5, the radius of the inscribed sphere 1.5 Or take only one stone: 1 the size of the parallelepiped: 5 × 5 × 5, the radius of the inscribed sphere 2.5 2 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 3 the size of the parallelepiped: 1 × 4 × 1, the radius of the inscribed sphere 0.5 4 the size of the parallelepiped: 2 × 1 × 3, the radius of the inscribed sphere 0.5 5 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 6 the size of the parallelepiped: 3 × 3 × 4, the radius of the inscribed sphere 1.5 It is most profitable to take only the first stone.
Java 8
standard input
[ "data structures", "hashing" ]
ef82292a6591de818ddda9f426208291
The first line contains the integer n (1 ≀ n ≀ 105). n lines follow, in the i-th of which there are three integers ai, bi and ci (1 ≀ ai, bi, ci ≀ 109)Β β€” the lengths of edges of the i-th stone. Note, that two stones may have exactly the same sizes, but they still will be considered two different stones.
1,600
In the first line print k (1 ≀ k ≀ 2) the number of stones which Zahar has chosen. In the second line print k distinct integers from 1 to nΒ β€” the numbers of stones which Zahar needs to choose. Consider that stones are numbered from 1 to n in the order as they are given in the input data. You can print the stones in arbitrary order. If there are several answers print any of them.
standard output
PASSED
777c5467cc3b5b587342521bcc75e23b
train_004.jsonl
1477922700
Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere. Zahar has n stones which are rectangular parallelepipeds. The edges sizes of the i-th of them are ai, bi and ci. He can take no more than two stones and present them to Kostya. If Zahar takes two stones, he should glue them together on one of the faces in order to get a new piece of rectangular parallelepiped of marble. Thus, it is possible to glue a pair of stones together if and only if two faces on which they are glued together match as rectangles. In such gluing it is allowed to rotate and flip the stones in any way. Help Zahar choose such a present so that Kostya can carve a sphere of the maximum possible volume and present it to Zahar.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.HashMap; import javax.print.attribute.standard.MediaSize.Other; public class A { static class N { int ind, n; N(int i, int in) { ind = i; n = in; } } public static void main(String[] args) throws Exception { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); String l[];// bf.readLine().split(" "); int n = Integer.parseInt(bf.readLine()); int in[] = new int[3]; int bestI = -1; int bestJ = -1; int maxMin = 0; String s1; HashMap<String, N> map = new HashMap<>(); int nums[][] = new int[n][3]; for (int i = 0; i < n; i++) { l = bf.readLine().split(" "); in[0] = Integer.parseInt(l[0]); in[1] = Integer.parseInt(l[1]); in[2] = Integer.parseInt(l[2]); Arrays.sort(in); if (in[0] > maxMin) { maxMin = in[0]; bestI = i; } s1 = in[0] + " " + in[1]; if (!map.containsKey(s1)) map.put(s1, new N(i, in[2])); else { N x = map.get(s1); if (in[2] > x.n) { map.put(s1, new N(i, in[2])); } } s1 = in[1] + " " + in[2]; if (!map.containsKey(s1)) map.put(s1, new N(i, in[0])); else { N x = map.get(s1); if (in[0] > x.n) { map.put(s1, new N(i, in[0])); } } s1 = in[0] + " " + in[2]; if (!map.containsKey(s1)) map.put(s1, new N(i, in[1])); else { N x = map.get(s1); if (in[1] > x.n) { map.put(s1, new N(i, in[1])); } } nums[i][0] = in[0]; nums[i][1] = in[1]; nums[i][2] = in[2]; } N curr; for (int i = 0; i < nums.length; i++) { s1 = nums[i][0] + " " + nums[i][2]; curr = map.get(s1); if (curr.ind != i) { int o = curr.n + nums[i][1]; int min = getMin(o, nums[i][0], nums[i][2]); if (min > maxMin) { bestI = i; bestJ = curr.ind; maxMin = min; } } s1 = nums[i][1] + " " + nums[i][2]; curr = map.get(s1); if (curr.ind != i) { int o = curr.n + nums[i][0]; int min = getMin(o, nums[i][1], nums[i][2]); if (min > maxMin) { bestI = i; bestJ = curr.ind; maxMin = min; } } s1 = nums[i][0] + " " + nums[i][1]; curr = map.get(s1); if (curr.ind != i) { int o = curr.n + nums[i][2]; int min = getMin(o, nums[i][1], nums[i][0]); if (min > maxMin) { bestI = i; bestJ = curr.ind; maxMin = min; } } } if (bestJ != -1) { System.out.println(2); System.out.println((bestI + 1) + " " + (bestJ + 1)); } else { System.out.println(1); System.out.println((bestI + 1)); } } private static int getMin(int o, int i, int j) { return Math.min(o, Math.min(i, j)); } }
Java
["6\n5 5 5\n3 2 4\n1 4 1\n2 1 3\n3 2 4\n3 3 4", "7\n10 7 8\n5 10 3\n4 2 6\n5 5 5\n10 2 8\n4 2 1\n7 7 7"]
3 seconds
["1\n1", "2\n1 5"]
NoteIn the first example we can connect the pairs of stones: 2 and 4, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 2 and 5, the size of the parallelepiped: 3 × 2 × 8 or 6 × 2 × 4 or 3 × 4 × 4, the radius of the inscribed sphere 1, or 1, or 1.5 respectively. 2 and 6, the size of the parallelepiped: 3 × 5 × 4, the radius of the inscribed sphere 1.5 4 and 5, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 5 and 6, the size of the parallelepiped: 3 × 4 × 5, the radius of the inscribed sphere 1.5 Or take only one stone: 1 the size of the parallelepiped: 5 × 5 × 5, the radius of the inscribed sphere 2.5 2 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 3 the size of the parallelepiped: 1 × 4 × 1, the radius of the inscribed sphere 0.5 4 the size of the parallelepiped: 2 × 1 × 3, the radius of the inscribed sphere 0.5 5 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 6 the size of the parallelepiped: 3 × 3 × 4, the radius of the inscribed sphere 1.5 It is most profitable to take only the first stone.
Java 8
standard input
[ "data structures", "hashing" ]
ef82292a6591de818ddda9f426208291
The first line contains the integer n (1 ≀ n ≀ 105). n lines follow, in the i-th of which there are three integers ai, bi and ci (1 ≀ ai, bi, ci ≀ 109)Β β€” the lengths of edges of the i-th stone. Note, that two stones may have exactly the same sizes, but they still will be considered two different stones.
1,600
In the first line print k (1 ≀ k ≀ 2) the number of stones which Zahar has chosen. In the second line print k distinct integers from 1 to nΒ β€” the numbers of stones which Zahar needs to choose. Consider that stones are numbered from 1 to n in the order as they are given in the input data. You can print the stones in arbitrary order. If there are several answers print any of them.
standard output
PASSED
4016361d2591a77d5fc63ab74a862ac8
train_004.jsonl
1477922700
Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere. Zahar has n stones which are rectangular parallelepipeds. The edges sizes of the i-th of them are ai, bi and ci. He can take no more than two stones and present them to Kostya. If Zahar takes two stones, he should glue them together on one of the faces in order to get a new piece of rectangular parallelepiped of marble. Thus, it is possible to glue a pair of stones together if and only if two faces on which they are glued together match as rectangles. In such gluing it is allowed to rotate and flip the stones in any way. Help Zahar choose such a present so that Kostya can carve a sphere of the maximum possible volume and present it to Zahar.
256 megabytes
import java.io.*; import java.math.BigDecimal; import java.util.*; /** * Created by chao on 16/11/13. */ public class A { private static Map<Long, List<Long>> map = new HashMap<>(); public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out)); //debug(); String s = br.readLine(); int n = Integer.parseInt(s); long[] a = new long[3]; for (long i = 1; i <= n; i++) { String[] nums = br.readLine().split(" "); for (int k = 0; k < nums.length; k++) { a[k] = Long.parseLong(nums[k]); } Arrays.sort(a); if (a[0] == a[1]) { if (a[1] == a[2]) { put(a[0], a[1], i, a[2]); } else { put(a[0], a[1], i, a[2]); put(a[0], a[2], i, a[1]); } } else { if (a[1] == a[2]) { put(a[0], a[1], i, a[2]); put(a[1], a[2], i, a[0]); } else { put(a[0], a[1], i, a[2]); put(a[0], a[2], i, a[1]); put(a[1], a[2], i, a[0]); } } } //double max = -1; long p1 = -1; long p2 = -1; long max = -1; for(long key : map.keySet()) { List<Long> heights = map.get(key); long r = Math.min(getLow(key),getHigh(key)); if (heights.size() == 1) { r = Math.min(r, getLow(heights.get(0))); if (r > max) { max = r; p1 = getHigh(heights.get(0)); p2 = -1; } } else { heights.sort(new lComparator()); r = Math.min(r, getLow(heights.get(0)) + getLow(heights.get(1))); if (r > max) { max = r; p1 = getHigh(heights.get(0)); p2 = getHigh(heights.get(1)); } } } if (p2 == -1) { pw.println(1); pw.println(p1); } else { pw.println(2); pw.println(p1 + " " + p2); } pw.flush(); pw.close(); br.close(); } private static void put(long a, long b, long i, long c) { long key = ((a<<30)|b); long val = ((i<<30)|c); if (map.containsKey(key)) { map.get(key).add(val); } else { List<Long> list = new ArrayList<>(); list.add(val); map.put(key, list); } } private static long getLow(long x) { return (x&((1L<<30) - 1)); } private static long getHigh(long x) { return (x >> 30); } } class lComparator implements Comparator<Long> { @Override public int compare(Long o1, Long o2) { long res = (o2&((1L<<30) - 1)) - (o1&((1L<<30) - 1)); if (res > 0) return 1; else if (res == 0) return 0; else return -1; } }
Java
["6\n5 5 5\n3 2 4\n1 4 1\n2 1 3\n3 2 4\n3 3 4", "7\n10 7 8\n5 10 3\n4 2 6\n5 5 5\n10 2 8\n4 2 1\n7 7 7"]
3 seconds
["1\n1", "2\n1 5"]
NoteIn the first example we can connect the pairs of stones: 2 and 4, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 2 and 5, the size of the parallelepiped: 3 × 2 × 8 or 6 × 2 × 4 or 3 × 4 × 4, the radius of the inscribed sphere 1, or 1, or 1.5 respectively. 2 and 6, the size of the parallelepiped: 3 × 5 × 4, the radius of the inscribed sphere 1.5 4 and 5, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 5 and 6, the size of the parallelepiped: 3 × 4 × 5, the radius of the inscribed sphere 1.5 Or take only one stone: 1 the size of the parallelepiped: 5 × 5 × 5, the radius of the inscribed sphere 2.5 2 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 3 the size of the parallelepiped: 1 × 4 × 1, the radius of the inscribed sphere 0.5 4 the size of the parallelepiped: 2 × 1 × 3, the radius of the inscribed sphere 0.5 5 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 6 the size of the parallelepiped: 3 × 3 × 4, the radius of the inscribed sphere 1.5 It is most profitable to take only the first stone.
Java 8
standard input
[ "data structures", "hashing" ]
ef82292a6591de818ddda9f426208291
The first line contains the integer n (1 ≀ n ≀ 105). n lines follow, in the i-th of which there are three integers ai, bi and ci (1 ≀ ai, bi, ci ≀ 109)Β β€” the lengths of edges of the i-th stone. Note, that two stones may have exactly the same sizes, but they still will be considered two different stones.
1,600
In the first line print k (1 ≀ k ≀ 2) the number of stones which Zahar has chosen. In the second line print k distinct integers from 1 to nΒ β€” the numbers of stones which Zahar needs to choose. Consider that stones are numbered from 1 to n in the order as they are given in the input data. You can print the stones in arbitrary order. If there are several answers print any of them.
standard output
PASSED
ba45d6554bef7e32f4025efe4ac58ef5
train_004.jsonl
1277730300
Once Bob took a paper stripe of n squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into three pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece, and each piece contains positive integer amount of squares. Would you help Bob solve this problem?
64 megabytes
/** * DA-IICT * Author : PARTH PATEL */ import java.io.*; import java.math.*; import java.util.*; import static java.util.Arrays.fill; import static java.lang.Math.*; import static java.util.Arrays.sort; import static java.util.Collections.sort; public class C21 { public static long mod = 1000000007; public static long INF = (1L << 60); static FastScanner2 in = new FastScanner2(); static OutputWriter out = new OutputWriter(System.out); public static void main(String[] args) { int n=in.nextInt(); int[] arr=new int[n]; int sum=0; for(int i=0;i<n;i++) { arr[i]=in.nextInt(); sum+=arr[i]; } if(sum%3!=0) { out.println(0); out.flush(); return; } else { int onesum=sum/3; long answer=0; int a=0; sum=0; for(int i=0;i<n;i++) { sum+=arr[i]; if(sum==2*onesum && i<n-1) { answer+=(long)a; } if(sum==onesum) { a++; } } out.println(answer); } out.close(); } public static long pow(long x, long n, long mod) { long res = 1; for (long p = x; n > 0; n >>= 1, p = (p * p) % mod) { if ((n & 1) != 0) { res = (res * p % mod); } } return res; } public static long gcd(long n1, long n2) { long r; while (n2 != 0) { r = n1 % n2; n1 = n2; n2 = r; } return n1; } public static long lcm(long n1, long n2) { long answer = (n1 * n2) / (gcd(n1, n2)); return answer; } static class FastScanner2 { private byte[] buf = new byte[1024]; private int curChar; private int snumChars; public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = System.in.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream inputstream) { reader = new BufferedReader(new InputStreamReader(inputstream)); tokenizer = null; } public String nextLine() { String fullLine = null; while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { fullLine = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return fullLine; } return fullLine; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public long[] nextLongArray(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } public int nextInt() { return Integer.parseInt(next()); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } } }
Java
["4\n1 2 3 3", "5\n1 2 3 4 5"]
1 second
["1", "0"]
null
Java 8
standard input
[ "dp", "binary search", "sortings" ]
4798211615bcff8730378330756ae63f
The first input line contains integer n (1 ≀ n ≀ 105) β€” amount of squares in the stripe. The second line contains n space-separated numbers β€” they are the numbers written in the squares of the stripe. These numbers are integer and do not exceed 10000 in absolute value.
2,000
Output the amount of ways to cut the stripe into three non-empty pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece. Don't forget that it's allowed to cut the stripe along the squares' borders only.
standard output
PASSED
8e320a8cd25f472bd3eaa323d85d83c0
train_004.jsonl
1277730300
Once Bob took a paper stripe of n squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into three pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece, and each piece contains positive integer amount of squares. Would you help Bob solve this problem?
64 megabytes
import java.io.*; import java.util.*; import java.util.stream.Stream; public class Main implements Runnable { static final int MOD = (int) 1e9 + 7; static final int MI = (int) 1e9; static final long ML = (long) 1e18; static final Reader in = new Reader(); static final PrintWriter out = new PrintWriter(System.out); StringBuilder answer = new StringBuilder(); public static void main(String[] args) { new Thread(null, new Main(), "persefone", 1 << 32).start(); } @Override public void run() { solve(); printf(); flush(); } void solve() { int n = in.nextInt(); int[] a = new int[n + 1]; int sum = 0; for (int i = 1; i <= n; i++) { sum += a[i] = in.nextInt(); } if (n < 3 || sum % 3 != 0) { printf(0); return; } int x = sum / 3, y = 2 * x, nx = 0, ny = 0; long ans = 0; sum = 0; for (int i = 1; i <= n - 1; i++) { sum += a[i]; if (sum == y) { ans += nx; } if (sum == x) nx++; } printf(ans); } static class ArrayUtils { public static int lowerBound(int[] a, int l, int r, int k) { int m = 0, ans = r; while (l < r) if (a[m = l + r >> 1] >= k) ans = r = m; else l = m + 1; return ans; } } void printf() { out.print(answer); } void close() { out.close(); } void flush() { out.flush(); } void printf(Stream<?> str) { str.forEach(o -> add(o, " ")); add("\n"); } void printf(Object... obj) { printf(false, obj); } void printfWithDescription(Object... obj) { printf(true, obj); } private void printf(boolean b, Object... obj) { if (obj.length > 1) { for (int i = 0; i < obj.length; i++) { if (b) add(obj[i].getClass().getSimpleName(), " - "); if (obj[i] instanceof Collection<?>) { printf((Collection<?>) obj[i]); } else if (obj[i] instanceof int[][]) { printf((int[][]) obj[i]); } else if (obj[i] instanceof long[][]) { printf((long[][]) obj[i]); } else if (obj[i] instanceof double[][]) { printf((double[][]) obj[i]); } else printf(obj[i]); } return; } if (b) add(obj[0].getClass().getSimpleName(), " - "); printf(obj[0]); } void printf(Object o) { if (o instanceof int[]) printf(Arrays.stream((int[]) o).boxed()); else if (o instanceof char[]) printf(new String((char[]) o)); else if (o instanceof long[]) printf(Arrays.stream((long[]) o).boxed()); else if (o instanceof double[]) printf(Arrays.stream((double[]) o).boxed()); else if (o instanceof boolean[]) { for (boolean b : (boolean[]) o) add(b, " "); add("\n"); } else add(o, "\n"); } void printf(int[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(long[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(double[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(boolean[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(Collection<?> col) { printf(col.stream()); } <T, K> void add(T t, K k) { if (t instanceof Collection<?>) { ((Collection<?>) t).forEach(i -> add(i, " ")); } else if (t instanceof Object[]) { Arrays.stream((Object[]) t).forEach(i -> add(i, " ")); } else add(t); add(k); } <T> void add(T t) { answer.append(t); } static class Reader { private BufferedReader br; private StringTokenizer st; Reader() { br = new BufferedReader(new InputStreamReader(System.in)); } Reader(String fileName) throws FileNotFoundException { br = new BufferedReader(new FileReader(fileName)); } boolean isReady() throws IOException { return br.ready(); } String next() { try { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } long nextLong() { return Long.parseLong(next()); } String nextLine() { String s = ""; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return s; } } }
Java
["4\n1 2 3 3", "5\n1 2 3 4 5"]
1 second
["1", "0"]
null
Java 8
standard input
[ "dp", "binary search", "sortings" ]
4798211615bcff8730378330756ae63f
The first input line contains integer n (1 ≀ n ≀ 105) β€” amount of squares in the stripe. The second line contains n space-separated numbers β€” they are the numbers written in the squares of the stripe. These numbers are integer and do not exceed 10000 in absolute value.
2,000
Output the amount of ways to cut the stripe into three non-empty pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece. Don't forget that it's allowed to cut the stripe along the squares' borders only.
standard output
PASSED
6bd6b9b6dabd517c81eb0eab452479ef
train_004.jsonl
1277730300
Once Bob took a paper stripe of n squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into three pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece, and each piece contains positive integer amount of squares. Would you help Bob solve this problem?
64 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Test { 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; } } public static void main(String args[]) { FastScanner in = new FastScanner(); int n = in.nextInt(); int a[] = new int[n]; int sum = 0; for(int i=0;i<n;i++){ a[i] = in.nextInt(); sum+=a[i]; } if(sum%3!=0||n<3){ System.out.println(0); return; } ArrayList<Integer> a1 = new ArrayList<Integer>(); ArrayList<Integer> a2 = new ArrayList<Integer>(); int s = 0; for(int i=0;i<n;i++){ s+=a[i]; if(s==sum/3) a1.add(i); else if(s/2==sum/3 && s%2==0) a2.add(a1.size()); } if(sum==0){ long x = a1.size(); x--; System.out.println((x*(x-1))/2); return; } int ans = 0; for(int i:a2){ ans+=i; } System.out.println(ans); } }
Java
["4\n1 2 3 3", "5\n1 2 3 4 5"]
1 second
["1", "0"]
null
Java 8
standard input
[ "dp", "binary search", "sortings" ]
4798211615bcff8730378330756ae63f
The first input line contains integer n (1 ≀ n ≀ 105) β€” amount of squares in the stripe. The second line contains n space-separated numbers β€” they are the numbers written in the squares of the stripe. These numbers are integer and do not exceed 10000 in absolute value.
2,000
Output the amount of ways to cut the stripe into three non-empty pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece. Don't forget that it's allowed to cut the stripe along the squares' borders only.
standard output
PASSED
78bc771ddf4fe0ef161336ad5691be61
train_004.jsonl
1277730300
Once Bob took a paper stripe of n squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into three pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece, and each piece contains positive integer amount of squares. Would you help Bob solve this problem?
64 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(String[] args) throws IOException { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(in, out); out.close(); } private static class TaskB { static final long max = 10000000000000000L; static final double eps = 0.000001; void solve(InputReader in, PrintWriter out) throws IOException { int n = in.nextInt(); int a[] = new int[n]; long sum = 0; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); sum += a[i]; } if (sum % 3 != 0) { out.println(0); return; } sum /= 3; long right = 0; long count = 0; boolean is[] = new boolean[n]; for (int i = n - 1; i >= 0; i--) { right += a[i]; if (right == sum) { count++; is[i] = true; } } if (is[0]) { count--; } long left = 0; long res = 0; for (int i = 0; i < n - 1; i++) { if (is[i + 1]) { count--; } left += a[i]; if (left == sum) res += count; } out.println(res); } double segment(double x1, double y1, double x2, double y2) { return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); } long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } long lcm(long a, long b) { return (a * b) / gcd(a, b); } } private static class InputReader { StringTokenizer st; BufferedReader br; public InputReader(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public InputReader(FileReader s) throws FileNotFoundException { br = new BufferedReader(s); } public String next() { while (st == null || !st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public String nextLine() { try { return br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } public double nextDouble() { return Double.parseDouble(next()); } public boolean ready() { try { return br.ready(); } catch (IOException e) { throw new RuntimeException(e); } } } }
Java
["4\n1 2 3 3", "5\n1 2 3 4 5"]
1 second
["1", "0"]
null
Java 8
standard input
[ "dp", "binary search", "sortings" ]
4798211615bcff8730378330756ae63f
The first input line contains integer n (1 ≀ n ≀ 105) β€” amount of squares in the stripe. The second line contains n space-separated numbers β€” they are the numbers written in the squares of the stripe. These numbers are integer and do not exceed 10000 in absolute value.
2,000
Output the amount of ways to cut the stripe into three non-empty pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece. Don't forget that it's allowed to cut the stripe along the squares' borders only.
standard output
PASSED
1721e0bb45356def89ff89e6c8bfa4c2
train_004.jsonl
1571754900
The only difference between easy and hard versions is the maximum value of $$$n$$$.You are given a positive integer number $$$n$$$. You really love good numbers so you want to find the smallest good number greater than or equal to $$$n$$$.The positive integer is called good if it can be represented as a sum of distinct powers of $$$3$$$ (i.e. no duplicates of powers of $$$3$$$ are allowed).For example: $$$30$$$ is a good number: $$$30 = 3^3 + 3^1$$$, $$$1$$$ is a good number: $$$1 = 3^0$$$, $$$12$$$ is a good number: $$$12 = 3^2 + 3^1$$$, but $$$2$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ ($$$2 = 3^0 + 3^0$$$), $$$19$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representations $$$19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0$$$ are invalid), $$$20$$$ is also not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representation $$$20 = 3^2 + 3^2 + 3^0 + 3^0$$$ is invalid). Note, that there exist other representations of $$$19$$$ and $$$20$$$ as sums of powers of $$$3$$$ but none of them consists of distinct powers of $$$3$$$.For the given positive integer $$$n$$$ find such smallest $$$m$$$ ($$$n \le m$$$) that $$$m$$$ is a good number.You have to answer $$$q$$$ independent queries.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Scanner; import java.math.BigInteger; import java.util.LinkedList; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC2 solver = new TaskC2(); solver.solve(1, in, out); out.close(); } static class TaskC2 { public void solve(int testNumber, Scanner in, PrintWriter out) { int q = in.nextInt(); for (int i = 0; i < q; i++) { BigInteger n = new BigInteger(in.next()); LinkedList<Integer> vals = new LinkedList<>(); BigInteger ZERO = new BigInteger("" + 0); BigInteger THREE = new BigInteger("" + 3); int pos2 = -1; while (n.compareTo(ZERO) > 0) { int mod = n.mod(THREE).intValue(); vals.addLast(mod); if (mod == 2) pos2 = vals.size() - 1; n = n.divide(THREE); } vals.add(0); if (pos2 != -1) { int pos1 = 0; for (int j = pos2 + 1; j < vals.size(); j++) { if (vals.get(j) == 0) { pos1 = j; break; } } vals.set(pos1, 1); for (int j = pos1 - 1; j >= 0; j--) { vals.set(j, 0); } } BigInteger answer = new BigInteger("0"); BigInteger pw = new BigInteger("1"); for (int ii = 0; ii < vals.size(); ++ii) { BigInteger mul = pw.multiply(new BigInteger("" + vals.get(ii))); answer = answer.add(mul); pw = pw.multiply(THREE); } if (vals.get(vals.size() - 1) == 1) answer = pw.divide(THREE); out.println(answer.toString()); } } } }
Java
["7\n1\n2\n6\n13\n14\n3620\n10000"]
1 second
["1\n3\n9\n13\n27\n6561\n19683"]
null
Java 8
standard input
[ "binary search", "meet-in-the-middle", "greedy", "math" ]
5953b898995a82edfbd42b6c0f7138af
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) β€” the number of queries. Then $$$q$$$ queries follow. The only line of the query contains one integer $$$n$$$ ($$$1 \le n \le 10^4$$$).
1,500
For each query, print such smallest integer $$$m$$$ (where $$$n \le m$$$) that $$$m$$$ is a good number.
standard output
PASSED
e94bbf018d33ba9f4e8ba055e59794e4
train_004.jsonl
1571754900
The only difference between easy and hard versions is the maximum value of $$$n$$$.You are given a positive integer number $$$n$$$. You really love good numbers so you want to find the smallest good number greater than or equal to $$$n$$$.The positive integer is called good if it can be represented as a sum of distinct powers of $$$3$$$ (i.e. no duplicates of powers of $$$3$$$ are allowed).For example: $$$30$$$ is a good number: $$$30 = 3^3 + 3^1$$$, $$$1$$$ is a good number: $$$1 = 3^0$$$, $$$12$$$ is a good number: $$$12 = 3^2 + 3^1$$$, but $$$2$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ ($$$2 = 3^0 + 3^0$$$), $$$19$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representations $$$19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0$$$ are invalid), $$$20$$$ is also not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representation $$$20 = 3^2 + 3^2 + 3^0 + 3^0$$$ is invalid). Note, that there exist other representations of $$$19$$$ and $$$20$$$ as sums of powers of $$$3$$$ but none of them consists of distinct powers of $$$3$$$.For the given positive integer $$$n$$$ find such smallest $$$m$$$ ($$$n \le m$$$) that $$$m$$$ is a good number.You have to answer $$$q$$$ independent queries.
256 megabytes
import java.util.*; import java.io.*; public class Good_Numbers { public static void main(String[] args) { Scanner sc =new Scanner(System.in); PrintWriter pw =new PrintWriter(System.out); int q =sc.nextInt(); while (q-->0) { long h=sc.nextLong(); char[]k =Long.toString(h, 3).toCharArray(); for (int i=k.length-1;i>0;--i) { if (k[i]>='2') { for (int m=i;m<k.length;++m) k[m]='0'; k[i-1]++; } } if (k[0]>='2') { Arrays.fill(k, '0'); String hw=new String(k); pw.println(Long.parseLong(1+hw, 3)); }else { pw.println(Long.parseLong(new String(k), 3)); } } pw.close(); } }
Java
["7\n1\n2\n6\n13\n14\n3620\n10000"]
1 second
["1\n3\n9\n13\n27\n6561\n19683"]
null
Java 8
standard input
[ "binary search", "meet-in-the-middle", "greedy", "math" ]
5953b898995a82edfbd42b6c0f7138af
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) β€” the number of queries. Then $$$q$$$ queries follow. The only line of the query contains one integer $$$n$$$ ($$$1 \le n \le 10^4$$$).
1,500
For each query, print such smallest integer $$$m$$$ (where $$$n \le m$$$) that $$$m$$$ is a good number.
standard output
PASSED
598ca720091dde840db232ff2ad639ab
train_004.jsonl
1571754900
The only difference between easy and hard versions is the maximum value of $$$n$$$.You are given a positive integer number $$$n$$$. You really love good numbers so you want to find the smallest good number greater than or equal to $$$n$$$.The positive integer is called good if it can be represented as a sum of distinct powers of $$$3$$$ (i.e. no duplicates of powers of $$$3$$$ are allowed).For example: $$$30$$$ is a good number: $$$30 = 3^3 + 3^1$$$, $$$1$$$ is a good number: $$$1 = 3^0$$$, $$$12$$$ is a good number: $$$12 = 3^2 + 3^1$$$, but $$$2$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ ($$$2 = 3^0 + 3^0$$$), $$$19$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representations $$$19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0$$$ are invalid), $$$20$$$ is also not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representation $$$20 = 3^2 + 3^2 + 3^0 + 3^0$$$ is invalid). Note, that there exist other representations of $$$19$$$ and $$$20$$$ as sums of powers of $$$3$$$ but none of them consists of distinct powers of $$$3$$$.For the given positive integer $$$n$$$ find such smallest $$$m$$$ ($$$n \le m$$$) that $$$m$$$ is a good number.You have to answer $$$q$$$ independent queries.
256 megabytes
import java.util.*; public class C { static Scanner sc = new Scanner(System.in); static String representation(long a) { StringBuilder r = new StringBuilder(); while (a != 0) { r.append(a % 3); a /= 3; } return "0" + r.reverse().toString(); } static String move(String s) { StringBuilder res = new StringBuilder(); for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '2') { res.setCharAt(i - 1, (char)((int)s.charAt(i - 1) + 1)); for (int j = i; j < s.length(); j++) { res.append('0'); } break; } res.append(s.charAt(i)); } return res.toString(); } static long pow(int a, int p) { long res = 1; for (int i = 0; i < p; i++) res *= a; return res; } static void test() { Long n = sc.nextLong(); String repr = representation(n); while (repr.contains("2")) { repr = move(repr); } long res = 0; for (int i = repr.length() - 1; i >= 0; i--) { if (repr.charAt(i) == '1') { res += pow(3, repr.length() - 1 - i); } } System.out.println(res); } public static void main(String[] args) { Long a = Long.valueOf(0); int q = sc.nextInt(); while (q-- > 0) test(); } }
Java
["7\n1\n2\n6\n13\n14\n3620\n10000"]
1 second
["1\n3\n9\n13\n27\n6561\n19683"]
null
Java 8
standard input
[ "binary search", "meet-in-the-middle", "greedy", "math" ]
5953b898995a82edfbd42b6c0f7138af
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) β€” the number of queries. Then $$$q$$$ queries follow. The only line of the query contains one integer $$$n$$$ ($$$1 \le n \le 10^4$$$).
1,500
For each query, print such smallest integer $$$m$$$ (where $$$n \le m$$$) that $$$m$$$ is a good number.
standard output
PASSED
adf08c6abb9ceab50e69f29a908b67f0
train_004.jsonl
1571754900
The only difference between easy and hard versions is the maximum value of $$$n$$$.You are given a positive integer number $$$n$$$. You really love good numbers so you want to find the smallest good number greater than or equal to $$$n$$$.The positive integer is called good if it can be represented as a sum of distinct powers of $$$3$$$ (i.e. no duplicates of powers of $$$3$$$ are allowed).For example: $$$30$$$ is a good number: $$$30 = 3^3 + 3^1$$$, $$$1$$$ is a good number: $$$1 = 3^0$$$, $$$12$$$ is a good number: $$$12 = 3^2 + 3^1$$$, but $$$2$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ ($$$2 = 3^0 + 3^0$$$), $$$19$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representations $$$19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0$$$ are invalid), $$$20$$$ is also not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representation $$$20 = 3^2 + 3^2 + 3^0 + 3^0$$$ is invalid). Note, that there exist other representations of $$$19$$$ and $$$20$$$ as sums of powers of $$$3$$$ but none of them consists of distinct powers of $$$3$$$.For the given positive integer $$$n$$$ find such smallest $$$m$$$ ($$$n \le m$$$) that $$$m$$$ is a good number.You have to answer $$$q$$$ independent queries.
256 megabytes
//package codeforces.round595; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.StringTokenizer; public class C { public static class FastReader { BufferedReader br; StringTokenizer root; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (root == null || !root.hasMoreTokens()) { try { root = new StringTokenizer(br.readLine()); } catch (Exception addd) { addd.printStackTrace(); } } return root.nextToken(); } int nextInt() { return Integer.parseInt(next()); } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (Exception e) { e.printStackTrace(); } return str; } } public static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); public static FastReader sc = new FastReader(); public static long pow(int base, int exponent) { long result = 1; for (int i = 0; i < exponent; i++) { result = result * base; } return result; } public static void main(String[] args) { int q = sc.nextInt(); while(q > 0) { q--; long n = sc.nextLong(); int maxExp = 0; while(pow(3, maxExp) < n) maxExp++; long bigger = pow(3, maxExp); if(bigger == n) { out.println(bigger); continue; } List <Integer> exponents = new ArrayList<>(); long totalSum = 0; for (int i = 0; i < maxExp; i++) { exponents.add(i); totalSum += pow(3, i); } boolean done = false; while(!done) { int exponentToRemove = -1; for(int i = exponents.size() - 1; i >= 0; i--) { long currentPow = pow(3, exponents.get(i)); if(totalSum - currentPow >= n) { exponentToRemove = i; totalSum -= currentPow; break; } } if(exponentToRemove == -1) { done = true; } else { exponents.remove(exponentToRemove); } } long result = 0; for (int i = 0; i < exponents.size(); i++) { result += pow(3, exponents.get(i)); } out.println(result >= n? result : bigger); } out.flush(); out.close(); } }
Java
["7\n1\n2\n6\n13\n14\n3620\n10000"]
1 second
["1\n3\n9\n13\n27\n6561\n19683"]
null
Java 8
standard input
[ "binary search", "meet-in-the-middle", "greedy", "math" ]
5953b898995a82edfbd42b6c0f7138af
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) β€” the number of queries. Then $$$q$$$ queries follow. The only line of the query contains one integer $$$n$$$ ($$$1 \le n \le 10^4$$$).
1,500
For each query, print such smallest integer $$$m$$$ (where $$$n \le m$$$) that $$$m$$$ is a good number.
standard output
PASSED
296c26edd066839e9fbb54ee6e6c9c89
train_004.jsonl
1571754900
The only difference between easy and hard versions is the maximum value of $$$n$$$.You are given a positive integer number $$$n$$$. You really love good numbers so you want to find the smallest good number greater than or equal to $$$n$$$.The positive integer is called good if it can be represented as a sum of distinct powers of $$$3$$$ (i.e. no duplicates of powers of $$$3$$$ are allowed).For example: $$$30$$$ is a good number: $$$30 = 3^3 + 3^1$$$, $$$1$$$ is a good number: $$$1 = 3^0$$$, $$$12$$$ is a good number: $$$12 = 3^2 + 3^1$$$, but $$$2$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ ($$$2 = 3^0 + 3^0$$$), $$$19$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representations $$$19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0$$$ are invalid), $$$20$$$ is also not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representation $$$20 = 3^2 + 3^2 + 3^0 + 3^0$$$ is invalid). Note, that there exist other representations of $$$19$$$ and $$$20$$$ as sums of powers of $$$3$$$ but none of them consists of distinct powers of $$$3$$$.For the given positive integer $$$n$$$ find such smallest $$$m$$$ ($$$n \le m$$$) that $$$m$$$ is a good number.You have to answer $$$q$$$ independent queries.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.*; import java.io.*; public class Codeforces { 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 long high(long n) { long p = (long)(Math.log(n) / Math.log(3)); return (long)Math.pow(3, p); } public static void main(String[] args) throws IOException { try { FastReader in = new FastReader(); int t = in.nextInt(); while(t-->0) { long n = in.nextLong(); if(n==0||n==1) System.out.println("1"); else { String l = Long.toString(n, 3); //System.out.println(l); int pos0=-1; int pos2=-1; int i = 0; while(i<l.length()) { if(l.charAt(i)=='2') { pos2 = i; break; } i++; } if(pos2==-1) { System.out.println(n); continue; } i = pos2; while(i>=0) { if(l.charAt(i)=='0') { pos0 = i; break; } i--; } if(pos0==-1) { BigInteger bg = new BigInteger("3"); System.out.println(bg.pow(l.length())); continue; } char[] c = l.toCharArray(); c[pos0] ='1'; for(int j=pos0+1;j<l.length();j++) c[j] = '0'; BigInteger str = new BigInteger(new String(c), 3); System.out.println(str.toString(10)); } } }catch(Exception e) {} } }
Java
["7\n1\n2\n6\n13\n14\n3620\n10000"]
1 second
["1\n3\n9\n13\n27\n6561\n19683"]
null
Java 8
standard input
[ "binary search", "meet-in-the-middle", "greedy", "math" ]
5953b898995a82edfbd42b6c0f7138af
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) β€” the number of queries. Then $$$q$$$ queries follow. The only line of the query contains one integer $$$n$$$ ($$$1 \le n \le 10^4$$$).
1,500
For each query, print such smallest integer $$$m$$$ (where $$$n \le m$$$) that $$$m$$$ is a good number.
standard output
PASSED
9e6e6ae17893a0dcfb1a94a78585b8ee
train_004.jsonl
1571754900
The only difference between easy and hard versions is the maximum value of $$$n$$$.You are given a positive integer number $$$n$$$. You really love good numbers so you want to find the smallest good number greater than or equal to $$$n$$$.The positive integer is called good if it can be represented as a sum of distinct powers of $$$3$$$ (i.e. no duplicates of powers of $$$3$$$ are allowed).For example: $$$30$$$ is a good number: $$$30 = 3^3 + 3^1$$$, $$$1$$$ is a good number: $$$1 = 3^0$$$, $$$12$$$ is a good number: $$$12 = 3^2 + 3^1$$$, but $$$2$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ ($$$2 = 3^0 + 3^0$$$), $$$19$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representations $$$19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0$$$ are invalid), $$$20$$$ is also not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representation $$$20 = 3^2 + 3^2 + 3^0 + 3^0$$$ is invalid). Note, that there exist other representations of $$$19$$$ and $$$20$$$ as sums of powers of $$$3$$$ but none of them consists of distinct powers of $$$3$$$.For the given positive integer $$$n$$$ find such smallest $$$m$$$ ($$$n \le m$$$) that $$$m$$$ is a good number.You have to answer $$$q$$$ independent queries.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class Main { //static final long MOD = 998244353; static final long MOD = 1000000007; static final int INF = 1000000007; static boolean[] visited; public static void main(String[] args) throws IOException { FastScanner sc = new FastScanner(); int Q = sc.nextInt(); StringBuilder ans = new StringBuilder(); for (int q = 0; q < Q; q++) { long N = sc.nextLong(); int[] div3 = new int[39]; long pow = 1; for (int i = 0; i < 38; i++) pow *= 3; for (int i = 38; i >= 0; i--) { if (N >= 2*pow) { div3[i] = 2; N -= 2*pow; } else if (N >= pow) { div3[i] = 1; N -= pow; } pow /= 3; } //System.out.println(Arrays.toString(div3)); for (int i = 38; i >= 0; i--) { if (div3[i] == 2) { for (int j = i-1; j >= 0; j--) { div3[j] = 0; } int index = i; while (div3[index] == 2) { div3[index] = 0; div3[index+1] += 1; index++; } } } //System.out.println(Arrays.toString(div3)); long val = 0; for (int i = 0; i < 39; i++) { long power = 1; for (int j = 0; j < i; j++) { power *= 3; } val += (div3[i]*power); } ans.append(val + "\n"); } System.out.print(ans); } static class BinaryIndexedTree { private int[] arr; public BinaryIndexedTree (int N) { arr = new int[N+1]; arr[0] = 0; } //add k to the i-th element. public void add(int 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 int sum(int s_i, int e_i) { return sum(e_i) - sum(s_i); } public int sum(int i) { int total = 0; int node = i; while (node > 0) { total += arr[node]; node -= node & (-node); } return total; } public int[] getArr() { return arr; } } public static long power(long x, long y, long p) { // Initialize result long res = 1; // Update x if it is more // than or equal to p x = x % p; while (y > 0) { // If y is odd, multiply x // with result if((y & 1)==1) res = (res * x) % p; // y must be even now // y = y / 2 y = y >> 1; x = (x * x) % p; } return res; } public static long dist(int[] point, int[] point2) { return (long)(Math.pow((point2[1]-point[1]),2)+Math.pow((point2[0]-point[0]),2)); } public static long gcd(long a, long b) { if (b == 0) return a; else return gcd(b,a%b); } public static int[][] sort(int[][] array) { //Sort an array (immune to quicksort TLE) Random rgen = new Random(); for (int i = 0; i < array.length; i++) { int randomPosition = rgen.nextInt(array.length); int[] temp = array[i]; array[i] = array[randomPosition]; array[randomPosition] = temp; } Arrays.sort(array, new Comparator<int[]>() { @Override public int compare(int[] arr1, int[] arr2) { if (arr1[0] != arr2[0]) return arr1[0]-arr2[0]; else return arr2[1]-arr1[1]; } }); return array; } 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; } } }
Java
["7\n1\n2\n6\n13\n14\n3620\n10000"]
1 second
["1\n3\n9\n13\n27\n6561\n19683"]
null
Java 8
standard input
[ "binary search", "meet-in-the-middle", "greedy", "math" ]
5953b898995a82edfbd42b6c0f7138af
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) β€” the number of queries. Then $$$q$$$ queries follow. The only line of the query contains one integer $$$n$$$ ($$$1 \le n \le 10^4$$$).
1,500
For each query, print such smallest integer $$$m$$$ (where $$$n \le m$$$) that $$$m$$$ is a good number.
standard output
PASSED
cb9d194bf7217b2c2b949d2b5903d51f
train_004.jsonl
1571754900
The only difference between easy and hard versions is the maximum value of $$$n$$$.You are given a positive integer number $$$n$$$. You really love good numbers so you want to find the smallest good number greater than or equal to $$$n$$$.The positive integer is called good if it can be represented as a sum of distinct powers of $$$3$$$ (i.e. no duplicates of powers of $$$3$$$ are allowed).For example: $$$30$$$ is a good number: $$$30 = 3^3 + 3^1$$$, $$$1$$$ is a good number: $$$1 = 3^0$$$, $$$12$$$ is a good number: $$$12 = 3^2 + 3^1$$$, but $$$2$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ ($$$2 = 3^0 + 3^0$$$), $$$19$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representations $$$19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0$$$ are invalid), $$$20$$$ is also not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representation $$$20 = 3^2 + 3^2 + 3^0 + 3^0$$$ is invalid). Note, that there exist other representations of $$$19$$$ and $$$20$$$ as sums of powers of $$$3$$$ but none of them consists of distinct powers of $$$3$$$.For the given positive integer $$$n$$$ find such smallest $$$m$$$ ($$$n \le m$$$) that $$$m$$$ is a good number.You have to answer $$$q$$$ independent queries.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Jasper van Merle */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); C1GoodNumbersEasyVersion solver = new C1GoodNumbersEasyVersion(); solver.solve(1, in, out); out.close(); } static class C1GoodNumbersEasyVersion { public void solve(int testNumber, InputReader in, PrintWriter out) { int q = in.nextInt(); for (int i = 0; i < q; i++) { long n = in.nextLong(); char[] base3 = Long.toString(n, 3).toCharArray(); outer: while (true) { int firstTwo = indexOf(base3, '2'); if (firstTwo == -1) { break; } for (int j = firstTwo; j >= 0; j--) { if (base3[j] == '0') { base3[j] = '1'; for (int k = j + 1; k < base3.length; k++) { base3[k] = '0'; } continue outer; } } base3 = new char[base3.length + 1]; base3[0] = '1'; for (int j = 1; j < base3.length; j++) { base3[j] = '0'; } } out.println(Long.parseLong(new String(base3), 3)); } } private int indexOf(char[] chars, char value) { for (int i = 0; i < chars.length; i++) { if (chars[i] == value) { return i; } } return -1; } } static class InputReader { private BufferedReader br; private StringTokenizer st; public InputReader(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["7\n1\n2\n6\n13\n14\n3620\n10000"]
1 second
["1\n3\n9\n13\n27\n6561\n19683"]
null
Java 8
standard input
[ "binary search", "meet-in-the-middle", "greedy", "math" ]
5953b898995a82edfbd42b6c0f7138af
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) β€” the number of queries. Then $$$q$$$ queries follow. The only line of the query contains one integer $$$n$$$ ($$$1 \le n \le 10^4$$$).
1,500
For each query, print such smallest integer $$$m$$$ (where $$$n \le m$$$) that $$$m$$$ is a good number.
standard output
PASSED
7fb99e2ccbbffa4bc62db83295618e1a
train_004.jsonl
1571754900
The only difference between easy and hard versions is the maximum value of $$$n$$$.You are given a positive integer number $$$n$$$. You really love good numbers so you want to find the smallest good number greater than or equal to $$$n$$$.The positive integer is called good if it can be represented as a sum of distinct powers of $$$3$$$ (i.e. no duplicates of powers of $$$3$$$ are allowed).For example: $$$30$$$ is a good number: $$$30 = 3^3 + 3^1$$$, $$$1$$$ is a good number: $$$1 = 3^0$$$, $$$12$$$ is a good number: $$$12 = 3^2 + 3^1$$$, but $$$2$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ ($$$2 = 3^0 + 3^0$$$), $$$19$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representations $$$19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0$$$ are invalid), $$$20$$$ is also not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representation $$$20 = 3^2 + 3^2 + 3^0 + 3^0$$$ is invalid). Note, that there exist other representations of $$$19$$$ and $$$20$$$ as sums of powers of $$$3$$$ but none of them consists of distinct powers of $$$3$$$.For the given positive integer $$$n$$$ find such smallest $$$m$$$ ($$$n \le m$$$) that $$$m$$$ is a good number.You have to answer $$$q$$$ independent queries.
256 megabytes
/** * @author Juan Sebastian Beltran Rojas * @mail jsbeltran.valhalla@gmail.com * @veredict * @url * @category * @date **/ import java.io.BufferedReader; import java.io.InputStreamReader; public class D { public static void main(String args[]) throws Throwable { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); long[] nums = new long[38]; nums[0] = 1; for (int i = 1; i < nums.length; i++) nums[i] = nums[i - 1] * 3; for (int Q=Integer.parseInt(in.readLine()),q=0; q++<Q; ) { long N = Long.parseLong(in.readLine()); String str = ""; for (int i = 0; N > 2; i++) { str = (N % 3) + str; N /= 3; } if(N>0) str = N + str; boolean ws = true; for (; ws; ) { ws = false; //System.out.println(str); for (int i = str.length() - 1; i >= 0 && !ws; i--) { if (str.charAt(i) == '2') { ws = true; int llevo = 1; str = str.substring(0, i) + "0" + str.substring(i + 1); i = i - 1; for (; i >= 0 && llevo > 0; i--) if (str.charAt(i) == '2') str = str.substring(0, i) + "0" + str.substring(i + 1); else { llevo = 0; int length = str.length(); str = str.substring(0, i) + (char) (str.charAt(i) + 1); for(;i+1<length;i++) str+="0"; } if (llevo > 0) { String sol="1"; for(int k=0;k<str.length();k++) sol +="0"; str=sol; } break; } } } System.out.println(Long.parseLong(str,3)); } } }
Java
["7\n1\n2\n6\n13\n14\n3620\n10000"]
1 second
["1\n3\n9\n13\n27\n6561\n19683"]
null
Java 8
standard input
[ "binary search", "meet-in-the-middle", "greedy", "math" ]
5953b898995a82edfbd42b6c0f7138af
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) β€” the number of queries. Then $$$q$$$ queries follow. The only line of the query contains one integer $$$n$$$ ($$$1 \le n \le 10^4$$$).
1,500
For each query, print such smallest integer $$$m$$$ (where $$$n \le m$$$) that $$$m$$$ is a good number.
standard output
PASSED
0deca3afcf71a6e8a0a47c1d23ba202b
train_004.jsonl
1571754900
The only difference between easy and hard versions is the maximum value of $$$n$$$.You are given a positive integer number $$$n$$$. You really love good numbers so you want to find the smallest good number greater than or equal to $$$n$$$.The positive integer is called good if it can be represented as a sum of distinct powers of $$$3$$$ (i.e. no duplicates of powers of $$$3$$$ are allowed).For example: $$$30$$$ is a good number: $$$30 = 3^3 + 3^1$$$, $$$1$$$ is a good number: $$$1 = 3^0$$$, $$$12$$$ is a good number: $$$12 = 3^2 + 3^1$$$, but $$$2$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ ($$$2 = 3^0 + 3^0$$$), $$$19$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representations $$$19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0$$$ are invalid), $$$20$$$ is also not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representation $$$20 = 3^2 + 3^2 + 3^0 + 3^0$$$ is invalid). Note, that there exist other representations of $$$19$$$ and $$$20$$$ as sums of powers of $$$3$$$ but none of them consists of distinct powers of $$$3$$$.For the given positive integer $$$n$$$ find such smallest $$$m$$$ ($$$n \le m$$$) that $$$m$$$ is a good number.You have to answer $$$q$$$ independent queries.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class A { public static void main(String[] args) throws Exception { // FileInputStream inputStream = new FileInputStream("input.txt"); // FileOutputStream outputStream = new FileOutputStream("output.txt"); InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Solver solver = new Solver(); // int t = in.nextInt(); int t = 1; for (int i = 0 ; i < t ; i++) { solver.solve(1, in, out); } out.close(); } static class Solver { public void solve(int testNumber, InputReader in, PrintWriter out) { BigInteger[] pwrs = new BigInteger[50]; BigInteger three = new BigInteger("3"); for (int i = 0 ; i < 50 ; i++) { pwrs[i] = three.pow(i); } int tests = in.nextInt(); for (int test = 0 ; test < tests ; test++) { BigInteger need = new BigInteger(in.next()); BigInteger now = new BigInteger("0"); int current = 0; while (now.compareTo(need) < 0) { now = now.add(pwrs[current++]); } // out.println(now + " " + need); if (now.compareTo(need) == 0) out.println(now); else { for (int i = current - 1 ; i >= 0 ; i--) { BigInteger tmp = now.subtract(pwrs[i]); if (tmp.compareTo(need) >= 0) { now = tmp; } } if (now.compareTo(need) >= 0) out.println(now); else out.println(pwrs[current - 1]); } } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public float nextFloat() { return Float.parseFloat(next()); } } }
Java
["7\n1\n2\n6\n13\n14\n3620\n10000"]
1 second
["1\n3\n9\n13\n27\n6561\n19683"]
null
Java 8
standard input
[ "binary search", "meet-in-the-middle", "greedy", "math" ]
5953b898995a82edfbd42b6c0f7138af
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) β€” the number of queries. Then $$$q$$$ queries follow. The only line of the query contains one integer $$$n$$$ ($$$1 \le n \le 10^4$$$).
1,500
For each query, print such smallest integer $$$m$$$ (where $$$n \le m$$$) that $$$m$$$ is a good number.
standard output
PASSED
136f641a3443fa084a3eb970eb9e20f0
train_004.jsonl
1571754900
The only difference between easy and hard versions is the maximum value of $$$n$$$.You are given a positive integer number $$$n$$$. You really love good numbers so you want to find the smallest good number greater than or equal to $$$n$$$.The positive integer is called good if it can be represented as a sum of distinct powers of $$$3$$$ (i.e. no duplicates of powers of $$$3$$$ are allowed).For example: $$$30$$$ is a good number: $$$30 = 3^3 + 3^1$$$, $$$1$$$ is a good number: $$$1 = 3^0$$$, $$$12$$$ is a good number: $$$12 = 3^2 + 3^1$$$, but $$$2$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ ($$$2 = 3^0 + 3^0$$$), $$$19$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representations $$$19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0$$$ are invalid), $$$20$$$ is also not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representation $$$20 = 3^2 + 3^2 + 3^0 + 3^0$$$ is invalid). Note, that there exist other representations of $$$19$$$ and $$$20$$$ as sums of powers of $$$3$$$ but none of them consists of distinct powers of $$$3$$$.For the given positive integer $$$n$$$ find such smallest $$$m$$$ ($$$n \le m$$$) that $$$m$$$ is a good number.You have to answer $$$q$$$ independent queries.
256 megabytes
import java.util.*; import java.io.*; public class a { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Solver solver = new Solver(); int t =1 ; t = in.nextInt(); solver.solve(t, in, out); out.close(); } static class Solver { public void solve(int testNumber, InputReader sc, PrintWriter out) { while(testNumber-->0) { long n = sc.nextLong(); long ans = n; List<Long> base3Num = new ArrayList<>(); while(n>0) { base3Num.add(n%3); n /= 3; } boolean flag = false; int lastZero = base3Num.size(); for(int i = base3Num.size()-1;i>=0;i--) { if(base3Num.get(i) == 0) lastZero = i; if(base3Num.get(i) == 2) { flag = true; break; } } // out.println(base3Num + " " + base3Num.size()+ " \n zero " + lastZero ); if(flag == false) { out.println(ans); continue; } ans = 0; for(int i = base3Num.size()-1;i>lastZero;i--) { if(base3Num.get(i)==1) ans += powerOf3(i); } // out.println(ans); ans += powerOf3(lastZero); out.println(ans); } } private long powerOf3(int i ) { long ans = 1; while(i-->0) ans *= 3; return ans; } private static int solve(String in){ int ans = 0; int cnt = 0; int[] preSum = new int[in.length()]; int[] postSum = new int[in.length()]; for(int i=0;i<in.length();i++) { if(i==0) preSum[i]=in.charAt(i)=='('?1:-1; else { preSum[i] = preSum[i-1] + (in.charAt(i)=='('?1:-1); } } // for(int x : preSum) // { // System.out.print(x +" "); // } // System.out.println(" -> " + in ); int postCnt = 0; int firstOpenInx = -1; for(int i = in.length()-1;i>=0;i--) { if(in.charAt(i) == '(') postCnt++; else postCnt--; int preCnt = i>0?preSum[i-1]:0; if(postCnt+preCnt == 0) { System.out.println(i + " -> " + preCnt + " " + postCnt); firstOpenInx = i; } } if(firstOpenInx == -1) return 0; for(int i=firstOpenInx;i<in.length();i++) { System.out.println(in + " " + i + " -> " + firstOpenInx); if(in.charAt(i) == ')') cnt--; else cnt++; if(cnt==0) ans++; } for(int i=0;i<firstOpenInx;i++) { System.out.println(in + " " + i + " -> " + firstOpenInx); if(in.charAt(i) == ')') cnt--; else cnt++; if(cnt==0) ans++; } return ans++; } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public InputReader(InputStream stream) { this.stream = stream; } private int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["7\n1\n2\n6\n13\n14\n3620\n10000"]
1 second
["1\n3\n9\n13\n27\n6561\n19683"]
null
Java 8
standard input
[ "binary search", "meet-in-the-middle", "greedy", "math" ]
5953b898995a82edfbd42b6c0f7138af
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) β€” the number of queries. Then $$$q$$$ queries follow. The only line of the query contains one integer $$$n$$$ ($$$1 \le n \le 10^4$$$).
1,500
For each query, print such smallest integer $$$m$$$ (where $$$n \le m$$$) that $$$m$$$ is a good number.
standard output
PASSED
509e877311f500bac3d08b862ad2a45e
train_004.jsonl
1571754900
The only difference between easy and hard versions is the maximum value of $$$n$$$.You are given a positive integer number $$$n$$$. You really love good numbers so you want to find the smallest good number greater than or equal to $$$n$$$.The positive integer is called good if it can be represented as a sum of distinct powers of $$$3$$$ (i.e. no duplicates of powers of $$$3$$$ are allowed).For example: $$$30$$$ is a good number: $$$30 = 3^3 + 3^1$$$, $$$1$$$ is a good number: $$$1 = 3^0$$$, $$$12$$$ is a good number: $$$12 = 3^2 + 3^1$$$, but $$$2$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ ($$$2 = 3^0 + 3^0$$$), $$$19$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representations $$$19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0$$$ are invalid), $$$20$$$ is also not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representation $$$20 = 3^2 + 3^2 + 3^0 + 3^0$$$ is invalid). Note, that there exist other representations of $$$19$$$ and $$$20$$$ as sums of powers of $$$3$$$ but none of them consists of distinct powers of $$$3$$$.For the given positive integer $$$n$$$ find such smallest $$$m$$$ ($$$n \le m$$$) that $$$m$$$ is a good number.You have to answer $$$q$$$ independent queries.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static int[] ans, adj; public static boolean[] vis; public static ArrayList<Integer> curCycle; public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int q = sc.nextInt(); long[] pow3 = new long[40]; pow3[0] = 1; for (int i = 1; i < 40; ++i) pow3[i] = 3L * pow3[i - 1]; while(q-- > 0) { long n = sc.nextLong(); boolean[] taken = new boolean[40]; long curSum = 0; long ans = Long.MAX_VALUE; long cnt = 50; while (cnt-- > 0) { for (int i = 39; i >= 0; --i) { if (curSum + pow3[i] >= n && !taken[i]) { ans = Math.min(ans, curSum + pow3[i]); } else { if (!taken[i]) { taken[i] = true; curSum += pow3[i]; break; } } } } out.println(ans); } out.close(); out.flush(); } public static int dfs(int u) { if (vis[u] == true) return 0; vis[u] = true; int curAns = 1; if (!vis[adj[u]]) curAns += dfs(adj[u]); ans[u] = curAns; curCycle.add(u); return curAns; } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader f) { br = new BufferedReader(f); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["7\n1\n2\n6\n13\n14\n3620\n10000"]
1 second
["1\n3\n9\n13\n27\n6561\n19683"]
null
Java 8
standard input
[ "binary search", "meet-in-the-middle", "greedy", "math" ]
5953b898995a82edfbd42b6c0f7138af
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) β€” the number of queries. Then $$$q$$$ queries follow. The only line of the query contains one integer $$$n$$$ ($$$1 \le n \le 10^4$$$).
1,500
For each query, print such smallest integer $$$m$$$ (where $$$n \le m$$$) that $$$m$$$ is a good number.
standard output
PASSED
4eacacafa13621330ade7b29fe3115b0
train_004.jsonl
1571754900
The only difference between easy and hard versions is the maximum value of $$$n$$$.You are given a positive integer number $$$n$$$. You really love good numbers so you want to find the smallest good number greater than or equal to $$$n$$$.The positive integer is called good if it can be represented as a sum of distinct powers of $$$3$$$ (i.e. no duplicates of powers of $$$3$$$ are allowed).For example: $$$30$$$ is a good number: $$$30 = 3^3 + 3^1$$$, $$$1$$$ is a good number: $$$1 = 3^0$$$, $$$12$$$ is a good number: $$$12 = 3^2 + 3^1$$$, but $$$2$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ ($$$2 = 3^0 + 3^0$$$), $$$19$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representations $$$19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0$$$ are invalid), $$$20$$$ is also not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representation $$$20 = 3^2 + 3^2 + 3^0 + 3^0$$$ is invalid). Note, that there exist other representations of $$$19$$$ and $$$20$$$ as sums of powers of $$$3$$$ but none of them consists of distinct powers of $$$3$$$.For the given positive integer $$$n$$$ find such smallest $$$m$$$ ($$$n \le m$$$) that $$$m$$$ is a good number.You have to answer $$$q$$$ independent queries.
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.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); C2GoodNumbersHardVersion solver = new C2GoodNumbersHardVersion(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class C2GoodNumbersHardVersion { PrintWriter out; InputReader in; public void solve(int testNumber, InputReader in, PrintWriter out) { this.out = out; this.in = in; long n = nl(); long nn = n; boolean[] vis = new boolean[50]; boolean[] not_ok = new boolean[50]; long[] val = new long[50]; int i = 0; boolean ok = true; while (n >= 3) { long x = n / 3; long y = n % 3; val[i] = y; if (val[i] == 2) ok = false; if (y > 0) vis[i] = true; n = x; i++; } val[i] = n; // pn(Arrays.toString(val)); if (val[i] == 2) ok = false; for (int p = i; p >= 0; p--) { if (val[p] == 2) { for (int q = p + 1; ; q++) { if (val[q] == 0) { val[q] = 1; for (int x = q - 1; x >= 0; x--) val[x] = 0; break; } } break; } } long sum = 0; for (i = 0; i < 50; i++) { if (val[i] == 1) { long prod = 1; for (int j = 0; j < i; j++) prod *= 3; sum += prod; } } /* long ans = 0; while(true){ long xx = nn; boolean ok1 = true; while(xx > 2){ if(xx % 3 == 2) ok1 = false; xx /= 3; } if(xx == 2) ok1 = false; if(ok1){ ans = nn; break; } nn++; }*/ pn(sum); } long nl() { return in.nextLong(); } void pn(long zx) { out.println(zx); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new UnknownError(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new UnknownError(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public long nextLong() { return Long.parseLong(next()); } public String next() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["7\n1\n2\n6\n13\n14\n3620\n10000"]
1 second
["1\n3\n9\n13\n27\n6561\n19683"]
null
Java 8
standard input
[ "binary search", "meet-in-the-middle", "greedy", "math" ]
5953b898995a82edfbd42b6c0f7138af
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) β€” the number of queries. Then $$$q$$$ queries follow. The only line of the query contains one integer $$$n$$$ ($$$1 \le n \le 10^4$$$).
1,500
For each query, print such smallest integer $$$m$$$ (where $$$n \le m$$$) that $$$m$$$ is a good number.
standard output
PASSED
a1d08e3eab8f64456f92122491af7830
train_004.jsonl
1571754900
The only difference between easy and hard versions is the maximum value of $$$n$$$.You are given a positive integer number $$$n$$$. You really love good numbers so you want to find the smallest good number greater than or equal to $$$n$$$.The positive integer is called good if it can be represented as a sum of distinct powers of $$$3$$$ (i.e. no duplicates of powers of $$$3$$$ are allowed).For example: $$$30$$$ is a good number: $$$30 = 3^3 + 3^1$$$, $$$1$$$ is a good number: $$$1 = 3^0$$$, $$$12$$$ is a good number: $$$12 = 3^2 + 3^1$$$, but $$$2$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ ($$$2 = 3^0 + 3^0$$$), $$$19$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representations $$$19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0$$$ are invalid), $$$20$$$ is also not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representation $$$20 = 3^2 + 3^2 + 3^0 + 3^0$$$ is invalid). Note, that there exist other representations of $$$19$$$ and $$$20$$$ as sums of powers of $$$3$$$ but none of them consists of distinct powers of $$$3$$$.For the given positive integer $$$n$$$ find such smallest $$$m$$$ ($$$n \le m$$$) that $$$m$$$ is a good number.You have to answer $$$q$$$ independent queries.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; import java.util.Vector; public class Test { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter(System.out); int Q = Integer.parseInt(br.readLine()); while(Q-- > 0) { ArrayList<Integer> ls = new ArrayList<Integer>(); String s = br.readLine(); BigInteger n = new BigInteger(s); while(n.compareTo(BigInteger.valueOf(0)) == 1) { ls.add(n.mod(BigInteger.valueOf(3)).intValue()); n = n.divide(BigInteger.valueOf(3)); } Collections.reverse(ls); //writer.print(ls); boolean check = true; int index = -1; for(int i = 0; i < ls.size(); i++) if(ls.get(i) == 2) { index = i; check = false; break; } //writer.println(ls); if(check) writer.println(s); else { ArrayList<Integer> ans = new ArrayList<>(); int index1 = -1; for(int i = 0; i <= index-1; i++) if(ls.get(i) == 0) index1 = i; if(index1 == -1) { ans.add(1); for(int i = 0; i < ls.size(); i++) ans.add(0); BigInteger val = new BigInteger("0"); for(int i = ans.size()-1; i >= 0; i--) { BigInteger num1 = new BigInteger(Integer.toString(ans.get(i))); BigInteger num2 = new BigInteger("3"); num2 = num2.pow(ans.size()-1-i); num1 = num1.multiply(num2); val = val.add(num1); } //writer.println(ans); writer.println(val); } else { for(int i = 0; i < index1; i++) ans.add(ls.get(i)); ans.add(1); for(int i = index1+1; i < ls.size(); i++) ans.add(0); BigInteger val = new BigInteger("0"); for(int i = ans.size()-1; i >= 0; i--) { BigInteger num1 = new BigInteger(Integer.toString(ans.get(i))); BigInteger num2 = new BigInteger("3"); num2 = num2.pow(ans.size()-1-i); num1 = num1.multiply(num2); val = val.add(num1); } //writer.println(ans); writer.println(val); } } } br.close(); writer.close(); } }
Java
["7\n1\n2\n6\n13\n14\n3620\n10000"]
1 second
["1\n3\n9\n13\n27\n6561\n19683"]
null
Java 8
standard input
[ "binary search", "meet-in-the-middle", "greedy", "math" ]
5953b898995a82edfbd42b6c0f7138af
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) β€” the number of queries. Then $$$q$$$ queries follow. The only line of the query contains one integer $$$n$$$ ($$$1 \le n \le 10^4$$$).
1,500
For each query, print such smallest integer $$$m$$$ (where $$$n \le m$$$) that $$$m$$$ is a good number.
standard output
PASSED
edc4ea3e97e8040d8bdd2b5bbd60d014
train_004.jsonl
1571754900
The only difference between easy and hard versions is the maximum value of $$$n$$$.You are given a positive integer number $$$n$$$. You really love good numbers so you want to find the smallest good number greater than or equal to $$$n$$$.The positive integer is called good if it can be represented as a sum of distinct powers of $$$3$$$ (i.e. no duplicates of powers of $$$3$$$ are allowed).For example: $$$30$$$ is a good number: $$$30 = 3^3 + 3^1$$$, $$$1$$$ is a good number: $$$1 = 3^0$$$, $$$12$$$ is a good number: $$$12 = 3^2 + 3^1$$$, but $$$2$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ ($$$2 = 3^0 + 3^0$$$), $$$19$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representations $$$19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0$$$ are invalid), $$$20$$$ is also not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representation $$$20 = 3^2 + 3^2 + 3^0 + 3^0$$$ is invalid). Note, that there exist other representations of $$$19$$$ and $$$20$$$ as sums of powers of $$$3$$$ but none of them consists of distinct powers of $$$3$$$.For the given positive integer $$$n$$$ find such smallest $$$m$$$ ($$$n \le m$$$) that $$$m$$$ is a good number.You have to answer $$$q$$$ independent queries.
256 megabytes
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ //package Contests; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * * @author Akhilesh */ public class C1249_1 { public static void main(String[] args) throws IOException{ BufferedReader scan = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(scan.readLine().trim()); test : while(t-- > 0){ long n = Long.parseLong(scan.readLine().trim()); int arr[] = new int[100], index = 0; while(n > 0){ arr[index] = (int)(n%3); n = n/3; index++; } long ans = 0, mul = 1; int pos = -1; for(int i = index-1; i >= 0; i--){ if(arr[i] == 2){ pos = i; break; } } if(pos == -1){ for(int i = 0; i < index; i++){ ans += mul*arr[i]; mul *= 3; } }else{ for(int i = 0; i < pos; i++){ mul *= 3; } int carry = 1; for(int i = pos; i < index; i++){ if(carry == 0){ ans += mul*arr[i]; mul *= 3; }else{ if(arr[i] == 0){ carry = 0; ans += mul*1; mul *= 3; }else{ mul *= 3; } } } if(carry == 1){ ans += mul; } } System.out.println(ans); } } }
Java
["7\n1\n2\n6\n13\n14\n3620\n10000"]
1 second
["1\n3\n9\n13\n27\n6561\n19683"]
null
Java 8
standard input
[ "binary search", "meet-in-the-middle", "greedy", "math" ]
5953b898995a82edfbd42b6c0f7138af
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) β€” the number of queries. Then $$$q$$$ queries follow. The only line of the query contains one integer $$$n$$$ ($$$1 \le n \le 10^4$$$).
1,500
For each query, print such smallest integer $$$m$$$ (where $$$n \le m$$$) that $$$m$$$ is a good number.
standard output
PASSED
c3fe1b0b65c36d56f38323971003ed24
train_004.jsonl
1571754900
The only difference between easy and hard versions is the maximum value of $$$n$$$.You are given a positive integer number $$$n$$$. You really love good numbers so you want to find the smallest good number greater than or equal to $$$n$$$.The positive integer is called good if it can be represented as a sum of distinct powers of $$$3$$$ (i.e. no duplicates of powers of $$$3$$$ are allowed).For example: $$$30$$$ is a good number: $$$30 = 3^3 + 3^1$$$, $$$1$$$ is a good number: $$$1 = 3^0$$$, $$$12$$$ is a good number: $$$12 = 3^2 + 3^1$$$, but $$$2$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ ($$$2 = 3^0 + 3^0$$$), $$$19$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representations $$$19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0$$$ are invalid), $$$20$$$ is also not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representation $$$20 = 3^2 + 3^2 + 3^0 + 3^0$$$ is invalid). Note, that there exist other representations of $$$19$$$ and $$$20$$$ as sums of powers of $$$3$$$ but none of them consists of distinct powers of $$$3$$$.For the given positive integer $$$n$$$ find such smallest $$$m$$$ ($$$n \le m$$$) that $$$m$$$ is a good number.You have to answer $$$q$$$ independent queries.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.math.BigInteger; 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) throws IOException { 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 boolean check(long x) { while(x>0) { long y=x%3; if(y==2) return false; x/=3; } return true; } public int find(StringBuilder buf,int index) { for(int i=index;i<buf.length();i++) { if(buf.charAt(i)!='1'&&buf.charAt(i)!='2') return i; } return buf.length(); } public void solve(int testNumber, InputReader sc, PrintWriter out) throws IOException { int Q=sc.nextInt(); int max=38; long[] pow=new long[max+1]; pow[0]=1; for(int i=1;i<=max;i++) { pow[i]=pow[i-1]*3l; } while(Q-->0) { long n=sc.nextLong(); if(check(n)) { out.println(n); continue; } String temp=Long.toString(n,3); StringBuilder buf=new StringBuilder(temp); buf=buf.reverse(); for(int i=0;i<buf.length();i++) { if(buf.charAt(i)=='0'||buf.charAt(i)=='1') continue; int index=find(buf,i+1); n=n/pow[index]*pow[index]+pow[index]; temp=Long.toString(n, 3); buf=new StringBuilder(temp); buf=buf.reverse(); } out.println(n); } } } static class InputReader{ StreamTokenizer tokenizer; public InputReader(InputStream stream){ tokenizer=new StreamTokenizer(new BufferedReader(new InputStreamReader(stream))); tokenizer.ordinaryChars(33,126); tokenizer.wordChars(33,126); } public String next() throws IOException { tokenizer.nextToken(); return tokenizer.sval; } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public boolean hasNext() throws IOException { int res=tokenizer.nextToken(); tokenizer.pushBack(); return res!=tokenizer.TT_EOF; } public double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } public BigInteger nextBigInteger() throws IOException { return new BigInteger(next()); } } }
Java
["7\n1\n2\n6\n13\n14\n3620\n10000"]
1 second
["1\n3\n9\n13\n27\n6561\n19683"]
null
Java 8
standard input
[ "binary search", "meet-in-the-middle", "greedy", "math" ]
5953b898995a82edfbd42b6c0f7138af
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) β€” the number of queries. Then $$$q$$$ queries follow. The only line of the query contains one integer $$$n$$$ ($$$1 \le n \le 10^4$$$).
1,500
For each query, print such smallest integer $$$m$$$ (where $$$n \le m$$$) that $$$m$$$ is a good number.
standard output
PASSED
ddc05fe2a8941d1a24f1522ea4277728
train_004.jsonl
1571754900
The only difference between easy and hard versions is the maximum value of $$$n$$$.You are given a positive integer number $$$n$$$. You really love good numbers so you want to find the smallest good number greater than or equal to $$$n$$$.The positive integer is called good if it can be represented as a sum of distinct powers of $$$3$$$ (i.e. no duplicates of powers of $$$3$$$ are allowed).For example: $$$30$$$ is a good number: $$$30 = 3^3 + 3^1$$$, $$$1$$$ is a good number: $$$1 = 3^0$$$, $$$12$$$ is a good number: $$$12 = 3^2 + 3^1$$$, but $$$2$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ ($$$2 = 3^0 + 3^0$$$), $$$19$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representations $$$19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0$$$ are invalid), $$$20$$$ is also not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representation $$$20 = 3^2 + 3^2 + 3^0 + 3^0$$$ is invalid). Note, that there exist other representations of $$$19$$$ and $$$20$$$ as sums of powers of $$$3$$$ but none of them consists of distinct powers of $$$3$$$.For the given positive integer $$$n$$$ find such smallest $$$m$$$ ($$$n \le m$$$) that $$$m$$$ is a good number.You have to answer $$$q$$$ independent queries.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; @SuppressWarnings("Duplicates") // author @mdazmat9 public class Main{ static Scanner sc = new Scanner(System.in); static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) throws IOException { int test = 1; test=sc.nextInt(); ArrayList<Long> a=new ArrayList<>(); ArrayList<Long> b=new ArrayList<>(); a.add(1l); long num=3; for(int i=2;i<=19;i++){ a.add(num); num=num*3; } long last=1<<19; for(int mask=1;mask<last;mask++){ long sum=0; for(int i=a.size()-1;i>=0;i--){ long p=(mask>>i)&1; if(p==1)sum+=a.get(i); } list1.add(sum); seta.add(sum); } //out.println(seta); last=1l<<19; for(int i=1;i<=19;i++){ b.add(num); num=num*3; } for(int mask=1;mask<last;mask++){ long sum=0; for(int i=b.size()-1;i>=0;i--){ long p=(mask>>i)&1; if(p==1)sum+=b.get(i); } if(sum>=0) { list2.add(sum); setb.add(sum); } } Collections.sort(list1); Collections.sort(list2); for (int ind = 0; ind < test; ind++) { solve(); } out.flush(); } static TreeSet<Long> seta=new TreeSet<>(); static TreeSet<Long> setb=new TreeSet<>(); static ArrayList<Long> list1=new ArrayList<>(); static ArrayList<Long> list2=new ArrayList<>(); static void solve(){ long n=sc.nextLong(); long check=list1.get(list1.size()-1); if(n<=check){ long ans=seta.ceiling(n); out.println(ans); return; } if(setb.contains(n)){ out.println(n); return; } long lower=setb.floor(n); long upper=Long.MAX_VALUE; if(setb.higher(n)!=null){ upper=setb.higher(n); } int low=0,high=list1.size()-1; while (low<=high){ int mid=(low+high)/2; if(lower+list1.get(mid)>=n){ upper=Math.min(upper,lower+list1.get(mid)); high=mid-1; }else { low=mid+1; } } long val=9223372036854775807l; if(upper==val){ out.println(1350851717672992090l-1); } else out.println(upper); } static int[] intarray(int n){ int [] a=new int[n];for(int i=0;i<n;i++)a[i]=sc.nextInt();return a; } static void sort(int[]a){ shuffle(a);Arrays.sort(a);} static void sort(long[]a){ shuffle(a);Arrays.sort(a);} static long[] longarray(int n){ long [] a=new long[n];for(int i=0;i<n;i++)a[i]=sc.nextLong();return a; } static ArrayList<Integer> intlist(int n){ArrayList<Integer> list=new ArrayList<>();for(int i=0;i<n;i++)list.add(sc.nextInt());return list; } static ArrayList<Long> longlist(int n){ArrayList<Long> list=new ArrayList<>();for(int i=0;i<n;i++)list.add(sc.nextLong());return list; } static int[][] int2darray(int n,int m){ int [][] a=new int[n][m];for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ a[i][j]=sc.nextInt(); } }return a; } static long[][] long2darray(int n,int m){ long [][] a=new long[n][m];for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ a[i][j]=sc.nextLong(); } }return a; } static char[][] char2darray(int n,int m){ char [][] a=new char[n][m];for(int i=0;i<n;i++){ String s=sc.next(); a[i]=s.toCharArray(); }return a; } static double pi=3.14159265358979323846264; public static double logb( double a, double b ) {return Math.log(a) / Math.log(b); } static long fast_pow(long a, long b,long abs) { if(b == 0) return 1L; long val = fast_pow(a, b / 2,abs); if(b % 2 == 0) return val * val % abs; else return val * val % abs * a % abs; } static long abs = (long)1e9 + 7; static void shuffle(int[] a) { int n = a.length;for(int i = 0; i < n; i++) { int r = i + (int) (Math.random() * (n - i));int tmp = a[i];a[i] = a[r];a[r] = tmp; } } static void shuffle(long[] a) { int n = a.length;for(int i = 0; i < n; i++) { int r = i + (int) (Math.random() * (n - i));long tmp = a[i];a[i] = a[r];a[r] = tmp; } } static long gcd(long a , long b) { if(b == 0) return a; return gcd(b , a % b); } } class Scanner { public BufferedReader reader; public StringTokenizer st; public Scanner(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); st = null; } public String next() { while (st == null || !st.hasMoreTokens()) { try { String line = reader.readLine(); if (line == null) return null; st = new StringTokenizer(line); } catch (Exception e) { throw (new RuntimeException()); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } }
Java
["7\n1\n2\n6\n13\n14\n3620\n10000"]
1 second
["1\n3\n9\n13\n27\n6561\n19683"]
null
Java 8
standard input
[ "binary search", "meet-in-the-middle", "greedy", "math" ]
5953b898995a82edfbd42b6c0f7138af
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) β€” the number of queries. Then $$$q$$$ queries follow. The only line of the query contains one integer $$$n$$$ ($$$1 \le n \le 10^4$$$).
1,500
For each query, print such smallest integer $$$m$$$ (where $$$n \le m$$$) that $$$m$$$ is a good number.
standard output
PASSED
73bf3cabef2314cf8391593362a489d1
train_004.jsonl
1571754900
The only difference between easy and hard versions is the maximum value of $$$n$$$.You are given a positive integer number $$$n$$$. You really love good numbers so you want to find the smallest good number greater than or equal to $$$n$$$.The positive integer is called good if it can be represented as a sum of distinct powers of $$$3$$$ (i.e. no duplicates of powers of $$$3$$$ are allowed).For example: $$$30$$$ is a good number: $$$30 = 3^3 + 3^1$$$, $$$1$$$ is a good number: $$$1 = 3^0$$$, $$$12$$$ is a good number: $$$12 = 3^2 + 3^1$$$, but $$$2$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ ($$$2 = 3^0 + 3^0$$$), $$$19$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representations $$$19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0$$$ are invalid), $$$20$$$ is also not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representation $$$20 = 3^2 + 3^2 + 3^0 + 3^0$$$ is invalid). Note, that there exist other representations of $$$19$$$ and $$$20$$$ as sums of powers of $$$3$$$ but none of them consists of distinct powers of $$$3$$$.For the given positive integer $$$n$$$ find such smallest $$$m$$$ ($$$n \le m$$$) that $$$m$$$ is a good number.You have to answer $$$q$$$ independent queries.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String args[]){ InputReader obj = new InputReader(System.in); int t=obj.nextInt(); for(int l=0;l<t;l++){ long n=obj.nextLong(); if(n==1e18){ String a="1350851717672992089"; System.out.println(a); continue; } StringBuilder str = new StringBuilder(); while(n!=0){ str.append(n%3); n/=3; } //System.out.println(str); for(int j=str.length()-1;j>=0;j--){ if(str.charAt(j)=='2'){ for(int k=j;k>=0;k--){ str.setCharAt(k,'0'); } int h=j+1; boolean chk=false; if(h>=str.length()){ chk=true; } while(h<str.length() && str.charAt(h)-47==2){ str.setCharAt(h,'0'); h++; if(h==str.length()){ chk=true; break; } } if(chk){ str.append(1); } else{ str.setCharAt(h,'1'); } break; } } //System.out.println(str); long sum=0; long pow=1; for(int j=0;j<str.length();j++){ sum+=pow*(long)(str.charAt(j)-48); pow*=3; } System.out.println(sum); } } public static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["7\n1\n2\n6\n13\n14\n3620\n10000"]
1 second
["1\n3\n9\n13\n27\n6561\n19683"]
null
Java 8
standard input
[ "binary search", "meet-in-the-middle", "greedy", "math" ]
5953b898995a82edfbd42b6c0f7138af
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) β€” the number of queries. Then $$$q$$$ queries follow. The only line of the query contains one integer $$$n$$$ ($$$1 \le n \le 10^4$$$).
1,500
For each query, print such smallest integer $$$m$$$ (where $$$n \le m$$$) that $$$m$$$ is a good number.
standard output
PASSED
79b6902bd003ebff5a7899a9cafe3279
train_004.jsonl
1571754900
The only difference between easy and hard versions is the maximum value of $$$n$$$.You are given a positive integer number $$$n$$$. You really love good numbers so you want to find the smallest good number greater than or equal to $$$n$$$.The positive integer is called good if it can be represented as a sum of distinct powers of $$$3$$$ (i.e. no duplicates of powers of $$$3$$$ are allowed).For example: $$$30$$$ is a good number: $$$30 = 3^3 + 3^1$$$, $$$1$$$ is a good number: $$$1 = 3^0$$$, $$$12$$$ is a good number: $$$12 = 3^2 + 3^1$$$, but $$$2$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ ($$$2 = 3^0 + 3^0$$$), $$$19$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representations $$$19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0$$$ are invalid), $$$20$$$ is also not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representation $$$20 = 3^2 + 3^2 + 3^0 + 3^0$$$ is invalid). Note, that there exist other representations of $$$19$$$ and $$$20$$$ as sums of powers of $$$3$$$ but none of them consists of distinct powers of $$$3$$$.For the given positive integer $$$n$$$ find such smallest $$$m$$$ ($$$n \le m$$$) that $$$m$$$ is a good number.You have to answer $$$q$$$ independent queries.
256 megabytes
import java.math.BigInteger; import java.util.*; import java.io.*; public class Main3 { static PrintWriter pr; static Scanner scan; static BufferedReader br; static StringTokenizer st; public static void main(String args[]) throws Exception { pr = new PrintWriter(System.out); scan = new Scanner(System.in); br = new BufferedReader(new InputStreamReader(System.in)); int q = inputInt(); while(q--!=0){ long m = inputLong(); BigInteger a = BigInteger.valueOf(m); BigInteger[] b = new BigInteger[39]; BigInteger ans = BigInteger.valueOf(-1); int prev=39; while(a.longValue()!=0 && ans.longValue()==-1){ int p = (int)(Math.log(a.longValue())/Math.log(3)); if(prev==p){ for(int i=p+1;i<39;i++){ if(b[i]==null){ ans = BigInteger.valueOf(3).pow(i); while(i!=39){ if(b[i]!=null) ans = ans.add(b[i]); i++; } pr.println(ans); break; } } break; } b[p]=BigInteger.valueOf(3).pow(p); a=a.subtract(b[p]); prev = p; } if(a.longValue()==0){ pr.println(m); } } pr.close(); } public static int inputInt() throws IOException{ return Integer.parseInt(br.readLine()); } public static long inputLong() throws IOException{ return Long.parseLong(br.readLine()); } public static String inputString() throws IOException{ return br.readLine(); } public static int[] intArray(int n) throws IOException{ int a[] = new int[n]; st = new StringTokenizer(br.readLine()); for(int i=0;i<n;i++){ a[i] = Integer.parseInt(st.nextToken()); } return a; } public static long[] longArray(int n) throws IOException{ long a[] = new long[n]; st = new StringTokenizer(br.readLine()); for(int i=0;i<n;i++){ a[i] = Long.parseLong(st.nextToken()); } return a; } public static double[] doubleArray(int n) throws IOException{ double a[] = new double[n]; st = new StringTokenizer(br.readLine()); for(int i=0;i<n;i++){ a[i] = Double.parseDouble(st.nextToken()); } return a; } public static String[] stringArray(int n) throws IOException{ String a[] = new String[n]; st = new StringTokenizer(br.readLine()); for(int i=0;i<n;i++){ a[i] = st.nextToken(); } return a; } public static long gcd(long a,long b){ if(b==0){ return a; } else{ return gcd(b,a%b); } } }
Java
["7\n1\n2\n6\n13\n14\n3620\n10000"]
1 second
["1\n3\n9\n13\n27\n6561\n19683"]
null
Java 8
standard input
[ "binary search", "meet-in-the-middle", "greedy", "math" ]
5953b898995a82edfbd42b6c0f7138af
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) β€” the number of queries. Then $$$q$$$ queries follow. The only line of the query contains one integer $$$n$$$ ($$$1 \le n \le 10^4$$$).
1,500
For each query, print such smallest integer $$$m$$$ (where $$$n \le m$$$) that $$$m$$$ is a good number.
standard output
PASSED
6b817b0eb2e9e346d76241f5fade667b
train_004.jsonl
1571754900
The only difference between easy and hard versions is the maximum value of $$$n$$$.You are given a positive integer number $$$n$$$. You really love good numbers so you want to find the smallest good number greater than or equal to $$$n$$$.The positive integer is called good if it can be represented as a sum of distinct powers of $$$3$$$ (i.e. no duplicates of powers of $$$3$$$ are allowed).For example: $$$30$$$ is a good number: $$$30 = 3^3 + 3^1$$$, $$$1$$$ is a good number: $$$1 = 3^0$$$, $$$12$$$ is a good number: $$$12 = 3^2 + 3^1$$$, but $$$2$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ ($$$2 = 3^0 + 3^0$$$), $$$19$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representations $$$19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0$$$ are invalid), $$$20$$$ is also not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representation $$$20 = 3^2 + 3^2 + 3^0 + 3^0$$$ is invalid). Note, that there exist other representations of $$$19$$$ and $$$20$$$ as sums of powers of $$$3$$$ but none of them consists of distinct powers of $$$3$$$.For the given positive integer $$$n$$$ find such smallest $$$m$$$ ($$$n \le m$$$) that $$$m$$$ is a good number.You have to answer $$$q$$$ independent queries.
256 megabytes
import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; import java.util.Arrays; import java.util.InputMismatchException; import java.util.*; import java.io.*; import java.math.*; public class Main6{ static class Pair { int x; int y; int z; int d; public Pair(int x,int y,int z,int d) { this.x= x; this.y= y; this.z=z; this.d=d; } @Override public int hashCode() { final int temp = 14; int ans = 1; ans =x*31+y*13; return ans; } // Equal objects must produce the same // hash code as long as they are equal @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null) { return false; } if (this.getClass() != o.getClass()) { return false; } Pair other = (Pair)o; if (this.x != other.x || this.y!=other.y) { return false; } return true; } } static class Pair1 { String x; int y; int z; } static class Compare { static void compare(Pair arr[], int n) { // Comparator to sort the pair according to second element Arrays.sort(arr, new Comparator<Pair>() { @Override public int compare(Pair p1, Pair p2) { if(p1.x>p2.x) { return 1; } else if(p1.x<p2.x) { return -1; } else { if(p1.y>p2.y) { return 1; } else if(p1.y<p2.y) { return -1; } else { if(p1.z>p2.z) { return 1; } else if(p1.z<p2.z) { return -1; } else return 0; } } } }); } } public static long pow(long a, long b) { long result=1; while(b>0) { if (b % 2 != 0) { result=(result*a)%1000000007; b--; } a=(a*a)%1000000007; b /= 2; } return result; } public static long fact(long num) { long value=1; int i=0; for(i=2;i<num;i++) { value=((value%mod)*i%mod)%mod; } return value; } public static long gcd(long a, long b) { if (a == 0) return b; return gcd(b%a, a); } /* public static long lcm(long a,long b) { return a * (b / gcd(a, b)); } */ public static long sum(int h) { return (h*(h+1)/2); } /* public static void dfs(int parent,boolean[] visited,int[] dp) { ArrayList<Integer> arr=new ArrayList<Integer>(); arr=graph.get(parent); visited[parent]=true; for(int i=0;i<arr.size();i++) { int num=(int)arr.get(i); if(visited[num]==false) { dfs(num,visited,dp); } dp[parent]=Math.max(dp[num]+1,dp[parent]); } } // static int flag1=0; static int[] dis;*/ static int mod=1000000007; static ArrayList<ArrayList<Integer>> graph; static ArrayList<ArrayList<Integer>> g; /* public static void bfs(int num,int size) { boolean[] visited=new boolean[size+1]; Queue<Integer> q=new LinkedList<>(); q.add(num); ans[num]=1; visited[num]=true; while(!q.isEmpty()) { int x=q.poll(); ArrayList<Integer> al=graph.get(x); for(int i=0;i<al.size();i++) { int y=al.get(i); if(visited[y]==false) { q.add(y); ans[y]=ans[x]+1; visited[y]=true; } } } } static int[] ans;*/ // static int[] a; public static int[] sort(int[] a) { int n=a.length; ArrayList<Integer> ar=new ArrayList<>(); for(int i=0;i<a.length;i++) { ar.add(a[i]); } Collections.sort(ar); for(int i=0;i<n;i++) { a[i]=ar.get(i); } return a; } static class pqcomparator implements Comparator<Pair> { public int compare(Pair p1 ,Pair p2) { if(p1.y>p2.y) { return -1; } else return 1; } } public static void dfs(int parent,boolean[] visited) { ArrayList<Integer> arr=new ArrayList<Integer>(); arr=graph.get(parent); visited[parent]=true; ar.add(parent); count++; for(int i=0;i<arr.size();i++) { int num=(int)arr.get(i); if(visited[num]==false) { dfs(num,visited); } } } static int count=0; static ArrayList<Integer> ar; static public void main(String args[])throws IOException { int t=i(); StringBuilder sb=new StringBuilder(); long[] a=new long[100]; a[0]=1; TreeSet<Long> ts=new TreeSet<>(); ts.add(1L); for(int i=1;;i++) { a[i]=a[i-1]*3; if(a[i]>0) ts.add(a[i]); if(a[i]<=0) break; } while(t-->0) { long n=l(); int ans=0; long number=n; int flag=0; ArrayList<Long> ar=new ArrayList<>(); while(number>0) { if(ts.contains(number)==true) { ar.add(number); break; } else { Long num=ts.lower(number); if(num!=null) { number-=num; ar.add(num); } } } TreeMap<Long,Integer> hash=new TreeMap<>(); for(int i=0;i<ar.size();i++) { if(hash.containsKey(ar.get(i))==false) hash.put(ar.get(i),1); else hash.put(ar.get(i),hash.get(ar.get(i))+1); } long tmp=0; for(Map.Entry<Long,Integer> entry: hash.entrySet()) { long num=entry.getKey(); long value=entry.getValue(); if(value>1) { tmp=num; } } if(tmp==0) { sb.append(n+"\n"); } else { long ans2=0; long[] b=new long[100]; b[0]=1; for(int i=1;i<=100;i++) { b[i]=b[i-1]*3; if(b[i]>=tmp && hash.containsKey(b[i])==false) { ans2+=b[i]; break; } } if(ans2>=n) sb.append(ans2+"\n"); else { for(Map.Entry<Long,Integer> entry: hash.entrySet()) { long num=entry.getKey(); long value=entry.getValue(); if(value==1 && num>ans2) { ans2+=num; } } sb.append(ans2+"\n"); } } } System.out.print(sb.toString()); } static boolean areParenthesisBalanced(char exp[]) { Stack<Character> st=new Stack<>(); for(int i=0;i<exp.length;i++) { if (exp[i] == '(') st.push(exp[i]); if (exp[i] == ')') { if (st.isEmpty()) { return false; } else if ( !isMatchingPair(st.pop(), exp[i]) ) { return false; } } } if (st.isEmpty()) return true; else { return false; } } static boolean isMatchingPair(char character1, char character2) { if (character1 == '(' && character2 == ')') return true; else return false; } /**/ static InputReader in=new InputReader(System.in); static OutputWriter out=new OutputWriter(System.out); public static long l() { String s=in.String(); return Long.parseLong(s); } public static void pln(String value) { System.out.println(value); } public static int i() { return in.Int(); } public static String s() { return in.String(); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars== -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int Int() { 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 String() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return String(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } } class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = in.Int(); return array; } }
Java
["7\n1\n2\n6\n13\n14\n3620\n10000"]
1 second
["1\n3\n9\n13\n27\n6561\n19683"]
null
Java 8
standard input
[ "binary search", "meet-in-the-middle", "greedy", "math" ]
5953b898995a82edfbd42b6c0f7138af
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) β€” the number of queries. Then $$$q$$$ queries follow. The only line of the query contains one integer $$$n$$$ ($$$1 \le n \le 10^4$$$).
1,500
For each query, print such smallest integer $$$m$$$ (where $$$n \le m$$$) that $$$m$$$ is a good number.
standard output
PASSED
b4a0e086b7805d7d4d422d0a8881857f
train_004.jsonl
1571754900
The only difference between easy and hard versions is the maximum value of $$$n$$$.You are given a positive integer number $$$n$$$. You really love good numbers so you want to find the smallest good number greater than or equal to $$$n$$$.The positive integer is called good if it can be represented as a sum of distinct powers of $$$3$$$ (i.e. no duplicates of powers of $$$3$$$ are allowed).For example: $$$30$$$ is a good number: $$$30 = 3^3 + 3^1$$$, $$$1$$$ is a good number: $$$1 = 3^0$$$, $$$12$$$ is a good number: $$$12 = 3^2 + 3^1$$$, but $$$2$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ ($$$2 = 3^0 + 3^0$$$), $$$19$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representations $$$19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0$$$ are invalid), $$$20$$$ is also not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representation $$$20 = 3^2 + 3^2 + 3^0 + 3^0$$$ is invalid). Note, that there exist other representations of $$$19$$$ and $$$20$$$ as sums of powers of $$$3$$$ but none of them consists of distinct powers of $$$3$$$.For the given positive integer $$$n$$$ find such smallest $$$m$$$ ($$$n \le m$$$) that $$$m$$$ is a good number.You have to answer $$$q$$$ independent queries.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; import java.math.*; //BigInteger A; //A= BigInteger.valueOf(54); //ArrayList<Integer> a=new ArrayList<>(); //TreeSet<Integer> ts=new TreeSet<>(); //HashMap<Integer,Integer> hm=new HashMap<>(); //PriorityQueue<Integer> pq=new PriorityQueue<>(); public final class P3A { public static long pow(int a,int b) { if(b==0) return 1; long x=pow(a,b/2); if(b%2==0) return x*x; else return a*x*x; } public static void main(String[]args)throws IOException { FastReader ob=new FastReader(); int t=ob.nextInt(); while(t-->0) { long n=ob.nextLong();long n1=n; Stack<Integer> s=new Stack(); while(n!=0) { s.push((int)(n%3)); n=n/3; } int a[]=new int[s.size()];int k=0; while(!s.isEmpty()) a[k++]=s.pop(); /*for(int i=0;i<a.length;i++) System.out.print(a[i]+" "); System.out.println();*/ int pos=-1; for(int i=0;i<a.length;i++) { if(a[i]==2) {pos=i;break;} } if(pos==-1) System.out.println(n1); else { int pos1=-1; for(int i=pos-1;i>=0;i--) { if(a[i]==0) {a[i]=1;pos1=i;break;} } if(pos1==-1) System.out.println(pow(3,a.length)); else { long ans=0; for(int i=pos1;i>=0;i--) ans+=a[i]*pow(3,(a.length-i-1)); System.out.println(ans); } } } } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public String nextLine() { String s=""; try { s=br.readLine(); } catch (IOException e) { e.printStackTrace(); } return s; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } }
Java
["7\n1\n2\n6\n13\n14\n3620\n10000"]
1 second
["1\n3\n9\n13\n27\n6561\n19683"]
null
Java 8
standard input
[ "binary search", "meet-in-the-middle", "greedy", "math" ]
5953b898995a82edfbd42b6c0f7138af
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) β€” the number of queries. Then $$$q$$$ queries follow. The only line of the query contains one integer $$$n$$$ ($$$1 \le n \le 10^4$$$).
1,500
For each query, print such smallest integer $$$m$$$ (where $$$n \le m$$$) that $$$m$$$ is a good number.
standard output
PASSED
1bd7be4be979114d6dc78b79975fa380
train_004.jsonl
1571754900
The only difference between easy and hard versions is the maximum value of $$$n$$$.You are given a positive integer number $$$n$$$. You really love good numbers so you want to find the smallest good number greater than or equal to $$$n$$$.The positive integer is called good if it can be represented as a sum of distinct powers of $$$3$$$ (i.e. no duplicates of powers of $$$3$$$ are allowed).For example: $$$30$$$ is a good number: $$$30 = 3^3 + 3^1$$$, $$$1$$$ is a good number: $$$1 = 3^0$$$, $$$12$$$ is a good number: $$$12 = 3^2 + 3^1$$$, but $$$2$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ ($$$2 = 3^0 + 3^0$$$), $$$19$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representations $$$19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0$$$ are invalid), $$$20$$$ is also not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representation $$$20 = 3^2 + 3^2 + 3^0 + 3^0$$$ is invalid). Note, that there exist other representations of $$$19$$$ and $$$20$$$ as sums of powers of $$$3$$$ but none of them consists of distinct powers of $$$3$$$.For the given positive integer $$$n$$$ find such smallest $$$m$$$ ($$$n \le m$$$) that $$$m$$$ is a good number.You have to answer $$$q$$$ independent queries.
256 megabytes
import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; public class GoodNumber { public static void main( String[] args ) { // System.out.println( Long.MAX_VALUE ); // getMinNumberIn3Pow(1000000000000000000L); Scanner scanner = new Scanner( System.in ); int t = Integer.parseInt( scanner.nextLine() ); ArrayList<BigDecimal> res = new ArrayList<BigDecimal>(); while( t-- > 0 ) { long number = Long.parseLong( scanner.nextLine() ); res.add( getGoodNumber( number ) ); } for( BigDecimal goodNumber : res ) { System.out.println( goodNumber ); } } private static BigDecimal getGoodNumber( long num ) { StringBuilder ternary = new StringBuilder(); long current = num; while( current > 0L ) { ternary.append( current % 3L ); current /= 3L; } return getGreaterWith3Base( ternary, num ); } private static BigDecimal getGreaterWith3Base( StringBuilder num, long originalNum ) { num.reverse(); BigDecimal number = new BigDecimal( "0" ); int size = num.length(); int index; boolean twoFound = false; for( index = 0; index < size; index++ ) { if( num.charAt( index ) == '2' ) { twoFound = true; break; } } if( !twoFound ) return new BigDecimal( originalNum ); int maxIndex =0; boolean changed = false; for( int i = index-1; i >= 0; i--) { if( num.charAt( i ) == '0' ) { num.setCharAt( i, '1' ); maxIndex =i; changed = true; break; } } for(int i=maxIndex+1;i<size;i++) num.setCharAt( i, '0' ); if( !changed ) { return getXPowY( 3, size ); } else { for( int i = 0,j=size-1; i <size; i++ ) { number = number.add( new BigDecimal(String.valueOf( num.charAt( i ) )).multiply( getXPowY( 3, j-- ) ) ); } } return number; } private static BigDecimal getXPowY( int x, int y ) { BigDecimal num1 = new BigDecimal( x ); BigDecimal res = new BigDecimal( 1 ); while(y>0) { if(y%2!=0) res =res.multiply( num1 ); num1 = num1.multiply( num1 ); y=y/2; } return res; } }
Java
["7\n1\n2\n6\n13\n14\n3620\n10000"]
1 second
["1\n3\n9\n13\n27\n6561\n19683"]
null
Java 8
standard input
[ "binary search", "meet-in-the-middle", "greedy", "math" ]
5953b898995a82edfbd42b6c0f7138af
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) β€” the number of queries. Then $$$q$$$ queries follow. The only line of the query contains one integer $$$n$$$ ($$$1 \le n \le 10^4$$$).
1,500
For each query, print such smallest integer $$$m$$$ (where $$$n \le m$$$) that $$$m$$$ is a good number.
standard output
PASSED
d530541dde455de51dd76f56edd23867
train_004.jsonl
1571754900
The only difference between easy and hard versions is the maximum value of $$$n$$$.You are given a positive integer number $$$n$$$. You really love good numbers so you want to find the smallest good number greater than or equal to $$$n$$$.The positive integer is called good if it can be represented as a sum of distinct powers of $$$3$$$ (i.e. no duplicates of powers of $$$3$$$ are allowed).For example: $$$30$$$ is a good number: $$$30 = 3^3 + 3^1$$$, $$$1$$$ is a good number: $$$1 = 3^0$$$, $$$12$$$ is a good number: $$$12 = 3^2 + 3^1$$$, but $$$2$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ ($$$2 = 3^0 + 3^0$$$), $$$19$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representations $$$19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0$$$ are invalid), $$$20$$$ is also not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representation $$$20 = 3^2 + 3^2 + 3^0 + 3^0$$$ is invalid). Note, that there exist other representations of $$$19$$$ and $$$20$$$ as sums of powers of $$$3$$$ but none of them consists of distinct powers of $$$3$$$.For the given positive integer $$$n$$$ find such smallest $$$m$$$ ($$$n \le m$$$) that $$$m$$$ is a good number.You have to answer $$$q$$$ independent queries.
256 megabytes
import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; public class GoodNumber { public static void main( String[] args ) { // System.out.println( Long.MAX_VALUE ); // getMinNumberIn3Pow(1000000000000000000L); Scanner scanner = new Scanner( System.in ); int t = Integer.parseInt( scanner.nextLine() ); ArrayList<BigDecimal> res = new ArrayList<BigDecimal>(); while( t-- > 0 ) { long number = Long.parseLong( scanner.nextLine() ); res.add( getGoodNumber( number ) ); } for( BigDecimal goodNumber : res ) { System.out.println( goodNumber ); } } private static BigDecimal getGoodNumber( long num ) { StringBuilder ternary = new StringBuilder(); long current = num; while( current > 0L ) { ternary.append( current % 3L ); current /= 3L; } return getGreaterWith3Base( ternary, num ); } private static BigDecimal getGreaterWith3Base( StringBuilder num, long originalNum ) { num.reverse(); BigDecimal number = new BigDecimal( "0" ); int size = num.length(); int index; boolean twoFound = false; for( index = 0; index < size; index++ ) { if( num.charAt( index ) == '2' ) { twoFound = true; break; } } if( !twoFound ) return new BigDecimal( originalNum ); int maxIndex =0; boolean changed = false; for( int i = index-1; i >= 0; i--) { if( num.charAt( i ) == '0' ) { num.setCharAt( i, '1' ); maxIndex =i; changed = true; break; } } for(int i=maxIndex+1;i<size;i++) num.setCharAt( i, '0' ); if( !changed ) { return getXPowY( 3, size ); } else { for( int i = 0,j=size-1; i <size; i++ ) { number = number.add( new BigDecimal(String.valueOf( num.charAt( i ) )).multiply( getXPowY( 3, j-- ) ) ); } } return number; } private static BigDecimal getXPowY( int x, int y ) { BigDecimal num1 = new BigDecimal( x ); BigDecimal res = new BigDecimal( 1 ); for( int i = 1; i <= y; i++ ) { res = res.multiply( num1 ); } return res; } }
Java
["7\n1\n2\n6\n13\n14\n3620\n10000"]
1 second
["1\n3\n9\n13\n27\n6561\n19683"]
null
Java 8
standard input
[ "binary search", "meet-in-the-middle", "greedy", "math" ]
5953b898995a82edfbd42b6c0f7138af
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) β€” the number of queries. Then $$$q$$$ queries follow. The only line of the query contains one integer $$$n$$$ ($$$1 \le n \le 10^4$$$).
1,500
For each query, print such smallest integer $$$m$$$ (where $$$n \le m$$$) that $$$m$$$ is a good number.
standard output
PASSED
b6f4b228bd803abc90b4305492a16ccb
train_004.jsonl
1571754900
The only difference between easy and hard versions is the maximum value of $$$n$$$.You are given a positive integer number $$$n$$$. You really love good numbers so you want to find the smallest good number greater than or equal to $$$n$$$.The positive integer is called good if it can be represented as a sum of distinct powers of $$$3$$$ (i.e. no duplicates of powers of $$$3$$$ are allowed).For example: $$$30$$$ is a good number: $$$30 = 3^3 + 3^1$$$, $$$1$$$ is a good number: $$$1 = 3^0$$$, $$$12$$$ is a good number: $$$12 = 3^2 + 3^1$$$, but $$$2$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ ($$$2 = 3^0 + 3^0$$$), $$$19$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representations $$$19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0$$$ are invalid), $$$20$$$ is also not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representation $$$20 = 3^2 + 3^2 + 3^0 + 3^0$$$ is invalid). Note, that there exist other representations of $$$19$$$ and $$$20$$$ as sums of powers of $$$3$$$ but none of them consists of distinct powers of $$$3$$$.For the given positive integer $$$n$$$ find such smallest $$$m$$$ ($$$n \le m$$$) that $$$m$$$ is a good number.You have to answer $$$q$$$ independent queries.
256 megabytes
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ //package solution; /** * * @author USER */ import java.util.*; import java.lang.*; import java.io.*; import java.math.*; import java.text.*; public class Solution{ static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream st) { this.stream = st; } public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int ni() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nl() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nia(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = ni(); } return a; } public String rs() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } public static class Key { private final int x; private final int y; public Key(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Key)) return false; Key key = (Key) o; return x == key.x && y == key.y; } @Override public int hashCode() { int result = x; result = 31 * result + y; return result; } } static PrintWriter w = new PrintWriter(System.out); static long mod=998244353L,mod1=1000000007; static int co[][]; static void dsort(){ Arrays.parallelSort(co,(o1,o2)->o1[0]!=o2[0]?o1[0]-o2[0]:o1[1]-o2[1]); } static long power(long x, long y) { long temp=0; if( y == 0) return 1; temp = power(x, y/2); if (y%2 == 0) return (temp*temp)%mod1; else return (((x*temp)%mod1)*temp)%mod1; } static long modInverse(long a, long m){ long num=m; long x=1; long power=a%mod1; while(num>0){ if(num%2==1){ x=(x*power)%mod1; } num>>=1; power=(power*power)%mod1; } return x; } static long ncrWithoutMod(int n,int r){ if(n<r)return 0L; long ans=fact[n]/(fact[r]*fact[n-r]); return ans; } static long fact[]=new long[1000005]; public static void findFact(){ fact[0]=1; for(int i=1;i<=1000000;i++){ fact[i]=(i*fact[i-1])%mod1; } } public static void main(String [] args){ InputReader sdf=new InputReader(System.in); Scanner sc=new Scanner(System.in); int t=sc.nextInt(); next: while(t-->0){ long n=sc.nextLong(); String s=Long.toString(n, 3); s="0"+s; char[]ch=s.toCharArray(); in: for(int i=1;i<ch.length;i++){ if(ch[i]=='2'){ for(int k=i;k<ch.length;k++){ ch[k]='0'; } for(int k=i-1;k>=0;k--){ if(ch[k]=='0'){ ch[k]='1'; break in; } else ch[k]='0'; } } } s=ch.toString(); String ss=""; for(int i=0;i<ch.length;i++){ ss=ss+ch[i]; } n=(long)Long.parseLong(ss,3); System.out.println(n); } w.close(); } } // // // // ///RKC // // static long ncr(long n, long r) // { if(r==0)return 1; // else { // long ans=n%M; // ans*=ncr(n-1,r-1)%M; // ans%=M; // ans*=inverse(r)%M; // ans%=M;return ans; // // } // // } // static long fast_exp(long x,long n){ // long ans=1; // while(n>0){ // if((n&1)!=0){ // ans*=x; // ans%=M; // } // n=n>>1; // x=(x*x)%M; // } // return ans; // } //static long inverse(long x){return fast_exp(x,M-2);} // // // ///RKC // // // // // static long bigpowmod(long a,long n,long m){ // a=a%m; // long res=1; // while(n>0){ // if((n&1)!=0){ // res=(res*a); // res=res%m; // } // a=(a*a)%m; // n=n>>1; // // } // // return res; // } // // static long printNcR(long n, long r) { // // // p holds the value of n*(n-1)*(n-2)..., // // k holds the value of r*(r-1)... // long p = 1, k = 1; // // // C(n, r) == C(n, n-r), // // choosing the smaller value // if (n - r < r) { // r = n - r; // } // // if (r != 0) { // while (r > 0) { // p *= n; // k *= r; // // // gcd of p, k // long m = __gcd(p, k); // // // dividing by gcd, to simplify product // // division by their gcd saves from the overflow // p /= m; // k /= m; // // n--; // r--; // } // // // k should be simplified to 1 // // as C(n, r) is a natural number // // (denominator should be 1 ) . // } else { // p = 1; // } // // // if our approach is correct p = ans and k =1 // return p; // } // // static long __gcd(long n1, long n2) { // long gcd = 1; // // for (int i = 1; i <= n1 && i <= n2; ++i) { // // Checks if i is factor of both integers // if (n1 % i == 0 && n2 % i == 0) { // gcd = i; // } // } // return gcd; // } // static long power(int x,int y) // { // long temp; // if( y == 0) // return 1; // temp = power(x, y/2); // if (y%2 == 0) // return temp*temp; // else // return x*temp*temp; //} // // // // //static class Reader // { // final private int BUFFER_SIZE = 1 << 16; // private DataInputStream din; // private byte[] buffer; // private int bufferPointer, bytesRead; // // public Reader() // { // din = new DataInputStream(System.in); // buffer = new byte[BUFFER_SIZE]; // bufferPointer = bytesRead = 0; // } // // public Reader(String file_name) throws IOException // { // din = new DataInputStream(new FileInputStream(file_name)); // buffer = new byte[BUFFER_SIZE]; // bufferPointer = bytesRead = 0; // } // // public String readLine() throws IOException // { // byte[] buf = new byte[64]; // line length // int cnt = 0, c; // while ((c = read()) != -1) // { // if (c == '\n') // break; // buf[cnt++] = (byte) c; // } // return new String(buf, 0, cnt); // } // // public int nextInt() throws IOException // { // int ret = 0; // byte c = read(); // while (c <= ' ') // c = read(); // boolean neg = (c == '-'); // if (neg) // c = read(); // do // { // ret = ret * 10 + c - '0'; // } while ((c = read()) >= '0' && c <= '9'); // // if (neg) // return -ret; // return ret; // } // // public long nextLong() throws IOException // { // long ret = 0; // byte c = read(); // while (c <= ' ') // c = read(); // boolean neg = (c == '-'); // if (neg) // c = read(); // do { // ret = ret * 10 + c - '0'; // } // while ((c = read()) >= '0' && c <= '9'); // if (neg) // return -ret; // return ret; // } // // public double nextDouble() throws IOException // { // double ret = 0, div = 1; // byte c = read(); // while (c <= ' ') // c = read(); // boolean neg = (c == '-'); // if (neg) // c = read(); // // do { // ret = ret * 10 + c - '0'; // } // while ((c = read()) >= '0' && c <= '9'); // // if (c == '.') // { // while ((c = read()) >= '0' && c <= '9') // { // ret += (c - '0') / (div *= 10); // } // } // // if (neg) // return -ret; // return ret; // } // // private void fillBuffer() throws IOException // { // bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); // if (bytesRead == -1) // buffer[0] = -1; // } // // private byte read() throws IOException // { // if (bufferPointer == bytesRead) // fillBuffer(); // return buffer[bufferPointer++]; // } // // public void close() throws IOException // { // if (din == null) // return; // din.close(); // } // } // // //} // class MySort { // public void selectionSort(int[]a,int left,int right){ // //left index from 0 and right= last index // for(int i=left;i<=right;i++){ // int min_index=i; // for(int j=i+1;j<=right;j++){ // if(a[min_index]>a[j])min_index=j; // } // int temp=a[min_index]; // a[min_index]=a[i]; // a[i]=temp; // } // } // // public void bubbleSort(int a[],int left,int right){ // //left index from 0 and right= last index // // for(int i=left;i<=right;i++){ // for(int j=left;j<right;j++){ // if(a[j+1]<a[j]){ // int temp=a[j+1]; // a[j+1]=a[j]; // a[j]=temp; // } // } // } // } // // // public void insertionSort(int a[],int left,int right){ // //left index from 0 and right= last index // for(int i=left+1;i<=right;i++){ // int temp=a[i]; // int j=i-1; // for(;j>=0&&temp<a[j];j--){ // a[j+1]=a[j]; // } // a[j+1]=temp; // } // } // // public void quickSort(int a[],int left,int right){ // //left index from 0 and right= last index // if(left<right){ // int pi_index=partition(a,left,right); // // quickSort(a,pi_index+1,right);//for left side of pivot // quickSort(a,left,pi_index-1);//for right side of pivot // // } // // } // private int partition(int a[],int left,int right){ // //last element is used as pivot // int pivot=a[right]; // int i=left-1; // for(int j=left;j<right;j++){ // if(pivot>a[j]){ // i++; // int temp=a[i]; // a[i]=a[j]; // a[j]=temp; // } // } // int temp=a[i+1]; // a[i+1]=a[right]; // a[right]=temp; // return i+1; // } // // public void mergeSort(int []a,int left,int right){ if(left<right){ int m=(left+right)/2; mergeSort(a, left, m); mergeSort(a, m+1, right); merging(a,left,m,right); } } private void merging(int[]a,int left,int m,int right){ int n1=m-left+1; int n2=right-(m+1)+1; int []L=new int[n1]; int []R=new int[n2]; for(int i=0;i<n1;i++){L[i]=a[left+i];} for(int i=0;i<n2;i++){R[i]=a[m+1+i];} int i=0;int j=0; int k=left; while(i<n1&&j<n2){ if(L[i]<=R[j]){ a[k]=L[i]; i++; } else { a[k]=R[j]; j++; } k++; } while(i<n1){ a[k]=L[i]; i++; k++; } while(j<n2){ a[k]=R[j]; j++; k++; } } }
Java
["7\n1\n2\n6\n13\n14\n3620\n10000"]
1 second
["1\n3\n9\n13\n27\n6561\n19683"]
null
Java 8
standard input
[ "binary search", "meet-in-the-middle", "greedy", "math" ]
5953b898995a82edfbd42b6c0f7138af
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) β€” the number of queries. Then $$$q$$$ queries follow. The only line of the query contains one integer $$$n$$$ ($$$1 \le n \le 10^4$$$).
1,500
For each query, print such smallest integer $$$m$$$ (where $$$n \le m$$$) that $$$m$$$ is a good number.
standard output
PASSED
3aca037e24337f7cdabd1d4c6fe83822
train_004.jsonl
1571754900
The only difference between easy and hard versions is the maximum value of $$$n$$$.You are given a positive integer number $$$n$$$. You really love good numbers so you want to find the smallest good number greater than or equal to $$$n$$$.The positive integer is called good if it can be represented as a sum of distinct powers of $$$3$$$ (i.e. no duplicates of powers of $$$3$$$ are allowed).For example: $$$30$$$ is a good number: $$$30 = 3^3 + 3^1$$$, $$$1$$$ is a good number: $$$1 = 3^0$$$, $$$12$$$ is a good number: $$$12 = 3^2 + 3^1$$$, but $$$2$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ ($$$2 = 3^0 + 3^0$$$), $$$19$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representations $$$19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0$$$ are invalid), $$$20$$$ is also not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representation $$$20 = 3^2 + 3^2 + 3^0 + 3^0$$$ is invalid). Note, that there exist other representations of $$$19$$$ and $$$20$$$ as sums of powers of $$$3$$$ but none of them consists of distinct powers of $$$3$$$.For the given positive integer $$$n$$$ find such smallest $$$m$$$ ($$$n \le m$$$) that $$$m$$$ is a good number.You have to answer $$$q$$$ independent queries.
256 megabytes
import java.io.*; import java.util.*; public class Solution{ static int count; public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int q = sc.nextInt(); for(int i = 0; i < q; i++) { long n = sc.nextLong(); long sum=0; int j=0; long temp=n; //int sum1=0; int min = 0; long arr[]=new long[39]; for(int k=0;k<39;k++) arr[k]=0; while(temp>0) { long r= temp%3; arr[j]=r; temp=temp/3; j++; //System.out.println("index"+ (j-1)+ " : "+arr[j-1]); } //int p=0; for(int k=0;k<38;k++) { if(arr[k]>=2) { arr[k+1]=arr[k+1]+1; for(int d=0;d<=k;d++) arr[d]=0; } } long pow=1; for(int l=0;l<39;l++) { //System.out.println("index" + l+ "product"+ arr[l]*Math.pow(3,l) ); sum+=arr[l]*pow; pow=pow*3; } System.out.println(sum); } //1000000000000000000 } }
Java
["7\n1\n2\n6\n13\n14\n3620\n10000"]
1 second
["1\n3\n9\n13\n27\n6561\n19683"]
null
Java 8
standard input
[ "binary search", "meet-in-the-middle", "greedy", "math" ]
5953b898995a82edfbd42b6c0f7138af
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) β€” the number of queries. Then $$$q$$$ queries follow. The only line of the query contains one integer $$$n$$$ ($$$1 \le n \le 10^4$$$).
1,500
For each query, print such smallest integer $$$m$$$ (where $$$n \le m$$$) that $$$m$$$ is a good number.
standard output
PASSED
572aed90dfb973271177afedb793455a
train_004.jsonl
1571754900
The only difference between easy and hard versions is the maximum value of $$$n$$$.You are given a positive integer number $$$n$$$. You really love good numbers so you want to find the smallest good number greater than or equal to $$$n$$$.The positive integer is called good if it can be represented as a sum of distinct powers of $$$3$$$ (i.e. no duplicates of powers of $$$3$$$ are allowed).For example: $$$30$$$ is a good number: $$$30 = 3^3 + 3^1$$$, $$$1$$$ is a good number: $$$1 = 3^0$$$, $$$12$$$ is a good number: $$$12 = 3^2 + 3^1$$$, but $$$2$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ ($$$2 = 3^0 + 3^0$$$), $$$19$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representations $$$19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0$$$ are invalid), $$$20$$$ is also not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representation $$$20 = 3^2 + 3^2 + 3^0 + 3^0$$$ is invalid). Note, that there exist other representations of $$$19$$$ and $$$20$$$ as sums of powers of $$$3$$$ but none of them consists of distinct powers of $$$3$$$.For the given positive integer $$$n$$$ find such smallest $$$m$$$ ($$$n \le m$$$) that $$$m$$$ is a good number.You have to answer $$$q$$$ independent queries.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Solution{ static int mod = (int)1e9+7; public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out)); public static void main(String sp[])throws IOException{ FastReader sc = new FastReader(); int q = sc.nextInt(); while(q-->0){ long n = sc.nextLong(); long total=0; int count=0; for(int i=0;;i++){ total += power(3,i); count++; if(total>=n) break; } if(total==n){ System.out.println(n); continue; } for(int i=count;i>=0;i--){ long hold = power(3,i); if(total-hold>=n){ total-=hold; } } System.out.println(total); } } public static long power(long a, long b){ long total=1; while(b>0){ if((b&1)==1){ total = total*a; } b=b>>1; a = a*a; } return total; } public static class pair{ int power; int endu; } public static class comp implements Comparator<pair>{ public int compare(pair o1, pair o2){ return o1.power-o2.power; } } public static long sum(long a, long d, long n){ long total = ((n)*((2*a)+(n-1)*d))/2; return total; } public static class trie{ char ch; HashMap<Character,trie> hm = new HashMap<>(); int count; boolean isterminal; } public static int partition(int [] arr, int s, int e){ int index=s; int pivot = arr[e]; for(int i=s;i<=e-1;i++){ if(arr[i]<=pivot){ arr = swap(arr, index, i); index++; } } swap(arr,index,e); print(arr); return index; } public static int[] swap(int[] arr, int low, int high){ int temp = arr[low]; arr[low]=arr[high]; arr[high]=temp; return arr; } public static long gcd(long a, long b){ if(a==0) return b; return gcd(b%a,a); } public static void print(int[] arr){ for(int i=0;i<arr.length;i++) System.out.print(arr[i]+" "); System.out.println(); } public static class FastReader { BufferedReader br; StringTokenizer st; 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; } } }
Java
["7\n1\n2\n6\n13\n14\n3620\n10000"]
1 second
["1\n3\n9\n13\n27\n6561\n19683"]
null
Java 8
standard input
[ "binary search", "meet-in-the-middle", "greedy", "math" ]
5953b898995a82edfbd42b6c0f7138af
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) β€” the number of queries. Then $$$q$$$ queries follow. The only line of the query contains one integer $$$n$$$ ($$$1 \le n \le 10^4$$$).
1,500
For each query, print such smallest integer $$$m$$$ (where $$$n \le m$$$) that $$$m$$$ is a good number.
standard output
PASSED
3ed51374fa1b975bbf066aaf8a095359
train_004.jsonl
1571754900
The only difference between easy and hard versions is the maximum value of $$$n$$$.You are given a positive integer number $$$n$$$. You really love good numbers so you want to find the smallest good number greater than or equal to $$$n$$$.The positive integer is called good if it can be represented as a sum of distinct powers of $$$3$$$ (i.e. no duplicates of powers of $$$3$$$ are allowed).For example: $$$30$$$ is a good number: $$$30 = 3^3 + 3^1$$$, $$$1$$$ is a good number: $$$1 = 3^0$$$, $$$12$$$ is a good number: $$$12 = 3^2 + 3^1$$$, but $$$2$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ ($$$2 = 3^0 + 3^0$$$), $$$19$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representations $$$19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0$$$ are invalid), $$$20$$$ is also not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representation $$$20 = 3^2 + 3^2 + 3^0 + 3^0$$$ is invalid). Note, that there exist other representations of $$$19$$$ and $$$20$$$ as sums of powers of $$$3$$$ but none of them consists of distinct powers of $$$3$$$.For the given positive integer $$$n$$$ find such smallest $$$m$$$ ($$$n \le m$$$) that $$$m$$$ is a good number.You have to answer $$$q$$$ independent queries.
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.net.Inet4Address; import java.util.*; import java.lang.*; import java.util.HashMap; import java.util.PriorityQueue; public class Solution implements Runnable { static class pair implements Comparable { int f; int s; pair(int fi, int se) { f=fi; s=se; } public int compareTo(Object o)//desc order { pair pr=(pair)o; if(s>pr.s) return -1; if(s==pr.s) { if(f>pr.f) return 1; else return -1; } else return 1; } public boolean equals(Object o) { pair ob=(pair)o; if(o!=null) { if((ob.f==this.f)&&(ob.s==this.s)) return true; } return false; } public int hashCode() { return (this.f+" "+this.s).hashCode(); } } public class triplet implements Comparable { int f; int s; int t; triplet(int f,int s,int t) { this.f=f; this.s=s; this.t=t; } public boolean equals(Object o) { triplet ob=(triplet)o; int ff; int ss; double tt; if(o!=null) { ff=ob.f; ss=ob.s; tt=ob.t; if((ff==this.f)&&(ss==this.s)&&(tt==this.t)) return true; } return false; } public int hashCode() { return (this.f+" "+this.s+" "+this.t).hashCode(); } public int compareTo(Object o)//ascending order { triplet tr=(triplet)o; if(t>tr.t) return 1; else return -1; } } void merge1(int arr[], int l, int m, int r) { int n1 = m - l + 1; int n2 = r - m; int L[] = new int [n1]; int R[] = new int [n2]; for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; int i = 0, j = 0; int k = l; while (i < n1 && j < n2) { if (L[i]<=R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } while (i < n1) { arr[k] = L[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; j++; k++; } } void sort1(int arr[], int l, int r) { if (l < r) { int m = (l+r)/2; sort1(arr, l, m); sort1(arr , m+1, r); merge1(arr, l, m, r); } } long pow[]; long solve(int l,int r,long sum,long n,int k) { long min=Long.MAX_VALUE/3; for(int i=l;i<=r;i++) { if(i==k) continue; if(sum+pow[i]>=n) min=Math.min(min,sum+pow[i]); } return min; } public static void main(String args[])throws Exception { new Thread(null,new Solution(),"Solution",1<<27).start(); } public void run() { try { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); pow=new long[39]; pow[0]=1; for(int i=1;i<39;i++) pow[i]=3*pow[i-1]; int t=in.ni(); while(t--!=0) { long n=in.nl(); long min=Long.MAX_VALUE/3; int k=0; for(int i=0;i<n;i++) { if(pow[i]>n) { k=i-1; min=pow[i]; break; } } long sum=0; while(k>=0) { sum+=pow[k]; if(sum>=n) min=Math.min(min,sum); min=Math.min(min,solve(0,k-1,sum,n,-1)); for(int i=0;i<k;i++) min=Math.min(min,solve(0,k-1,sum+pow[i],n,i)); int xx=-1; for(int i=0;i<k;i++) { if(sum+pow[i]<=n) { xx=i; } } if(xx==-1) break; k=xx; } out.println(min); } out.close(); } catch(Exception e){ System.out.println(e); } } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int ni() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nl() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = ni(); } return a; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["7\n1\n2\n6\n13\n14\n3620\n10000"]
1 second
["1\n3\n9\n13\n27\n6561\n19683"]
null
Java 8
standard input
[ "binary search", "meet-in-the-middle", "greedy", "math" ]
5953b898995a82edfbd42b6c0f7138af
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) β€” the number of queries. Then $$$q$$$ queries follow. The only line of the query contains one integer $$$n$$$ ($$$1 \le n \le 10^4$$$).
1,500
For each query, print such smallest integer $$$m$$$ (where $$$n \le m$$$) that $$$m$$$ is a good number.
standard output
PASSED
91655d8c2d7fc844a51734be2f468cbe
train_004.jsonl
1571754900
The only difference between easy and hard versions is the maximum value of $$$n$$$.You are given a positive integer number $$$n$$$. You really love good numbers so you want to find the smallest good number greater than or equal to $$$n$$$.The positive integer is called good if it can be represented as a sum of distinct powers of $$$3$$$ (i.e. no duplicates of powers of $$$3$$$ are allowed).For example: $$$30$$$ is a good number: $$$30 = 3^3 + 3^1$$$, $$$1$$$ is a good number: $$$1 = 3^0$$$, $$$12$$$ is a good number: $$$12 = 3^2 + 3^1$$$, but $$$2$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ ($$$2 = 3^0 + 3^0$$$), $$$19$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representations $$$19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0$$$ are invalid), $$$20$$$ is also not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representation $$$20 = 3^2 + 3^2 + 3^0 + 3^0$$$ is invalid). Note, that there exist other representations of $$$19$$$ and $$$20$$$ as sums of powers of $$$3$$$ but none of them consists of distinct powers of $$$3$$$.For the given positive integer $$$n$$$ find such smallest $$$m$$$ ($$$n \le m$$$) that $$$m$$$ is a good number.You have to answer $$$q$$$ independent queries.
256 megabytes
//When I wrote this code, only God & I understood what it did. Now only God knows !! import java.util.*; import java.io.*; import java.math.*; public class Main { static class FastReader { private InputStream mIs;private byte[] buf = new byte[1024];private int curChar,numChars;public FastReader() { this(System.in); }public FastReader(InputStream is) { mIs = is;} public int read() {if (numChars == -1) throw new InputMismatchException();if (curChar >= numChars) {curChar = 0;try { numChars = mIs.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 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 long l(){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 i(){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 double d() throws IOException {return Double.parseDouble(next()) ;} public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public void scanIntArr(int [] arr){ for(int li=0;li<arr.length;++li){ arr[li]=i();}} public void scanLongArr(long [] arr){for (int i=0;i<arr.length;++i){arr[i]=l();}} public void shuffle(int [] arr){ for(int i=arr.length;i>0;--i) { int r=(int)(Math.random()*i); int temp=arr[i-1]; arr[i-1]=arr[r]; arr[r]=temp; } } } public static int mod = (int) (1e9 + 7); public static void main(String[] args) throws IOException { // new Thread(null,new Main(),"Anything",1<<27).start(); FastReader fr = new FastReader(); PrintWriter pw = new PrintWriter(System.out); /* inputCopy 8 1 2 6 13 14 3620 10000 1000000000000000000 outputCopy 1 3 9 13 27 6561 19683 1350851717672992089 */ int q=fr.i(); for(int qi=0;qi<q;++qi) { long num=fr.l(); char [] arr=Long.toString(num,3).toCharArray(); char [] ans=new char[64]; int positionOf2=-1; for(int i=0;i<arr.length;++i) { if(arr[i]=='2') { positionOf2 = i; break; } } if(positionOf2==-1) { pw.println(num); continue; } boolean found=false; int ansIndex=63; for(int i=arr.length-1;i>=positionOf2;--i) { ans[ansIndex]='0'; --ansIndex; } for(int i=positionOf2-1;i>=0;--i) { if(arr[i]=='0' && !found) { Arrays.fill(ans,'0'); ans[ansIndex]='1'; found=true; --ansIndex; } else { ans[ansIndex]=arr[i]; --ansIndex; } } if(!found) { Arrays.fill(ans,'0'); ans[ansIndex] = '1'; } pw.println(Long.valueOf(String.valueOf(ans),3)); } pw.flush(); pw.close(); } }
Java
["7\n1\n2\n6\n13\n14\n3620\n10000"]
1 second
["1\n3\n9\n13\n27\n6561\n19683"]
null
Java 8
standard input
[ "binary search", "meet-in-the-middle", "greedy", "math" ]
5953b898995a82edfbd42b6c0f7138af
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) β€” the number of queries. Then $$$q$$$ queries follow. The only line of the query contains one integer $$$n$$$ ($$$1 \le n \le 10^4$$$).
1,500
For each query, print such smallest integer $$$m$$$ (where $$$n \le m$$$) that $$$m$$$ is a good number.
standard output
PASSED
f1e296251fcdb624e994c06de3e82ae9
train_004.jsonl
1571754900
The only difference between easy and hard versions is the maximum value of $$$n$$$.You are given a positive integer number $$$n$$$. You really love good numbers so you want to find the smallest good number greater than or equal to $$$n$$$.The positive integer is called good if it can be represented as a sum of distinct powers of $$$3$$$ (i.e. no duplicates of powers of $$$3$$$ are allowed).For example: $$$30$$$ is a good number: $$$30 = 3^3 + 3^1$$$, $$$1$$$ is a good number: $$$1 = 3^0$$$, $$$12$$$ is a good number: $$$12 = 3^2 + 3^1$$$, but $$$2$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ ($$$2 = 3^0 + 3^0$$$), $$$19$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representations $$$19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0$$$ are invalid), $$$20$$$ is also not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representation $$$20 = 3^2 + 3^2 + 3^0 + 3^0$$$ is invalid). Note, that there exist other representations of $$$19$$$ and $$$20$$$ as sums of powers of $$$3$$$ but none of them consists of distinct powers of $$$3$$$.For the given positive integer $$$n$$$ find such smallest $$$m$$$ ($$$n \le m$$$) that $$$m$$$ is a good number.You have to answer $$$q$$$ independent queries.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; /*CODE BY SHIKHAR TYAGI*/ public class C { public static void main(String args[]) { FastScanner scn = new FastScanner(); int q = scn.nextInt(); while (q-- > 0) { long n = scn.nextLong(); int a[] = new int[1000]; int i = 0; long dupn = n; while (dupn != 0) { a[i] = (int) (dupn % 3); dupn /= 3; i++; } boolean hai = false; int pos = -1; for (i = 0; i < 1000; ++i) { if (a[i] == 2) { hai = true; pos = i; } } if (!hai) { System.out.println(n); } else { for (i = pos + 1; i < 1000; ++i) { if (a[i] == 0) { a[i] = 1; for (int j = i - 1; j >= 0; --j) { a[j] = 0; } break; } } BigInteger ans = new BigInteger("0"); BigInteger b = new BigInteger("3"); for(i=0;i<1000;++i){ if(a[i] == 1){ ans = ans.add(b.pow(i)); } } System.out.println(ans.toString()); } } } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["7\n1\n2\n6\n13\n14\n3620\n10000"]
1 second
["1\n3\n9\n13\n27\n6561\n19683"]
null
Java 8
standard input
[ "binary search", "meet-in-the-middle", "greedy", "math" ]
5953b898995a82edfbd42b6c0f7138af
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) β€” the number of queries. Then $$$q$$$ queries follow. The only line of the query contains one integer $$$n$$$ ($$$1 \le n \le 10^4$$$).
1,500
For each query, print such smallest integer $$$m$$$ (where $$$n \le m$$$) that $$$m$$$ is a good number.
standard output
PASSED
ef7b86b04ba066cd2b13071b9c45b3bb
train_004.jsonl
1571754900
The only difference between easy and hard versions is the maximum value of $$$n$$$.You are given a positive integer number $$$n$$$. You really love good numbers so you want to find the smallest good number greater than or equal to $$$n$$$.The positive integer is called good if it can be represented as a sum of distinct powers of $$$3$$$ (i.e. no duplicates of powers of $$$3$$$ are allowed).For example: $$$30$$$ is a good number: $$$30 = 3^3 + 3^1$$$, $$$1$$$ is a good number: $$$1 = 3^0$$$, $$$12$$$ is a good number: $$$12 = 3^2 + 3^1$$$, but $$$2$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ ($$$2 = 3^0 + 3^0$$$), $$$19$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representations $$$19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0$$$ are invalid), $$$20$$$ is also not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representation $$$20 = 3^2 + 3^2 + 3^0 + 3^0$$$ is invalid). Note, that there exist other representations of $$$19$$$ and $$$20$$$ as sums of powers of $$$3$$$ but none of them consists of distinct powers of $$$3$$$.For the given positive integer $$$n$$$ find such smallest $$$m$$$ ($$$n \le m$$$) that $$$m$$$ is a good number.You have to answer $$$q$$$ independent queries.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; public class cdf595c1 { public static long power(long x,long y) { long result = 1; for (long i = 1; i <= y; i++) result = result * x; return result; } public static void main(String args[])throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int n=Integer.parseInt(br.readLine()); outer:for(int i=0;i<n;i++) { long t=Long.parseLong(br.readLine()); String temp="675425858836496044"; long tt=Long.parseLong(temp); long copy=t,copy2=t; if(t>tt) { System.out.println("1350851717672992089"); continue; } int arr[]=new int[38]; long sum=0; for(int j=37;j>=0;j--) { if(power(3,j)<=copy) { copy-=power(3, j); arr[j]=1; } } if(copy==0) { System.out.println(t); continue; } for(int j=0;j<38;j++) { if(arr[j]==0) { sum=power(3, j)-copy; arr[j]=1; break; } } copy2+=sum; long ll=1; for(int j=1;j<38;j++) { if(ll<=copy2&&ll>=t) { System.out.println(ll); continue outer; } ll*=3; } for(int j=37;j>=0;j--) { if(arr[j]==1&&copy2-power(3, j)>=t) { arr[j]=0; copy2-=power(3, j); } } // for(int j=0;j<=37;j++) // System.out.print(arr[j]+" "); // System.out.println(); System.out.println(copy2); } } }
Java
["7\n1\n2\n6\n13\n14\n3620\n10000"]
1 second
["1\n3\n9\n13\n27\n6561\n19683"]
null
Java 8
standard input
[ "binary search", "meet-in-the-middle", "greedy", "math" ]
5953b898995a82edfbd42b6c0f7138af
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) β€” the number of queries. Then $$$q$$$ queries follow. The only line of the query contains one integer $$$n$$$ ($$$1 \le n \le 10^4$$$).
1,500
For each query, print such smallest integer $$$m$$$ (where $$$n \le m$$$) that $$$m$$$ is a good number.
standard output
PASSED
fb024793e76949bfb3c0aa42fff7fbfa
train_004.jsonl
1571754900
The only difference between easy and hard versions is the maximum value of $$$n$$$.You are given a positive integer number $$$n$$$. You really love good numbers so you want to find the smallest good number greater than or equal to $$$n$$$.The positive integer is called good if it can be represented as a sum of distinct powers of $$$3$$$ (i.e. no duplicates of powers of $$$3$$$ are allowed).For example: $$$30$$$ is a good number: $$$30 = 3^3 + 3^1$$$, $$$1$$$ is a good number: $$$1 = 3^0$$$, $$$12$$$ is a good number: $$$12 = 3^2 + 3^1$$$, but $$$2$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ ($$$2 = 3^0 + 3^0$$$), $$$19$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representations $$$19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0$$$ are invalid), $$$20$$$ is also not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representation $$$20 = 3^2 + 3^2 + 3^0 + 3^0$$$ is invalid). Note, that there exist other representations of $$$19$$$ and $$$20$$$ as sums of powers of $$$3$$$ but none of them consists of distinct powers of $$$3$$$.For the given positive integer $$$n$$$ find such smallest $$$m$$$ ($$$n \le m$$$) that $$$m$$$ is a good number.You have to answer $$$q$$$ independent queries.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.StringTokenizer; public class GoodNumbers { public static void main(String[] args) { FastReader input=new FastReader(); int t=input.nextInt(); while(t-->0) { long n=input.nextLong(); BigInteger ans=new BigInteger("0"); while(n>0) { int x=(int)(Math.log(n)/Math.log(3)); BigInteger sum=new BigInteger("0"); for(int i=0;i<=x;i++) { BigInteger temp=new BigInteger("3"); temp=temp.pow(i); sum=sum.add(temp); } if(sum.compareTo(new BigInteger(String.valueOf(n)))==-1) { BigInteger b=new BigInteger("3"); b=b.pow(x+1); ans=ans.add(b); n=0; } else { BigInteger b=new BigInteger("3"); b=b.pow(x); ans=ans.add(b); n=n-(long)Math.pow(3,(long)(x)); } } System.out.println(ans.toString()); } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["7\n1\n2\n6\n13\n14\n3620\n10000"]
1 second
["1\n3\n9\n13\n27\n6561\n19683"]
null
Java 8
standard input
[ "binary search", "meet-in-the-middle", "greedy", "math" ]
5953b898995a82edfbd42b6c0f7138af
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) β€” the number of queries. Then $$$q$$$ queries follow. The only line of the query contains one integer $$$n$$$ ($$$1 \le n \le 10^4$$$).
1,500
For each query, print such smallest integer $$$m$$$ (where $$$n \le m$$$) that $$$m$$$ is a good number.
standard output
PASSED
3fa10e05f65568de6b03a736478f1817
train_004.jsonl
1304694000
Little Vasya likes very much to play with sets consisting of positive integers. To make the game more interesting, Vasya chose n non-empty sets in such a way, that no two of them have common elements.One day he wanted to show his friends just how interesting playing with numbers is. For that he wrote out all possible unions of two different sets on nΒ·(n - 1) / 2 pieces of paper. Then he shuffled the pieces of paper. He had written out the numbers in the unions in an arbitrary order.For example, if n = 4, and the actual sets have the following form {1, 3}, {5}, {2, 4}, {7}, then the number of set pairs equals to six. The six pieces of paper can contain the following numbers: 2, 7, 4. 1, 7, 3; 5, 4, 2; 1, 3, 5; 3, 1, 2, 4; 5, 7. Then Vasya showed the pieces of paper to his friends, but kept the n sets secret from them. His friends managed to calculate which sets Vasya had thought of in the first place. And how about you, can you restore the sets by the given pieces of paper?
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; /** * @author kgs */ public class B { private void solve() throws IOException { int n = nextInt(); List<Set<Integer>> sets = new ArrayList<Set<Integer>>(); int setsCount = (n * (n - 1)) / 2; for (int i = 0; i < setsCount; i++) { int currSize = nextInt(); Set<Integer> currSet = new TreeSet<Integer>(); for (int j = 0; j < currSize; j++) { currSet.add(nextInt()); } sets.add(currSet); } List<Set<Integer>> result = new ArrayList<Set<Integer>>(); if (n == 2) { Set<Integer> a = new TreeSet<Integer>(sets.get(0)); Set<Integer> b = new TreeSet<Integer>(a); a.remove(b.toArray()[0]); b.removeAll(a); result.add(a); result.add(b); } else { Set<Integer> first = null; boolean b = false; for (int i = 0; i < setsCount; i++) { for (int j = i + 1; j < setsCount; j++) { first = intersection(sets.get(i), sets.get(j)); if (first.size() > 0) { b = true; break; } } if (b) break; } result.add(first); for (int i = 0; i < setsCount; i++) { Set<Integer> intersect = intersection(first, sets.get(i)); if (intersect.size() > 0) { Set<Integer> rest = new TreeSet<Integer>(sets.get(i)); rest.removeAll(first); result.add(rest); } } } for (Set<Integer> s : result) { out.print(s.size()); for (Integer e : s) { out.print(" " + e); } out.println(); } } private Set<Integer> intersection(Set<Integer> a, Set<Integer> b) { Set<Integer> res = new TreeSet<Integer>(a); res.retainAll(b); return res; } // ----------------- HELPER ROUTINES ------------------ private BufferedReader in; private PrintWriter out; private StringTokenizer strTok; private String nextLine() throws IOException { return in.readLine(); } private String nextToken() throws IOException { while (strTok == null || !strTok.hasMoreTokens()) { String line = nextLine(); if (line != null) { strTok = new StringTokenizer(line); } else { return null; } } return strTok.nextToken(); } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } private double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } private BigInteger nextBig() throws IOException { return new BigInteger(nextToken()); } public static void main(String[] args) { new B().run(); } private long getMemory() { return (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024 / 1024; } private void run() { Locale.setDefault(Locale.US); try { boolean onlineJudge = System.getProperty("ONLINE_JUDGE") != null; if (!onlineJudge) { in = new BufferedReader(new FileReader("src/input.txt")); out = new PrintWriter("src/output.txt"); } else { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } long startMem = getMemory(); long startTime = System.currentTimeMillis(); solve(); long endTime = System.currentTimeMillis(); long endMem = getMemory(); if (!onlineJudge) { System.out.println("Running time = " + (endTime - startTime) + "ms"); System.out.println("Memory used = " + (endMem - startMem) + "MB"); System.out.println("Total memory = " + getMemory() + "MB"); } in.close(); out.close(); } catch (Throwable t) { t.printStackTrace(); System.exit(1); } } }
Java
["4\n3 2 7 4\n3 1 7 3\n3 5 4 2\n3 1 3 5\n4 3 1 2 4\n2 5 7", "4\n5 6 7 8 9 100\n4 7 8 9 1\n4 7 8 9 2\n3 1 6 100\n3 2 6 100\n2 1 2", "3\n2 1 2\n2 1 3\n2 2 3"]
2 seconds
["1 7 \n2 2 4 \n2 1 3 \n1 5", "3 7 8 9 \n2 6 100 \n1 1 \n1 2", "1 1 \n1 2 \n1 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "hashing" ]
bde894dc01c65da67d32c716981926f6
The first input file line contains a number n (2 ≀ n ≀ 200), n is the number of sets at Vasya's disposal. Then follow sets of numbers from the pieces of paper written on nΒ·(n - 1) / 2 lines. Each set starts with the number ki (2 ≀ ki ≀ 200), which is the number of numbers written of the i-th piece of paper, and then follow ki numbers aij (1 ≀ aij ≀ 200). All the numbers on the lines are separated by exactly one space. It is guaranteed that the input data is constructed according to the above given rules from n non-intersecting sets.
1,700
Print on n lines Vasya's sets' description. The first number on the line shows how many numbers the current set has. Then the set should be recorded by listing its elements. Separate the numbers by spaces. Each number and each set should be printed exactly once. Print the sets and the numbers in the sets in any order. If there are several answers to that problem, print any of them. It is guaranteed that there is a solution.
standard output
PASSED
e730e8ef6f60fbcd1e1d7287660a29df
train_004.jsonl
1304694000
Little Vasya likes very much to play with sets consisting of positive integers. To make the game more interesting, Vasya chose n non-empty sets in such a way, that no two of them have common elements.One day he wanted to show his friends just how interesting playing with numbers is. For that he wrote out all possible unions of two different sets on nΒ·(n - 1) / 2 pieces of paper. Then he shuffled the pieces of paper. He had written out the numbers in the unions in an arbitrary order.For example, if n = 4, and the actual sets have the following form {1, 3}, {5}, {2, 4}, {7}, then the number of set pairs equals to six. The six pieces of paper can contain the following numbers: 2, 7, 4. 1, 7, 3; 5, 4, 2; 1, 3, 5; 3, 1, 2, 4; 5, 7. Then Vasya showed the pieces of paper to his friends, but kept the n sets secret from them. His friends managed to calculate which sets Vasya had thought of in the first place. And how about you, can you restore the sets by the given pieces of paper?
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.util.ArrayList; import java.util.Collections; import java.util.TreeSet; public class Main { private static StreamTokenizer in; private static PrintWriter out; static { in = new StreamTokenizer(new BufferedReader(new InputStreamReader( System.in))); out = new PrintWriter(System.out); } private static int nextInt() throws Exception { in.nextToken(); return (int) in.nval; } private static String nextString() throws Exception { in.nextToken(); return in.sval; } public static void main(String[] argv) throws Exception { int n = nextInt(), nn = n * (n - 1) / 2; TreeSet<Integer>[] d = new TreeSet[nn]; TreeSet<Integer> ost = new TreeSet<Integer>(); for (int i = 0; i < nn; i++) { d[i] = new TreeSet<Integer>(); int g = nextInt(); for (int j = 0; j < g; j++) { int u = nextInt(); d[i].add(u); if (!ost.contains(u)) { ost.add(u); } } } if (n == 2) { int u = d[0].first(); out.println("1 " + u); TreeSet<Integer> f = d[0]; d[0].remove(u); out.print(f.size()); for (int i : f) { out.print(" " + i); } out.println(); out.flush(); return; } TreeSet<Integer>[] answer = new TreeSet[nn]; int p = 0; while (true) { if (ost.size() == 0) { break; } answer[p] = new TreeSet<Integer>(); int number = ost.first(); ArrayList<Integer> indexs = new ArrayList<Integer>(); for (int i=0; i<nn; i++) { TreeSet<Integer> l = d[i]; if (l.contains(number)) { indexs.add(i); } } TreeSet<Integer> u = (TreeSet<Integer>) d[indexs.get(0)].clone(); indexs.remove(0); for (int j : indexs) { u.retainAll(d[j]); } for (int i : u) { ost.remove(i); } answer[p++] = u; } for(int h=0; h<p; h++) { TreeSet<Integer> f = answer[h]; out.print(f.size()); for (int i : f) { out.print(" " + i); } out.println(); } out.flush(); } }
Java
["4\n3 2 7 4\n3 1 7 3\n3 5 4 2\n3 1 3 5\n4 3 1 2 4\n2 5 7", "4\n5 6 7 8 9 100\n4 7 8 9 1\n4 7 8 9 2\n3 1 6 100\n3 2 6 100\n2 1 2", "3\n2 1 2\n2 1 3\n2 2 3"]
2 seconds
["1 7 \n2 2 4 \n2 1 3 \n1 5", "3 7 8 9 \n2 6 100 \n1 1 \n1 2", "1 1 \n1 2 \n1 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "hashing" ]
bde894dc01c65da67d32c716981926f6
The first input file line contains a number n (2 ≀ n ≀ 200), n is the number of sets at Vasya's disposal. Then follow sets of numbers from the pieces of paper written on nΒ·(n - 1) / 2 lines. Each set starts with the number ki (2 ≀ ki ≀ 200), which is the number of numbers written of the i-th piece of paper, and then follow ki numbers aij (1 ≀ aij ≀ 200). All the numbers on the lines are separated by exactly one space. It is guaranteed that the input data is constructed according to the above given rules from n non-intersecting sets.
1,700
Print on n lines Vasya's sets' description. The first number on the line shows how many numbers the current set has. Then the set should be recorded by listing its elements. Separate the numbers by spaces. Each number and each set should be printed exactly once. Print the sets and the numbers in the sets in any order. If there are several answers to that problem, print any of them. It is guaranteed that there is a solution.
standard output
PASSED
d057d23f6435c84563dc386d976e9687
train_004.jsonl
1304694000
Little Vasya likes very much to play with sets consisting of positive integers. To make the game more interesting, Vasya chose n non-empty sets in such a way, that no two of them have common elements.One day he wanted to show his friends just how interesting playing with numbers is. For that he wrote out all possible unions of two different sets on nΒ·(n - 1) / 2 pieces of paper. Then he shuffled the pieces of paper. He had written out the numbers in the unions in an arbitrary order.For example, if n = 4, and the actual sets have the following form {1, 3}, {5}, {2, 4}, {7}, then the number of set pairs equals to six. The six pieces of paper can contain the following numbers: 2, 7, 4. 1, 7, 3; 5, 4, 2; 1, 3, 5; 3, 1, 2, 4; 5, 7. Then Vasya showed the pieces of paper to his friends, but kept the n sets secret from them. His friends managed to calculate which sets Vasya had thought of in the first place. And how about you, can you restore the sets by the given pieces of paper?
256 megabytes
import java.util.*; public class B { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); ArrayList<int[]> list = new ArrayList<int[]>(); ArrayList<Integer> endIdx = new ArrayList<Integer>(); ArrayList<Integer> numbers=new ArrayList<Integer>(); int count = (n * (n - 1)) / 2; for (int i = 0; i < count; i++) { int numb = sc.nextInt(); for (int j = 0; j < numb; j++) { int x = sc.nextInt(); if (!map.containsKey(x)){ numbers.add(x); map.put(x, map.size()); endIdx.add(0); list.add(new int[n-1]); } int idx = map.get(x); list.get(idx)[endIdx.get(idx)] = i; endIdx.set(idx, endIdx.get(idx) + 1); } } if(n==2){ System.out.println(1+" "+numbers.get(0)); System.out.print(numbers.size()-1+" "); for(int i=1;i<numbers.size();i++) System.out.print(numbers.get(i)+" "); }else { ArrayList<ArrayList<Integer>> res=new ArrayList<ArrayList<Integer>>(); HashMap<Integer, Integer> map2=new HashMap<Integer, Integer>(); for(int i=0;i<numbers.size();i++){ int tmp=numbers.get(i); int hash=Arrays.hashCode(list.get(map.get(tmp))); if(!map2.containsKey(hash)){ map2.put(hash, map2.size()); res.add(new ArrayList<Integer>()); } if(map2.containsKey(hash)){ res.get(map2.get(hash)).add(tmp); } } for(int i=0;i<res.size();i++){ System.out.print(res.get(i).size()+" "); for(int j=0;j<res.get(i).size();j++){ System.out.print(res.get(i).get(j)+" "); } System.out.println(); } } } }
Java
["4\n3 2 7 4\n3 1 7 3\n3 5 4 2\n3 1 3 5\n4 3 1 2 4\n2 5 7", "4\n5 6 7 8 9 100\n4 7 8 9 1\n4 7 8 9 2\n3 1 6 100\n3 2 6 100\n2 1 2", "3\n2 1 2\n2 1 3\n2 2 3"]
2 seconds
["1 7 \n2 2 4 \n2 1 3 \n1 5", "3 7 8 9 \n2 6 100 \n1 1 \n1 2", "1 1 \n1 2 \n1 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "hashing" ]
bde894dc01c65da67d32c716981926f6
The first input file line contains a number n (2 ≀ n ≀ 200), n is the number of sets at Vasya's disposal. Then follow sets of numbers from the pieces of paper written on nΒ·(n - 1) / 2 lines. Each set starts with the number ki (2 ≀ ki ≀ 200), which is the number of numbers written of the i-th piece of paper, and then follow ki numbers aij (1 ≀ aij ≀ 200). All the numbers on the lines are separated by exactly one space. It is guaranteed that the input data is constructed according to the above given rules from n non-intersecting sets.
1,700
Print on n lines Vasya's sets' description. The first number on the line shows how many numbers the current set has. Then the set should be recorded by listing its elements. Separate the numbers by spaces. Each number and each set should be printed exactly once. Print the sets and the numbers in the sets in any order. If there are several answers to that problem, print any of them. It is guaranteed that there is a solution.
standard output
PASSED
b7c479d3ab935486285d82506ffa7dc6
train_004.jsonl
1304694000
Little Vasya likes very much to play with sets consisting of positive integers. To make the game more interesting, Vasya chose n non-empty sets in such a way, that no two of them have common elements.One day he wanted to show his friends just how interesting playing with numbers is. For that he wrote out all possible unions of two different sets on nΒ·(n - 1) / 2 pieces of paper. Then he shuffled the pieces of paper. He had written out the numbers in the unions in an arbitrary order.For example, if n = 4, and the actual sets have the following form {1, 3}, {5}, {2, 4}, {7}, then the number of set pairs equals to six. The six pieces of paper can contain the following numbers: 2, 7, 4. 1, 7, 3; 5, 4, 2; 1, 3, 5; 3, 1, 2, 4; 5, 7. Then Vasya showed the pieces of paper to his friends, but kept the n sets secret from them. His friends managed to calculate which sets Vasya had thought of in the first place. And how about you, can you restore the sets by the given pieces of paper?
256 megabytes
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; public class A { static { final Locale us = Locale.US; if (!Locale.getDefault().equals(us)) { Locale.setDefault(us); } } static boolean file = false; static boolean isLocal = false; private static int nextInt() throws IOException { in.nextToken(); return (int) in.nval; } static StreamTokenizer in; static { try { // in = new Scanner(file ? new // FileInputStream("f:\\var\\tmp\\in.txt") // : System.in); // in = new BufferedReader(new InputStreamReader( // file ? new FileInputStream("f:\\var\\tmp\\in.txt") // : System.in)); in = new StreamTokenizer(new BufferedReader(new InputStreamReader( file ? new FileInputStream("f:\\var\\tmp\\in.txt") : System.in))); } catch (final FileNotFoundException e) { e.printStackTrace(); } } static PrintWriter out; static { try { out = file ? new PrintWriter( new FileWriter("f:\\var\\tmp\\out.txt")) : new PrintWriter( System.out); } catch (final IOException e) { e.printStackTrace(); } } static PrintStream err; private static final String[] NAMES = new String[] { "Sheldon", "Leonard", "Penny", "Rajesh", "Howard" }; static { err = System.err; } /** * @param args * @throws IOException */ public static void main(final String[] args) throws IOException { try { final long startTime = System.nanoTime(); final int t = 1;// nextInt(); for (int i = 0; i < t; ++i) { solve(i + 1); if (isLocal && file) { err.println(i + 1 + "/" + t); } if (isLocal && !file) { out.flush(); } } if (isLocal) { err.println(String.format("Completed after %d ms.", (System.nanoTime() - startTime) / 1000000)); } } finally { out.flush(); } } private static void solve(final int testId) throws IOException { final int n = nextInt(); final int m = n * (n - 1) / 2; final boolean[] was = new boolean[200]; final boolean[][] member = new boolean[200][m]; for (final boolean[] q : member) { Arrays.fill(q, false); } int cnt = 0; for (int i = 0; i < m; ++i) { final int k = nextInt(); for (int j = 0; j < k; ++j) { final int number = nextInt() - 1; if (!was[number]) { ++cnt; } was[number] = true; member[number][i] = true; } } final int[] hashes = new int[200]; for (int i = 0; i < 200; ++i) { hashes[i] = Arrays.hashCode(member[i]); } if (n == 2) { int j = 0; while (!was[j]) { ++j; } out.print("1 "); out.println(j + 1); out.printf("%d", cnt - 1); for (int i = j + 1; i < 200; ++i) { if (was[i]) { out.printf(" %d", i + 1); } } out.println(); } else { for (int seed = 0; seed < 200; ++seed) { if (was[seed]) { final List<Integer> ans = new ArrayList<Integer>(); ans.add(seed); for (int j = 0; j < 200; ++j) { if (j != seed && hashes[seed] == hashes[j] && Arrays.equals(member[seed], member[j])) { ans.add(j); was[j] = false; } } out.print(ans.size()); for (final int i : ans) { out.printf(" %d", i + 1); } out.println(); } } } } }
Java
["4\n3 2 7 4\n3 1 7 3\n3 5 4 2\n3 1 3 5\n4 3 1 2 4\n2 5 7", "4\n5 6 7 8 9 100\n4 7 8 9 1\n4 7 8 9 2\n3 1 6 100\n3 2 6 100\n2 1 2", "3\n2 1 2\n2 1 3\n2 2 3"]
2 seconds
["1 7 \n2 2 4 \n2 1 3 \n1 5", "3 7 8 9 \n2 6 100 \n1 1 \n1 2", "1 1 \n1 2 \n1 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "hashing" ]
bde894dc01c65da67d32c716981926f6
The first input file line contains a number n (2 ≀ n ≀ 200), n is the number of sets at Vasya's disposal. Then follow sets of numbers from the pieces of paper written on nΒ·(n - 1) / 2 lines. Each set starts with the number ki (2 ≀ ki ≀ 200), which is the number of numbers written of the i-th piece of paper, and then follow ki numbers aij (1 ≀ aij ≀ 200). All the numbers on the lines are separated by exactly one space. It is guaranteed that the input data is constructed according to the above given rules from n non-intersecting sets.
1,700
Print on n lines Vasya's sets' description. The first number on the line shows how many numbers the current set has. Then the set should be recorded by listing its elements. Separate the numbers by spaces. Each number and each set should be printed exactly once. Print the sets and the numbers in the sets in any order. If there are several answers to that problem, print any of them. It is guaranteed that there is a solution.
standard output
PASSED
6aa15baa8d9fe6bd2bb56746ce5136ec
train_004.jsonl
1304694000
Little Vasya likes very much to play with sets consisting of positive integers. To make the game more interesting, Vasya chose n non-empty sets in such a way, that no two of them have common elements.One day he wanted to show his friends just how interesting playing with numbers is. For that he wrote out all possible unions of two different sets on nΒ·(n - 1) / 2 pieces of paper. Then he shuffled the pieces of paper. He had written out the numbers in the unions in an arbitrary order.For example, if n = 4, and the actual sets have the following form {1, 3}, {5}, {2, 4}, {7}, then the number of set pairs equals to six. The six pieces of paper can contain the following numbers: 2, 7, 4. 1, 7, 3; 5, 4, 2; 1, 3, 5; 3, 1, 2, 4; 5, 7. Then Vasya showed the pieces of paper to his friends, but kept the n sets secret from them. His friends managed to calculate which sets Vasya had thought of in the first place. And how about you, can you restore the sets by the given pieces of paper?
256 megabytes
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.HashMap; import java.util.HashSet; import java.util.Scanner; public class Main { public static void main(String[] args) throws FileNotFoundException { //System.setIn(new FileInputStream("sets.in")); Scanner sc = new Scanner(System.in); int n = Integer.parseInt(sc.nextLine()); int q = n * (n - 1) / 2; HashSet<Integer>[] hash = new HashSet[q]; HashSet<Integer>[] result = new HashSet[n]; HashSet<Integer> elements = new HashSet<Integer>(); HashSet<Integer> processed = new HashSet<Integer>(); HashMap<Integer, Integer> firstAppear = new HashMap<Integer, Integer>(); HashMap<Integer, Integer> secondAppear = new HashMap<Integer, Integer>(); //20.000 for(int i = 0; i < q; i++) { hash[i] = new HashSet<Integer>(); String[] parts = sc.nextLine().split(" "); for(int j = 1; j < parts.length; j++) { int number = Integer.parseInt(parts[j]); hash[i].add(number); elements.add(number); if(!firstAppear.containsKey(number)) firstAppear.put(number, i); else if(!secondAppear.containsKey(number)) secondAppear.put(number, i); } } if(n == 2) { boolean deleted = false; int num = 0; for(int element : hash[0]) { if(!deleted) { num = element; deleted = true; } } hash[0].remove(num); System.out.println("1 " + num); System.out.print(hash[0].size()); for(int element: hash[0]) System.out.print(" " + element); System.out.println(); return; } int count = 0; for(int element : elements) { // 200 if(processed.contains(element)) continue; int firstApp = firstAppear.get(element); int secondApp = secondAppear.get(element); HashSet<Integer> firstSet = hash[firstApp]; HashSet<Integer> secondSet = hash[secondApp]; HashSet<Integer> actSet = new HashSet<Integer>(); for(int number : firstSet) if(secondSet.contains(number)) actSet.add(number); for(int number : actSet) processed.add(number); result[count] = actSet; count++; } for(int i = 0; i < n; i++) { System.out.print(result[i].size()); for(int number : result[i]) { System.out.print(" " + number); } System.out.println(); } } }
Java
["4\n3 2 7 4\n3 1 7 3\n3 5 4 2\n3 1 3 5\n4 3 1 2 4\n2 5 7", "4\n5 6 7 8 9 100\n4 7 8 9 1\n4 7 8 9 2\n3 1 6 100\n3 2 6 100\n2 1 2", "3\n2 1 2\n2 1 3\n2 2 3"]
2 seconds
["1 7 \n2 2 4 \n2 1 3 \n1 5", "3 7 8 9 \n2 6 100 \n1 1 \n1 2", "1 1 \n1 2 \n1 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "hashing" ]
bde894dc01c65da67d32c716981926f6
The first input file line contains a number n (2 ≀ n ≀ 200), n is the number of sets at Vasya's disposal. Then follow sets of numbers from the pieces of paper written on nΒ·(n - 1) / 2 lines. Each set starts with the number ki (2 ≀ ki ≀ 200), which is the number of numbers written of the i-th piece of paper, and then follow ki numbers aij (1 ≀ aij ≀ 200). All the numbers on the lines are separated by exactly one space. It is guaranteed that the input data is constructed according to the above given rules from n non-intersecting sets.
1,700
Print on n lines Vasya's sets' description. The first number on the line shows how many numbers the current set has. Then the set should be recorded by listing its elements. Separate the numbers by spaces. Each number and each set should be printed exactly once. Print the sets and the numbers in the sets in any order. If there are several answers to that problem, print any of them. It is guaranteed that there is a solution.
standard output
PASSED
5b88c33a9cffa7025571daad756e847d
train_004.jsonl
1304694000
Little Vasya likes very much to play with sets consisting of positive integers. To make the game more interesting, Vasya chose n non-empty sets in such a way, that no two of them have common elements.One day he wanted to show his friends just how interesting playing with numbers is. For that he wrote out all possible unions of two different sets on nΒ·(n - 1) / 2 pieces of paper. Then he shuffled the pieces of paper. He had written out the numbers in the unions in an arbitrary order.For example, if n = 4, and the actual sets have the following form {1, 3}, {5}, {2, 4}, {7}, then the number of set pairs equals to six. The six pieces of paper can contain the following numbers: 2, 7, 4. 1, 7, 3; 5, 4, 2; 1, 3, 5; 3, 1, 2, 4; 5, 7. Then Vasya showed the pieces of paper to his friends, but kept the n sets secret from them. His friends managed to calculate which sets Vasya had thought of in the first place. And how about you, can you restore the sets by the given pieces of paper?
256 megabytes
//package yandexqual2; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; public class B { static BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st; static PrintWriter out = new PrintWriter(System.out); static String nextToken() throws IOException{ while (st==null || !st.hasMoreTokens()){ String s = bf.readLine(); if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } static int nextInt() throws IOException{ return Integer.parseInt(nextToken()); } static long nextLong() throws IOException{ return Long.parseLong(nextToken()); } static String nextStr() throws IOException{ return nextToken(); } static double nextDouble() throws IOException{ return Double.parseDouble(nextToken()); } static int mark[], num[], q; static void dfs(int u, boolean used[], byte c[][]){ used[u] = true; mark[u] = q; num[q]++; for (int i=1; i<=200; i++) if (c[u][i]==1 && !used[i]) dfs(i, used, c); } public static void main(String[] args) throws IOException{ int n = nextInt(), m = n*(n-1)/2, a[][] = new int[m][]; byte d[] = new byte[201]; for (int i=0; i<m; i++){ int k = nextInt(); a[i] = new int[k]; for (int j=0; j<k; j++){ a[i][j] = nextInt(); d[a[i][j]] = 1; } } byte c[][] = new byte[201][201]; for (int p=1; p<=200; p++) if (d[p] == 1){ int b[] = new int[201]; int k = 0; for (int i=0; i<m; i++){ boolean f = false; for (int j=0; j<a[i].length; j++) if (a[i][j] == p){ f = true; break; } if (f){ k++; for (int j=0; j<a[i].length; j++) if (a[i][j] != p) b[a[i][j]] += k; } } k = k*(k+1)/2; for (int i=1; i<=200; i++) if (b[i] == k) c[p][i] = 1; } boolean used[] = new boolean[201]; mark = new int[201]; num = new int[201]; q = 0; ArrayList<Integer> set = new ArrayList<Integer>(); for (int i=1; i<=200; i++) if (d[i]==1 && !used[i]){ q++; set.clear(); dfs(i, used, c); // // out.print(set.size()); // for (int j=0; j<set.size(); j++){ // out.print(' '); // out.print(set.get(j)); // } // out.println(); } while (q < n){ q++; for (int i=1; i<=200; i++) if (num[mark[i]] > 1){ num[mark[i]]--; mark[i] = q; num[q]++; } } for (int i=1; i<=n; i++){ out.print(num[i]); for (int j=1; j<=200; j++) if (mark[j] == i){ out.print(' '); out.print(j); } out.println(); } out.flush(); } }
Java
["4\n3 2 7 4\n3 1 7 3\n3 5 4 2\n3 1 3 5\n4 3 1 2 4\n2 5 7", "4\n5 6 7 8 9 100\n4 7 8 9 1\n4 7 8 9 2\n3 1 6 100\n3 2 6 100\n2 1 2", "3\n2 1 2\n2 1 3\n2 2 3"]
2 seconds
["1 7 \n2 2 4 \n2 1 3 \n1 5", "3 7 8 9 \n2 6 100 \n1 1 \n1 2", "1 1 \n1 2 \n1 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "hashing" ]
bde894dc01c65da67d32c716981926f6
The first input file line contains a number n (2 ≀ n ≀ 200), n is the number of sets at Vasya's disposal. Then follow sets of numbers from the pieces of paper written on nΒ·(n - 1) / 2 lines. Each set starts with the number ki (2 ≀ ki ≀ 200), which is the number of numbers written of the i-th piece of paper, and then follow ki numbers aij (1 ≀ aij ≀ 200). All the numbers on the lines are separated by exactly one space. It is guaranteed that the input data is constructed according to the above given rules from n non-intersecting sets.
1,700
Print on n lines Vasya's sets' description. The first number on the line shows how many numbers the current set has. Then the set should be recorded by listing its elements. Separate the numbers by spaces. Each number and each set should be printed exactly once. Print the sets and the numbers in the sets in any order. If there are several answers to that problem, print any of them. It is guaranteed that there is a solution.
standard output
PASSED
98f91c192f58d1350e53451b3ac8c37f
train_004.jsonl
1304694000
Little Vasya likes very much to play with sets consisting of positive integers. To make the game more interesting, Vasya chose n non-empty sets in such a way, that no two of them have common elements.One day he wanted to show his friends just how interesting playing with numbers is. For that he wrote out all possible unions of two different sets on nΒ·(n - 1) / 2 pieces of paper. Then he shuffled the pieces of paper. He had written out the numbers in the unions in an arbitrary order.For example, if n = 4, and the actual sets have the following form {1, 3}, {5}, {2, 4}, {7}, then the number of set pairs equals to six. The six pieces of paper can contain the following numbers: 2, 7, 4. 1, 7, 3; 5, 4, 2; 1, 3, 5; 3, 1, 2, 4; 5, 7. Then Vasya showed the pieces of paper to his friends, but kept the n sets secret from them. His friends managed to calculate which sets Vasya had thought of in the first place. And how about you, can you restore the sets by the given pieces of paper?
256 megabytes
import java.awt.Point; import java.io.*; import java.math.BigInteger; import java.util.*; import static java.lang.Math.*; public class Solution82B { final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE")!=null; BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws FileNotFoundException{ if (ONLINE_JUDGE){ in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); }else{ in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } } String readString() throws IOException{ while(!tok.hasMoreTokens()){ tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int readInt() throws IOException{ return Integer.parseInt(readString()); } long readLong() throws IOException{ return Long.parseLong(readString()); } double readDouble() throws IOException{ return Double.parseDouble(readString()); } public static void main(String[] args){ new Solution82B().run(); } public void run(){ try{ long t1 = System.currentTimeMillis(); init(); solve(); out.close(); long t2 = System.currentTimeMillis(); System.err.println("Time = "+(t2-t1)); }catch (Exception e){ e.printStackTrace(System.err); System.exit(-1); } } static class Utils { private Utils() {} public static void mergeSort(int[] a) { mergeSort(a, 0, a.length - 1); } private static void mergeSort(int[] a, int leftIndex, int rightIndex) { final int MAGIC_VALUE = 50; if (leftIndex < rightIndex) { if (rightIndex - leftIndex <= MAGIC_VALUE) { insertionSort(a, leftIndex, rightIndex); } else { int middleIndex = (leftIndex + rightIndex) / 2; mergeSort(a, leftIndex, middleIndex); mergeSort(a, middleIndex + 1, rightIndex); merge(a, leftIndex, middleIndex, rightIndex); } } } private static void merge(int[] a, int leftIndex, int middleIndex, int rightIndex) { int length1 = middleIndex - leftIndex + 1; int length2 = rightIndex - middleIndex; int[] leftArray = new int[length1]; int[] rightArray = new int[length2]; System.arraycopy(a, leftIndex, leftArray, 0, length1); System.arraycopy(a, middleIndex + 1, rightArray, 0, length2); for (int k = leftIndex, i = 0, j = 0; k <= rightIndex; k++) { if (i == length1) { a[k] = rightArray[j++]; } else if (j == length2) { a[k] = leftArray[i++]; } else { a[k] = leftArray[i] <= rightArray[j] ? leftArray[i++] : rightArray[j++]; } } } private static void insertionSort(int[] a, int leftIndex, int rightIndex) { for (int i = leftIndex + 1; i <= rightIndex; i++) { int current = a[i]; int j = i - 1; while (j >= leftIndex && a[j] > current) { a[j + 1] = a[j]; j--; } a[j + 1] = current; } } } void solve() throws IOException{ int n = readInt(); boolean[] isPresent = new boolean[201]; int[][] map = new int[201][201]; for(int i = 0; i < n * (n - 1) / 2; i++){ int num = readInt(); int[] temp = new int[num]; for(int j = 0; j < num; j++){ temp[j] = readInt(); isPresent[temp[j]] = true; } for(int j = 0; j < num; j++){ for(int r = j; r < num; r++){ map[temp[j]][temp[r]]++; map[temp[r]][temp[j]]++; } } } if(n == 2){ String s1 = "1 "; boolean first = true; int count = 0; String s2 = ""; for(int i = 0; i <= 200; i++){ if(first && isPresent[i]){ first = false; s1 += i; continue; } if(!first && isPresent[i]){ count++; s2 += " " + i; } } out.println(s1); out.println(count + " " + s2); return; } for(int i = 1; i <= 200; i++){ if(isPresent[i]){ String s = ""; int count = 0; for(int j = 1; j <= 200; j++){ if(map[i][j] > 1){ count++; s += " " + j; isPresent[j] = false; } } out.println(count + s); } } } static double distance(long x1, long y1, long x2, long y2){ return Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)); } static long gcd(long a, long b){ while(a != b){ if(a < b) a -=b; else b -= a; } return a; } static long lcm(long a, long b){ return a * b /gcd(a, b); } }
Java
["4\n3 2 7 4\n3 1 7 3\n3 5 4 2\n3 1 3 5\n4 3 1 2 4\n2 5 7", "4\n5 6 7 8 9 100\n4 7 8 9 1\n4 7 8 9 2\n3 1 6 100\n3 2 6 100\n2 1 2", "3\n2 1 2\n2 1 3\n2 2 3"]
2 seconds
["1 7 \n2 2 4 \n2 1 3 \n1 5", "3 7 8 9 \n2 6 100 \n1 1 \n1 2", "1 1 \n1 2 \n1 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "hashing" ]
bde894dc01c65da67d32c716981926f6
The first input file line contains a number n (2 ≀ n ≀ 200), n is the number of sets at Vasya's disposal. Then follow sets of numbers from the pieces of paper written on nΒ·(n - 1) / 2 lines. Each set starts with the number ki (2 ≀ ki ≀ 200), which is the number of numbers written of the i-th piece of paper, and then follow ki numbers aij (1 ≀ aij ≀ 200). All the numbers on the lines are separated by exactly one space. It is guaranteed that the input data is constructed according to the above given rules from n non-intersecting sets.
1,700
Print on n lines Vasya's sets' description. The first number on the line shows how many numbers the current set has. Then the set should be recorded by listing its elements. Separate the numbers by spaces. Each number and each set should be printed exactly once. Print the sets and the numbers in the sets in any order. If there are several answers to that problem, print any of them. It is guaranteed that there is a solution.
standard output
PASSED
46dc4a1118ee34c96a1f2fc06f3226f4
train_004.jsonl
1304694000
Little Vasya likes very much to play with sets consisting of positive integers. To make the game more interesting, Vasya chose n non-empty sets in such a way, that no two of them have common elements.One day he wanted to show his friends just how interesting playing with numbers is. For that he wrote out all possible unions of two different sets on nΒ·(n - 1) / 2 pieces of paper. Then he shuffled the pieces of paper. He had written out the numbers in the unions in an arbitrary order.For example, if n = 4, and the actual sets have the following form {1, 3}, {5}, {2, 4}, {7}, then the number of set pairs equals to six. The six pieces of paper can contain the following numbers: 2, 7, 4. 1, 7, 3; 5, 4, 2; 1, 3, 5; 3, 1, 2, 4; 5, 7. Then Vasya showed the pieces of paper to his friends, but kept the n sets secret from them. His friends managed to calculate which sets Vasya had thought of in the first place. And how about you, can you restore the sets by the given pieces of paper?
256 megabytes
import java.io.*; import java.util.*; /** * Yandex.Algorithm 2011 Qualification 2, B * @author Roman Kosenko <madkite@gmail.com> */ public class C082B_Sets { public static void main(String... args) throws IOException { if(args.length != 0) System.setIn(new FileInputStream(args[0])); else if(!Boolean.parseBoolean(System.getProperty("ONLINE_JUDGE"))) { main("in/C082B.1.txt"); main("in/C082B.2.txt"); main("in/C082B.3.txt"); //main("input.txt"); return; } BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()), l = n * (n - 1) / 2; Map<Integer, BitSet> a = new HashMap<Integer, BitSet>(l); for(int i = l; i > 0; i--) { String[] ss = br.readLine().split(" "); for(int j = 1; j < ss.length; j++) { int v = Integer.parseInt(ss[j]); BitSet s = a.get(v); if(s == null) a.put(v, s = new BitSet(l)); s.set(i); } } if(l == 1) a.values().iterator().next().clear(); Map<BitSet, List<Integer>> b = new HashMap<BitSet, List<Integer>>(a.size() * 2); for(Map.Entry<Integer, BitSet> e : a.entrySet()) { List<Integer> r = b.get(e.getValue()); if(r == null) b.put(e.getValue(), r = new LinkedList<Integer>()); r.add(e.getKey()); } for(List<Integer> r : b.values()) System.out.println(r.size() + " " + r.toString().replaceAll("[^\\d ]", "")); } }
Java
["4\n3 2 7 4\n3 1 7 3\n3 5 4 2\n3 1 3 5\n4 3 1 2 4\n2 5 7", "4\n5 6 7 8 9 100\n4 7 8 9 1\n4 7 8 9 2\n3 1 6 100\n3 2 6 100\n2 1 2", "3\n2 1 2\n2 1 3\n2 2 3"]
2 seconds
["1 7 \n2 2 4 \n2 1 3 \n1 5", "3 7 8 9 \n2 6 100 \n1 1 \n1 2", "1 1 \n1 2 \n1 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "hashing" ]
bde894dc01c65da67d32c716981926f6
The first input file line contains a number n (2 ≀ n ≀ 200), n is the number of sets at Vasya's disposal. Then follow sets of numbers from the pieces of paper written on nΒ·(n - 1) / 2 lines. Each set starts with the number ki (2 ≀ ki ≀ 200), which is the number of numbers written of the i-th piece of paper, and then follow ki numbers aij (1 ≀ aij ≀ 200). All the numbers on the lines are separated by exactly one space. It is guaranteed that the input data is constructed according to the above given rules from n non-intersecting sets.
1,700
Print on n lines Vasya's sets' description. The first number on the line shows how many numbers the current set has. Then the set should be recorded by listing its elements. Separate the numbers by spaces. Each number and each set should be printed exactly once. Print the sets and the numbers in the sets in any order. If there are several answers to that problem, print any of them. It is guaranteed that there is a solution.
standard output
PASSED
ad5ce07be067300c3fe24a6e55557b99
train_004.jsonl
1304694000
Little Vasya likes very much to play with sets consisting of positive integers. To make the game more interesting, Vasya chose n non-empty sets in such a way, that no two of them have common elements.One day he wanted to show his friends just how interesting playing with numbers is. For that he wrote out all possible unions of two different sets on nΒ·(n - 1) / 2 pieces of paper. Then he shuffled the pieces of paper. He had written out the numbers in the unions in an arbitrary order.For example, if n = 4, and the actual sets have the following form {1, 3}, {5}, {2, 4}, {7}, then the number of set pairs equals to six. The six pieces of paper can contain the following numbers: 2, 7, 4. 1, 7, 3; 5, 4, 2; 1, 3, 5; 3, 1, 2, 4; 5, 7. Then Vasya showed the pieces of paper to his friends, but kept the n sets secret from them. His friends managed to calculate which sets Vasya had thought of in the first place. And how about you, can you restore the sets by the given pieces of paper?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Locale; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeSet; public class Main { @SuppressWarnings("unchecked") void solve() throws IOException { int n = nextInt(); if (n == 2) { int ki = nextInt(); out.println("1 " + nextInt()); out.print((ki - 1)); for (int j = 0; j < ki - 1; j++) { out.print(" " + nextInt()); } return; } boolean[] used = new boolean[201]; Arrays.fill(used, false); Set<Integer>[] s = new TreeSet[201]; Set<Integer>[] sets = new TreeSet[201]; for (int i = 1; i <= 200; i++) { s[i] = new TreeSet<Integer>(); sets[i] = new TreeSet<Integer>(); sets[i].add(i); } int npairs = n * (n - 1) / 2; for (int i = 0; i < npairs; i++) { int ki = nextInt(); for (int j = 0; j < ki; j++) { int k = nextInt(); s[k].add(i); used[k] = true; // out.println(k+" seen!"); } } for (int i = 1; i <= 200; i++) { for (int j = i + 1; j <= 200; j++) { int same = 0; for (int k : s[i]) { if (s[j].contains(k)) { same++; } } if (same == n - 1) { // out.println( i + " same set of " + j ); sets[i].add(j); } } } boolean[] seen = new boolean[201]; Arrays.fill(seen, false); for (int i = 1; i <= 200; i++) { if (used[i] && !seen[i] && sets[i].size() != 0) { seen[i] = true; out.print(sets[i].size()); for (int j : sets[i]) { seen[j] = true; out.print(" " + j); } out.println(); } } } private BufferedReader in; private PrintWriter out; private StringTokenizer st; Main() throws IOException { Locale.setDefault(Locale.ENGLISH); in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); eat(""); solve(); in.close(); out.close(); } private void eat(String str) { st = new StringTokenizer(str); } String next() throws IOException { while (!st.hasMoreTokens()) { String line = in.readLine(); if (line == null) { return null; } eat(line); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } public static void main(String[] args) throws IOException { new Main(); } }
Java
["4\n3 2 7 4\n3 1 7 3\n3 5 4 2\n3 1 3 5\n4 3 1 2 4\n2 5 7", "4\n5 6 7 8 9 100\n4 7 8 9 1\n4 7 8 9 2\n3 1 6 100\n3 2 6 100\n2 1 2", "3\n2 1 2\n2 1 3\n2 2 3"]
2 seconds
["1 7 \n2 2 4 \n2 1 3 \n1 5", "3 7 8 9 \n2 6 100 \n1 1 \n1 2", "1 1 \n1 2 \n1 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "hashing" ]
bde894dc01c65da67d32c716981926f6
The first input file line contains a number n (2 ≀ n ≀ 200), n is the number of sets at Vasya's disposal. Then follow sets of numbers from the pieces of paper written on nΒ·(n - 1) / 2 lines. Each set starts with the number ki (2 ≀ ki ≀ 200), which is the number of numbers written of the i-th piece of paper, and then follow ki numbers aij (1 ≀ aij ≀ 200). All the numbers on the lines are separated by exactly one space. It is guaranteed that the input data is constructed according to the above given rules from n non-intersecting sets.
1,700
Print on n lines Vasya's sets' description. The first number on the line shows how many numbers the current set has. Then the set should be recorded by listing its elements. Separate the numbers by spaces. Each number and each set should be printed exactly once. Print the sets and the numbers in the sets in any order. If there are several answers to that problem, print any of them. It is guaranteed that there is a solution.
standard output
PASSED
85b845cb91bfe63ae8b1b78ff7d8c882
train_004.jsonl
1304694000
Little Vasya likes very much to play with sets consisting of positive integers. To make the game more interesting, Vasya chose n non-empty sets in such a way, that no two of them have common elements.One day he wanted to show his friends just how interesting playing with numbers is. For that he wrote out all possible unions of two different sets on nΒ·(n - 1) / 2 pieces of paper. Then he shuffled the pieces of paper. He had written out the numbers in the unions in an arbitrary order.For example, if n = 4, and the actual sets have the following form {1, 3}, {5}, {2, 4}, {7}, then the number of set pairs equals to six. The six pieces of paper can contain the following numbers: 2, 7, 4. 1, 7, 3; 5, 4, 2; 1, 3, 5; 3, 1, 2, 4; 5, 7. Then Vasya showed the pieces of paper to his friends, but kept the n sets secret from them. His friends managed to calculate which sets Vasya had thought of in the first place. And how about you, can you restore the sets by the given pieces of paper?
256 megabytes
import java.util.*; public class TaskB { final int MOD = 1000000009; void run(){ int n = nextInt(); if(n == 2){ int k = nextInt(); System.out.println(1 + " " + nextInt()); System.out.print((k - 1) + " "); for(int i = 0; i < k - 1; i++){ System.out.print(nextInt()+ " "); } System.out.println(); return; } int k, x; HashMap<Integer, ArrayList<Integer> > map1 = new HashMap<Integer, ArrayList<Integer>>(); for(int i = 0; i < (n * (n - 1)) / 2; i++){ k = nextInt(); for(int j = 0; j < k; j++){ x = nextInt(); if(map1.containsKey(x)){ map1.get(x).add(i); }else{ map1.put(x, new ArrayList<Integer>()); map1.get(x).add(i); } } } HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for(Integer a : map1.keySet()){ long val = 0; for(Integer a1 : map1.get(a)){ val += a1; val *= 31; if(val >= MOD) val -= MOD; } map.put(a, (int)val); } HashMap<Integer, ArrayList<Integer>> map2 = new HashMap<Integer, ArrayList<Integer>>(); for(Integer key : map.keySet()){ if(map2.containsKey(map.get(key))){ map2.get(map.get(key)).add(key); }else{ map2.put(map.get(key), new ArrayList<Integer>()); map2.get(map.get(key)).add(key); } } for(Integer keys : map2.keySet()){ System.out.print(map2.get(keys).size() + " "); for(Integer a : map2.get(keys)){ System.out.print(a + " "); } System.out.println(); } } int nextInt(){ try{ int c = System.in.read(); if(c == -1) return c; while(c != '-' && (c < '0' || '9' < c)){ c = System.in.read(); if(c == -1) return c; } if(c == '-') return -nextInt(); int res = 0; do{ res *= 10; res += c - '0'; c = System.in.read(); }while('0' <= c && c <= '9'); return res; }catch(Exception e){ return -1; } } long nextLong(){ try{ int c = System.in.read(); if(c == -1) return -1; while(c != '-' && (c < '0' || '9' < c)){ c = System.in.read(); if(c == -1) return -1; } if(c == '-') return -nextLong(); long res = 0; do{ res *= 10; res += c-'0'; c = System.in.read(); }while('0' <= c && c <= '9'); return res; }catch(Exception e){ return -1; } } double nextDouble(){ return Double.parseDouble(next()); } String next(){ try{ StringBuilder res = new StringBuilder(""); int c = System.in.read(); while(Character.isWhitespace(c)) c = System.in.read(); do{ res.append((char)c); }while(!Character.isWhitespace(c=System.in.read())); return res.toString(); }catch(Exception e){ return null; } } String nextLine(){ try{ StringBuilder res = new StringBuilder(""); int c = System.in.read(); while(c == '\r' || c == '\n') c = System.in.read(); do{ res.append((char)c); c = System.in.read(); }while(c != '\r' && c != '\n'); return res.toString(); }catch(Exception e){ return null; } } public static void main(String[] args){ new TaskB().run(); } }
Java
["4\n3 2 7 4\n3 1 7 3\n3 5 4 2\n3 1 3 5\n4 3 1 2 4\n2 5 7", "4\n5 6 7 8 9 100\n4 7 8 9 1\n4 7 8 9 2\n3 1 6 100\n3 2 6 100\n2 1 2", "3\n2 1 2\n2 1 3\n2 2 3"]
2 seconds
["1 7 \n2 2 4 \n2 1 3 \n1 5", "3 7 8 9 \n2 6 100 \n1 1 \n1 2", "1 1 \n1 2 \n1 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "hashing" ]
bde894dc01c65da67d32c716981926f6
The first input file line contains a number n (2 ≀ n ≀ 200), n is the number of sets at Vasya's disposal. Then follow sets of numbers from the pieces of paper written on nΒ·(n - 1) / 2 lines. Each set starts with the number ki (2 ≀ ki ≀ 200), which is the number of numbers written of the i-th piece of paper, and then follow ki numbers aij (1 ≀ aij ≀ 200). All the numbers on the lines are separated by exactly one space. It is guaranteed that the input data is constructed according to the above given rules from n non-intersecting sets.
1,700
Print on n lines Vasya's sets' description. The first number on the line shows how many numbers the current set has. Then the set should be recorded by listing its elements. Separate the numbers by spaces. Each number and each set should be printed exactly once. Print the sets and the numbers in the sets in any order. If there are several answers to that problem, print any of them. It is guaranteed that there is a solution.
standard output
PASSED
55dea0d0fe9822868e17c7f4f925b595
train_004.jsonl
1304694000
Little Vasya likes very much to play with sets consisting of positive integers. To make the game more interesting, Vasya chose n non-empty sets in such a way, that no two of them have common elements.One day he wanted to show his friends just how interesting playing with numbers is. For that he wrote out all possible unions of two different sets on nΒ·(n - 1) / 2 pieces of paper. Then he shuffled the pieces of paper. He had written out the numbers in the unions in an arbitrary order.For example, if n = 4, and the actual sets have the following form {1, 3}, {5}, {2, 4}, {7}, then the number of set pairs equals to six. The six pieces of paper can contain the following numbers: 2, 7, 4. 1, 7, 3; 5, 4, 2; 1, 3, 5; 3, 1, 2, 4; 5, 7. Then Vasya showed the pieces of paper to his friends, but kept the n sets secret from them. His friends managed to calculate which sets Vasya had thought of in the first place. And how about you, can you restore the sets by the given pieces of paper?
256 megabytes
/* Author: Yiu Yu Ho Creation: <Creation Date> Last Updated: <Last Updated Date> */ import java.io.*; import java.util.*; public class Sets { public Scanner in = new Scanner(System.in); public PrintStream out = System.out; public TreeSet<Integer>[] L; public int n; ArrayList<TreeSet<Integer>> R; public void main() { n = in.nextInt(); L = new TreeSet[n*(n-1)/2]; for(int i = 0; i < L.length; ++i) { L[i] = new TreeSet<Integer>(); int len = in.nextInt(); for(int j = 0; j < len; ++j) L[i].add(in.nextInt()); } if(L.length == 1) { ArrayList<Integer> A = new ArrayList<Integer>(L[0]); out.println(1 + " " + A.get(0)); out.print(A.size() - 1); for(int i = 1; i < A.size(); ++i) out.print(" " + A.get(i)); out.println(); return; } TreeSet<Integer> S1 = null; for(int i = 1; i < L.length; ++i) { TreeSet<Integer> T = intersect(L[0], L[i]); if(T.size() > 0) { S1 = T; break; } } R = new ArrayList<TreeSet<Integer>>(); R.add(S1); for(int i = 0; i < L.length; ++i) if(subset(S1, L[i])) { R.add(subtract(L[i], S1)); } for(TreeSet<Integer> S : R) { out.print(S.size()); for(Integer x : S) out.print(" " + x); out.println(); } }//end public void main() public TreeSet<Integer> intersect(TreeSet<Integer> A, TreeSet<Integer> B) { TreeSet<Integer> R = new TreeSet<Integer>(); for(Integer x : A) if(B.contains(x)) R.add(x); return R; } public boolean subset(TreeSet<Integer> A, TreeSet<Integer> B) { for(Integer a : A) if(!B.contains(a)) return false; return true; } public TreeSet<Integer> subtract(TreeSet<Integer> A, TreeSet<Integer> B) { TreeSet<Integer> R = (TreeSet)(A.clone()); R.removeAll(B); return R; } public static void main(String[] args) { (new Sets()).main(); } }
Java
["4\n3 2 7 4\n3 1 7 3\n3 5 4 2\n3 1 3 5\n4 3 1 2 4\n2 5 7", "4\n5 6 7 8 9 100\n4 7 8 9 1\n4 7 8 9 2\n3 1 6 100\n3 2 6 100\n2 1 2", "3\n2 1 2\n2 1 3\n2 2 3"]
2 seconds
["1 7 \n2 2 4 \n2 1 3 \n1 5", "3 7 8 9 \n2 6 100 \n1 1 \n1 2", "1 1 \n1 2 \n1 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "hashing" ]
bde894dc01c65da67d32c716981926f6
The first input file line contains a number n (2 ≀ n ≀ 200), n is the number of sets at Vasya's disposal. Then follow sets of numbers from the pieces of paper written on nΒ·(n - 1) / 2 lines. Each set starts with the number ki (2 ≀ ki ≀ 200), which is the number of numbers written of the i-th piece of paper, and then follow ki numbers aij (1 ≀ aij ≀ 200). All the numbers on the lines are separated by exactly one space. It is guaranteed that the input data is constructed according to the above given rules from n non-intersecting sets.
1,700
Print on n lines Vasya's sets' description. The first number on the line shows how many numbers the current set has. Then the set should be recorded by listing its elements. Separate the numbers by spaces. Each number and each set should be printed exactly once. Print the sets and the numbers in the sets in any order. If there are several answers to that problem, print any of them. It is guaranteed that there is a solution.
standard output
PASSED
01c5ca5e3bcf71d57d16cb9a6ac7514d
train_004.jsonl
1304694000
Little Vasya likes very much to play with sets consisting of positive integers. To make the game more interesting, Vasya chose n non-empty sets in such a way, that no two of them have common elements.One day he wanted to show his friends just how interesting playing with numbers is. For that he wrote out all possible unions of two different sets on nΒ·(n - 1) / 2 pieces of paper. Then he shuffled the pieces of paper. He had written out the numbers in the unions in an arbitrary order.For example, if n = 4, and the actual sets have the following form {1, 3}, {5}, {2, 4}, {7}, then the number of set pairs equals to six. The six pieces of paper can contain the following numbers: 2, 7, 4. 1, 7, 3; 5, 4, 2; 1, 3, 5; 3, 1, 2, 4; 5, 7. Then Vasya showed the pieces of paper to his friends, but kept the n sets secret from them. His friends managed to calculate which sets Vasya had thought of in the first place. And how about you, can you restore the sets by the given pieces of paper?
256 megabytes
import java.io.*; import java.util.Arrays; import java.util.LinkedList; // BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); public class Sets { public static boolean equal(int[] a , int [] b) { for (int i = 0; i < b.length; i++) { if(a[i]!=b[i]) return false; } return true; } public static void main(String[] args) throws Exception { sets1 in = new sets1(System.in); int n = in.nextLong(); int till = n*(n-1)/2; if(n == 2) { int length = in.nextLong(); System.out.println(1+" "+in.nextLong()); System.out.print(length-1); for (int i = 1; i < length; i++) { System.out.print(" "+in.nextLong()); } System.out.println(); return; } number[] all = new number[200]; for (int i = 0; i < all.length; i++) { all[i] = new number(i+1, n); } for (int i = 0; i < till; i++) { int length = in.nextLong(); for (int j = 0; j < length; j++) { int temp = in.nextLong(); all[temp-1].where[all[temp-1].count++] = i; } } for (int i = 0; i < all.length; i++) { Arrays.sort(all[i].where); } boolean[] checked = new boolean[all.length]; for (int i = 0; i < all.length; i++) { if(checked[i]) continue; LinkedList<Integer> list = new LinkedList<Integer>(); list.add(i+1); checked[i] = true; if(all[i].count == 0) continue; for (int j = i+1; j < all.length; j++) { if(equal(all[i].where , all[j].where)) { list.add(j+1); checked[j] = true; } } System.out.print(list.size()); while(!list.isEmpty()) { System.out.print(" "+list.removeFirst()); } System.out.println(); } } } class sets1 { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public sets1(InputStream in) { din = new DataInputStream(in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public int nextLong() throws Exception { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = c == '-'; if (neg) c = read(); do { ret = ret * 10 + c - '0'; c = read(); } while (c > ' '); if (neg) return -ret; return ret; } public char nextChar() throws Exception { char ret = ' '; byte c = read(); while (c <= ' ') c = read(); ret = (char)c; return ret; } public String nextString() throws Exception { StringBuffer ret = new StringBuffer(); byte c = read(); while (c <= ' ') c = read(); do { ret = ret.append((char)c); c = read(); } while (c > ' '); return ret.toString(); } private void fillBuffer() throws Exception { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws Exception { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } } class number { int num; int[] where; int count; public number (int num , int length) { this.num = num; where = new int[length-1]; count = 0; } }
Java
["4\n3 2 7 4\n3 1 7 3\n3 5 4 2\n3 1 3 5\n4 3 1 2 4\n2 5 7", "4\n5 6 7 8 9 100\n4 7 8 9 1\n4 7 8 9 2\n3 1 6 100\n3 2 6 100\n2 1 2", "3\n2 1 2\n2 1 3\n2 2 3"]
2 seconds
["1 7 \n2 2 4 \n2 1 3 \n1 5", "3 7 8 9 \n2 6 100 \n1 1 \n1 2", "1 1 \n1 2 \n1 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation", "hashing" ]
bde894dc01c65da67d32c716981926f6
The first input file line contains a number n (2 ≀ n ≀ 200), n is the number of sets at Vasya's disposal. Then follow sets of numbers from the pieces of paper written on nΒ·(n - 1) / 2 lines. Each set starts with the number ki (2 ≀ ki ≀ 200), which is the number of numbers written of the i-th piece of paper, and then follow ki numbers aij (1 ≀ aij ≀ 200). All the numbers on the lines are separated by exactly one space. It is guaranteed that the input data is constructed according to the above given rules from n non-intersecting sets.
1,700
Print on n lines Vasya's sets' description. The first number on the line shows how many numbers the current set has. Then the set should be recorded by listing its elements. Separate the numbers by spaces. Each number and each set should be printed exactly once. Print the sets and the numbers in the sets in any order. If there are several answers to that problem, print any of them. It is guaranteed that there is a solution.
standard output