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 | d412a577b5e002c35bc7cd79c017741e | train_002.jsonl | 1379172600 | Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed. | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt() ;
int ans = 0 ;
String []cur = new String[n];
for(int i = 0 ; i < n ; i++){
cur[i] = sc.next() ;
}
int count = 1 ;
for(int i = 1 ; i < n ; i++){
if(cur[i-1].charAt(1) == cur[i].charAt(0)){
count++;
}
}
System.out.println(count);
}
}
| Java | ["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"] | 1 second | ["3", "2"] | NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets. | Java 6 | standard input | [
"implementation"
] | 6c52df7ea24671102e4c0eee19dc6bba | The first line of the input contains an integer n (1 ≤ n ≤ 100000) — the number of magnets. Then n lines follow. The i-th line (1 ≤ i ≤ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position. | 800 | On the single line of the output print the number of groups of magnets. | standard output | |
PASSED | 1f668763e7ac120c4670378ec32fed59 | train_002.jsonl | 1379172600 | Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed. | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt() ;
int ans = 0 ;
String []cur = new String[n];
for(int i = 0 ; i < n ; i++){
cur[i] = sc.next() ;
}
int count = 1 ;
for(int i = 1 ; i < n ; i++){
if(cur[i-1].charAt(1) == cur[i].charAt(0)){
count++;
}
}
System.out.println(count );
}
}
| Java | ["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"] | 1 second | ["3", "2"] | NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets. | Java 6 | standard input | [
"implementation"
] | 6c52df7ea24671102e4c0eee19dc6bba | The first line of the input contains an integer n (1 ≤ n ≤ 100000) — the number of magnets. Then n lines follow. The i-th line (1 ≤ i ≤ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position. | 800 | On the single line of the output print the number of groups of magnets. | standard output | |
PASSED | 882c5c43189099e1933b040a18ad8cc2 | train_002.jsonl | 1379172600 | Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed. | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
// int[] tn = new int[n];
String s = in.next();
char c=s.charAt(1);
int cmp=1;
for (int i = 1; i < n; i++) {
s=in.next();
if(s.charAt(0)==c){
cmp++;
}
c=s.charAt(1);
}
System.out.println(cmp);
}
}
| Java | ["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"] | 1 second | ["3", "2"] | NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets. | Java 6 | standard input | [
"implementation"
] | 6c52df7ea24671102e4c0eee19dc6bba | The first line of the input contains an integer n (1 ≤ n ≤ 100000) — the number of magnets. Then n lines follow. The i-th line (1 ≤ i ≤ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position. | 800 | On the single line of the output print the number of groups of magnets. | standard output | |
PASSED | c22e34bbe8360a50a21d7adfbcc92fac | train_002.jsonl | 1379172600 | Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed. | 256 megabytes |
import java.util.ArrayList;
import java.util.Scanner;
public class codeforce {
public static void main(String[] args)
{
int num,count=0,c=1;
Scanner obj= new Scanner(System.in);
num=obj.nextInt();
int arr[]=new int[num+1];
arr[0]=0;
for(int i=1;i<=num;i++)
{
arr[i]=obj.nextInt();
if(arr[i]!=arr[i-1])
{
count++;
}
}
System.out.print(count);
}}
| Java | ["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"] | 1 second | ["3", "2"] | NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets. | Java 6 | standard input | [
"implementation"
] | 6c52df7ea24671102e4c0eee19dc6bba | The first line of the input contains an integer n (1 ≤ n ≤ 100000) — the number of magnets. Then n lines follow. The i-th line (1 ≤ i ≤ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position. | 800 | On the single line of the output print the number of groups of magnets. | standard output | |
PASSED | c5fbd86c4af03f66bb8191f2032f6c92 | train_002.jsonl | 1439224200 | Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class B {
public static void main(String[] args) throws IOException {
FastScanner scan = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int n = scan.nextInt();
TreeSet<Integer> v = new TreeSet<Integer>();
TreeSet<Integer> u = new TreeSet<Integer>();
for(int i = 1; i <= n; i++) u.add(i);
int[] a = new int[n];
for(int i = 0; i < n; i++){
a[i] = scan.nextInt();
if(v.contains(a[i]) || a[i] > n)a[i] = -1;
else {
v.add(a[i]);
u.remove(a[i]);
}
}
for(int i = 0; i < n; i++){
if(a[i] != -1) out.println(a[i]);
else out.println(u.pollFirst());
}
out.close();
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(br.readLine());
} catch (Exception e){e.printStackTrace();}
}
public String next() {
if (st.hasMoreTokens()) return st.nextToken();
try {st = new StringTokenizer(br.readLine());}
catch (Exception 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 String nextLine() {
String line = "";
try {line = br.readLine();}
catch (Exception e) {e.printStackTrace();}
return line;
}
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 double[] nextDoubleArray(int n){
double[] a = new double[n];
for(int i = 0; i < n; i++) a[i] = nextDouble();
return a;
}
public char[][] nextGrid(int n, int m){
char[][] grid = new char[n][m];
for(int i = 0; i < n; i++) grid[i] = next().toCharArray();
return grid;
}
}
}
| Java | ["3\n1 3 2", "4\n2 2 3 3", "1\n2"] | 1 second | ["1 3 2", "2 1 3 4", "1"] | NoteIn the first test the numeration is already a permutation, so there is no need to change anything.In the second test there are two pairs of equal numbers, in each pair you need to replace one number.In the third test you need to replace 2 by 1, as the numbering should start from one. | Java 8 | standard input | [
"greedy",
"math"
] | 1cfd0e6504bba7db9ec79e2f243b99b4 | The first line contains a single integer n — the number of items (1 ≤ n ≤ 105). The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — the initial inventory numbers of the items. | 1,200 | Print n numbers — the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. | standard output | |
PASSED | ad6fe1bd06d87f481637ed37ef78dd63 | train_002.jsonl | 1439224200 | Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. | 256 megabytes | import java.io.*;
import java.util.*;
public class B {
public static void solution(BufferedReader reader, PrintWriter out)
throws IOException {
In in = new In(reader);
int n = in.nextInt();
int[] a = new int[n];
boolean[] used1 = new boolean[100001];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
used1[a[i]] = true;
}
boolean[] used2 = new boolean[100001];
for (int i = 0, j = 1; i < n; i++) {
if (a[i] > n || used2[a[i]]) {
while (used1[j])
j++;
a[i] = j++;
}
else
used2[a[i]] = true;
}
out.print(a[0]);
for (int i = 1; i < n; i++)
out.printf(" %d", a[i]);
out.println();
}
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(
new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(
new BufferedWriter(new OutputStreamWriter(System.out)));
solution(reader, out);
out.close();
}
protected static class In {
private BufferedReader reader;
private StringTokenizer tokenizer = new StringTokenizer("");
public In(BufferedReader reader) {
this.reader = reader;
}
public String next() throws IOException {
while (!tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(reader.readLine());
return tokenizer.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
}
}
| Java | ["3\n1 3 2", "4\n2 2 3 3", "1\n2"] | 1 second | ["1 3 2", "2 1 3 4", "1"] | NoteIn the first test the numeration is already a permutation, so there is no need to change anything.In the second test there are two pairs of equal numbers, in each pair you need to replace one number.In the third test you need to replace 2 by 1, as the numbering should start from one. | Java 8 | standard input | [
"greedy",
"math"
] | 1cfd0e6504bba7db9ec79e2f243b99b4 | The first line contains a single integer n — the number of items (1 ≤ n ≤ 105). The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — the initial inventory numbers of the items. | 1,200 | Print n numbers — the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. | standard output | |
PASSED | e3b832dc809e59b9f89f8feed71061fe | train_002.jsonl | 1439224200 | Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class Inventory2 {
static int[] dictionary = new int[100001];
static ArrayList<Integer> differences(int[] a, int[] b, int n) {
ArrayList<Integer> d = new ArrayList<Integer>();
for (int i = 0; i < n; i++) {
int curA = a[i], curB = b[i];
dictionary[curA]++;
dictionary[curB]++;
}
for (int i = 0; i < n + 1; i++) {
if (dictionary[i] == 1)
d.add(i);
dictionary[i] = 0;
}
return d;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int[] a = new int[n];
int [] res = new int [n];
int k = 0;
int c = 0;
StringTokenizer st = new StringTokenizer(br.readLine());
for (int i = 0; i < n; i++) {
a[i] = Integer.parseInt(st.nextToken());
}
int[] oneToN = new int[n];
for (int i = 0; i < n; i++) {
oneToN[i] = i + 1;
}
ArrayList<Integer> d = differences(a, oneToN, n);
int s = d.size();
for (int i = 0; i < n; i++) {
if(dictionary[a[i]] == 0 && a[i] <= n && a[i] >= 1){
res[k++] = a[i];
dictionary[a[i]] = 1;
}
else{
if(c < s){
int x = d.get(c);
if(dictionary[x] == 0 && x <= n && x >= 1){
res[k++] = x;
dictionary[x] = 1;
c++;
}
}
}
}
for (int i = 0; i < n; i++) {
if(res[i] != 0)
System.out.print(res[i]+" ");
}
}
}
| Java | ["3\n1 3 2", "4\n2 2 3 3", "1\n2"] | 1 second | ["1 3 2", "2 1 3 4", "1"] | NoteIn the first test the numeration is already a permutation, so there is no need to change anything.In the second test there are two pairs of equal numbers, in each pair you need to replace one number.In the third test you need to replace 2 by 1, as the numbering should start from one. | Java 8 | standard input | [
"greedy",
"math"
] | 1cfd0e6504bba7db9ec79e2f243b99b4 | The first line contains a single integer n — the number of items (1 ≤ n ≤ 105). The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — the initial inventory numbers of the items. | 1,200 | Print n numbers — the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. | standard output | |
PASSED | 3a8ea72dfbc7dc0ca9e40ed7c6433f86 | train_002.jsonl | 1439224200 | Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
static class FastScanner {
BufferedReader reader;
StringTokenizer tokenizer;
public FastScanner(InputStream stream) {
this.reader = new BufferedReader(new InputStreamReader(stream));
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public int[] nextIntegerArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < a.length; i++) {
a[i] = nextInt();
}
return a;
}
public long[] nextLongArray(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < a.length; i++) {
a[i] = nextLong();
}
return a;
}
public int nextInt(int radix) throws IOException {
return Integer.parseInt(next(), radix);
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public long nextLong(int radix) throws IOException {
return Long.parseLong(next(), radix);
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public BigInteger nextBigInteger() throws IOException {
return new BigInteger(next());
}
public BigInteger nextBigInteger(int radix) throws IOException {
return new BigInteger(next(), radix);
}
public String next() throws IOException {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
return this.next();
}
return tokenizer.nextToken();
}
public void close() throws IOException {
this.reader.close();
}
}
//SOLUTION //
FastScanner in = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) throws IOException{
new Main().solve();
}//void main
void solve() throws IOException{
int n=in.nextInt();
int[] a=new int[n+1];
int[] t=new int[100002];
for(int i=1; i<=n; i++)
{ a[i]=in.nextInt();
t[a[i]]=9;
}
int j=1;
for(int i=1;i<=n;i++){
if(t[a[i]]==9 && a[i] <= n)
{t[a[i]]++;continue;}
for(;true;j++){
if(t[j]==0)
{a[i]=j;t[j]++;break;}
}
}
for(int i=1;i<=n;i++)
out.print(a[i]+" ");
in.close();
out.close();
}
}
| Java | ["3\n1 3 2", "4\n2 2 3 3", "1\n2"] | 1 second | ["1 3 2", "2 1 3 4", "1"] | NoteIn the first test the numeration is already a permutation, so there is no need to change anything.In the second test there are two pairs of equal numbers, in each pair you need to replace one number.In the third test you need to replace 2 by 1, as the numbering should start from one. | Java 8 | standard input | [
"greedy",
"math"
] | 1cfd0e6504bba7db9ec79e2f243b99b4 | The first line contains a single integer n — the number of items (1 ≤ n ≤ 105). The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — the initial inventory numbers of the items. | 1,200 | Print n numbers — the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. | standard output | |
PASSED | ebccfc8c72302268acbb51776c4bf1b2 | train_002.jsonl | 1439224200 | Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. | 256 megabytes | import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
public class B569 {
public static void main(String[] args) {
// TODO Auto-generated method stub.
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int[] list = new int[n];
int[] map = new int[100001];
for(int i = 0; i < n; i++){
int temp = scan.nextInt();
list[i] = temp;
map[temp]++;
}
int temp = 1;
for(int j = 0; j < n; j++){
int i = list[j];
if(map[i] > 1 || i > n){
while(map[temp] > 0){
temp++;
}
map[temp]++;
map[i]--;
list[j] = temp;
}
}
for(int e:list)
System.out.print(e+" ");
}
}
| Java | ["3\n1 3 2", "4\n2 2 3 3", "1\n2"] | 1 second | ["1 3 2", "2 1 3 4", "1"] | NoteIn the first test the numeration is already a permutation, so there is no need to change anything.In the second test there are two pairs of equal numbers, in each pair you need to replace one number.In the third test you need to replace 2 by 1, as the numbering should start from one. | Java 8 | standard input | [
"greedy",
"math"
] | 1cfd0e6504bba7db9ec79e2f243b99b4 | The first line contains a single integer n — the number of items (1 ≤ n ≤ 105). The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — the initial inventory numbers of the items. | 1,200 | Print n numbers — the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. | standard output | |
PASSED | 25711a47fa0919e1c11a79df57ab6a5f | train_002.jsonl | 1439224200 | Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. | 256 megabytes | import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class MainA {
public static void main(String[] args) throws IOException {
new MainA().solve();
}
PrintWriter out;
boolean[] u;
ArrayList<Integer>[] g;
int cnt = 0;
int ind = 0;
int n;
int[] a = new int[1000000];
long MOD = 1000000007;
void solve() throws IOException{
Reader in = new Reader("input.txt");
out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out)) );
// out = new PrintWriter(new FileWriter(new File("output.txt")));
int n = in.nextInt();
int[] a = new int[1000000];
int[] b = new int[1000000];
for (int i = 0; i < n; i++) {
int x = in.nextInt();
b[i] = x;
a[x]++;
}
Queue<Integer> q = new LinkedList<>();
for (int i = 1; i <= n; i++)
if (a[i] == 0)
q.add(i);
for (int i = 0; i < n; i++)
if (a[b[i]] > 1 || b[i] > n) {
out.print(q.poll() + " ");
a[b[i]]--;
}
else
if (a[b[i]] == 1)
out.print(b[i]+" ");
out.flush();
out.close();
}
static class Pair implements Comparable<Pair> {
int a;
int b;
public Pair( int a, int b) {
this.a = a;
this.b = b;
}
@Override
public int compareTo(Pair o) {
if (o.a > a) return -1;
if (o.a < a) return 1;
if (o.b < b) return 1;
if (o.b > b) return -1;
return 0;
}
}
class Reader {
StringTokenizer token;
BufferedReader in;
public Reader(String file) throws IOException {
// in = new BufferedReader( new FileReader( file ) );
in = new BufferedReader( new InputStreamReader( System.in ) );
}
public byte nextByte() throws IOException {
return Byte.parseByte(Next());
}
public int nextInt() throws IOException {
return Integer.parseInt(Next());
}
public long nextLong() throws IOException {
return Long.parseLong(Next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(Next());
}
public String nextString() throws IOException {
return in.readLine();
}
private String Next() throws IOException {
while (token == null || !token.hasMoreTokens()) {
token = new StringTokenizer(in.readLine());
}
return token.nextToken();
}
}
} | Java | ["3\n1 3 2", "4\n2 2 3 3", "1\n2"] | 1 second | ["1 3 2", "2 1 3 4", "1"] | NoteIn the first test the numeration is already a permutation, so there is no need to change anything.In the second test there are two pairs of equal numbers, in each pair you need to replace one number.In the third test you need to replace 2 by 1, as the numbering should start from one. | Java 8 | standard input | [
"greedy",
"math"
] | 1cfd0e6504bba7db9ec79e2f243b99b4 | The first line contains a single integer n — the number of items (1 ≤ n ≤ 105). The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — the initial inventory numbers of the items. | 1,200 | Print n numbers — the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. | standard output | |
PASSED | e0f141f158caec5c5cb559fd52e8ca7d | train_002.jsonl | 1439224200 | Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
import java.util.stream.*;
@SuppressWarnings("unchecked")
public class P596B {
class Pair {
int v, i;
public Pair(int v, int i) {
this.v = v;
this.i = i;
}
@Override
public String toString() {
return Integer.toString(v);
// return ("[v=" + v + ", i=" + i + "]");
}
}
//--------------------------------------------
public void run() throws Exception {
int n = nextInt();
List<Pair> fp = new ArrayList(), ap = new ArrayList();
BitSet fv = new BitSet(n + 1);
fv.set(1, n + 1);
for (int i = 0; i < n; i++) {
Pair p = new Pair(nextInt(), i);
if (fv.get(p.v)) {
fv.clear(p.v);
ap.add(p);
} else {
fp.add(p);
}
}
for (int i = 0, ni = fv.nextSetBit(0); i < fp.size(); i++, ni = fv.nextSetBit(ni + 1)) {
Pair p = fp.get(i);
p.v = ni;
ap.add(p);
}
fp = null; fv = null;
ap.sort(new Comparator<Pair>() {
public int compare(Pair a, Pair b) {
return (a.i - b.i);
}
});
for (Pair p : ap) {
print(p + " ");
}
}
public static void main(String... args) throws Exception {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedOutputStream(System.out));
new P596B().run();
br.close();
pw.close();
System.err.println("\n[Time : " + (System.currentTimeMillis() - startTime) + " ms]");
}
static long startTime = System.currentTimeMillis();
static BufferedReader br;
static PrintWriter pw;
StringTokenizer stok;
String nextToken() throws IOException {
while (stok == null || !stok.hasMoreTokens()) {
String s = br.readLine();
if (s == null) { return null; }
stok = new StringTokenizer(s);
}
return stok.nextToken();
}
void print(byte b) { print("" + b); }
void print(int i) { print("" + i); }
void print(long l) { print("" + l); }
void print(double d) { print("" + d); }
void print(char c) { print("" + c); }
void print(Object o) {
if (o instanceof int[]) { print(Arrays.toString((int [])o));
} else if (o instanceof long[]) { print(Arrays.toString((long [])o));
} else if (o instanceof char[]) { print(Arrays.toString((char [])o));
} else if (o instanceof byte[]) { print(Arrays.toString((byte [])o));
} else if (o instanceof short[]) { print(Arrays.toString((short [])o));
} else if (o instanceof boolean[]) { print(Arrays.toString((boolean [])o));
} else if (o instanceof float[]) { print(Arrays.toString((float [])o));
} else if (o instanceof double[]) { print(Arrays.toString((double [])o));
} else if (o instanceof Object[]) { print(Arrays.toString((Object [])o));
} else { print("" + o); }
}
void print(String s) { pw.print(s); }
void println() { println(""); }
void println(byte b) { println("" + b); }
void println(int i) { println("" + i); }
void println(long l) { println("" + l); }
void println(double d) { println("" + d); }
void println(char c) { println("" + c); }
void println(Object o) { print(o); println(); }
void println(String s) { pw.println(s); }
int nextInt() throws IOException { return Integer.parseInt(nextToken()); }
long nextLong() throws IOException { return Long.parseLong(nextToken()); }
double nextDouble() throws IOException { return Double.parseDouble(nextToken()); }
char nextChar() throws IOException { return (char) (br.read()); }
String next() throws IOException { return nextToken(); }
String nextLine() throws IOException { return br.readLine(); }
int [] readInt(int size) throws IOException {
int [] array = new int [size];
for (int i = 0; i < size; i++) { array[i] = nextInt(); }
return array;
}
long [] readLong(int size) throws IOException {
long [] array = new long [size];
for (int i = 0; i < size; i++) { array[i] = nextLong(); }
return array;
}
double [] readDouble(int size) throws IOException {
double [] array = new double [size];
for (int i = 0; i < size; i++) { array[i] = nextDouble(); }
return array;
}
String [] readLines(int size) throws IOException {
String [] array = new String [size];
for (int i = 0; i < size; i++) { array[i] = nextLine(); }
return array;
}
int gcd(int a, int b) {
return ((b > 0) ? gcd(b, a % b) : a);
}
long gcd(long a, long b) {
return ((b > 0) ? gcd(b, a % b) : a);
}
} | Java | ["3\n1 3 2", "4\n2 2 3 3", "1\n2"] | 1 second | ["1 3 2", "2 1 3 4", "1"] | NoteIn the first test the numeration is already a permutation, so there is no need to change anything.In the second test there are two pairs of equal numbers, in each pair you need to replace one number.In the third test you need to replace 2 by 1, as the numbering should start from one. | Java 8 | standard input | [
"greedy",
"math"
] | 1cfd0e6504bba7db9ec79e2f243b99b4 | The first line contains a single integer n — the number of items (1 ≤ n ≤ 105). The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — the initial inventory numbers of the items. | 1,200 | Print n numbers — the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. | standard output | |
PASSED | 65e7d4cb19e257969ae7e8fd30bf4d74 | train_002.jsonl | 1439224200 | Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. | 256 megabytes | // 569B - Inventory
// http://codeforces.com/contest/569/problem/B
// Farwa Naqi
import java.util.*;
import java.lang.*;
import java.io.*;
public class Inventory569B
{
public static void main (String[] args) throws java.lang.Exception
{
// Input
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] frequency = new int[n];
List<Integer> a = new ArrayList<Integer>();
while (sc.hasNext()) {
int num = sc.nextInt();
a.add(num);
// Only increment frequency of valid numbers (1 to n)
if (num > 0 && num <= n) {
frequency[num-1]++;
}
}
// Find all the missing nums
List<Integer> missingNums = new ArrayList<Integer>();
for (int i = 0; i < n; i++) {
if (frequency[i] == 0) {
missingNums.add(i+1);
}
}
int index = 0;
// Iterate the inventory and find duplicate/out-of-bound numbers
for (int i = 0; i < a.size(); i++) {
int num = a.get(i);
// Check if it's greater than n; if it is, replace
if (num > n) {
System.out.print(missingNums.get(index)+" ");
index++;
} else if (frequency[num-1] > 1) {
System.out.print(missingNums.get(index)+" ");
index++;
frequency[num-1]--;
} else {
System.out.print(num+" ");
}
}
}
} | Java | ["3\n1 3 2", "4\n2 2 3 3", "1\n2"] | 1 second | ["1 3 2", "2 1 3 4", "1"] | NoteIn the first test the numeration is already a permutation, so there is no need to change anything.In the second test there are two pairs of equal numbers, in each pair you need to replace one number.In the third test you need to replace 2 by 1, as the numbering should start from one. | Java 8 | standard input | [
"greedy",
"math"
] | 1cfd0e6504bba7db9ec79e2f243b99b4 | The first line contains a single integer n — the number of items (1 ≤ n ≤ 105). The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — the initial inventory numbers of the items. | 1,200 | Print n numbers — the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. | standard output | |
PASSED | f1886c291b12c680f51c62d9ae250905 | train_002.jsonl | 1439224200 | Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. | 256 megabytes | import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
public class Code569B {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] a = new int[n];
BitSet used = new BitSet(n + 1);
BitSet changeList = new BitSet(n);
for(int i = 0; i < n; i++) {
a[i] = scanner.nextInt();
if(a[i] <= n && !used.get(a[i])) {
used.set(a[i]);
} else
changeList.set(i);
}
int index = -1;
for(int i = used.nextClearBit(1); i <= n; i = used.nextClearBit(i + 1)) {
index = changeList.nextSetBit(index + 1);
a[index] = i;
}
for(int i = 0; i < n; i++)
System.out.print(a[i] + " ");
System.out.println();
scanner.close();
}
}
| Java | ["3\n1 3 2", "4\n2 2 3 3", "1\n2"] | 1 second | ["1 3 2", "2 1 3 4", "1"] | NoteIn the first test the numeration is already a permutation, so there is no need to change anything.In the second test there are two pairs of equal numbers, in each pair you need to replace one number.In the third test you need to replace 2 by 1, as the numbering should start from one. | Java 8 | standard input | [
"greedy",
"math"
] | 1cfd0e6504bba7db9ec79e2f243b99b4 | The first line contains a single integer n — the number of items (1 ≤ n ≤ 105). The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — the initial inventory numbers of the items. | 1,200 | Print n numbers — the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. | standard output | |
PASSED | 7dadb8a21c326fda410e8d0cdb4edf9d | train_002.jsonl | 1439224200 | Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. | 256 megabytes | import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
public class Code569B {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] a = new int[n];
int[] dp = new int[(int) (Math.pow(10, 5) + 1)];
List<Integer> changeList = new ArrayList<>();
for(int i = 0; i < n; i++) {
a[i] = scanner.nextInt();
dp[a[i]]++;
if(a[i] > n || dp[a[i]] >= 2)
changeList.add(i);
}
for(int i = 0, j = 1; i < changeList.size(); i++) {
while(true) {
if(dp[j] < 1)
break;
j++;
}
a[changeList.get(i)] = j++;
}
for(int i = 0; i < n; i++)
System.out.print(a[i] + " ");
System.out.println();
scanner.close();
}
}
| Java | ["3\n1 3 2", "4\n2 2 3 3", "1\n2"] | 1 second | ["1 3 2", "2 1 3 4", "1"] | NoteIn the first test the numeration is already a permutation, so there is no need to change anything.In the second test there are two pairs of equal numbers, in each pair you need to replace one number.In the third test you need to replace 2 by 1, as the numbering should start from one. | Java 8 | standard input | [
"greedy",
"math"
] | 1cfd0e6504bba7db9ec79e2f243b99b4 | The first line contains a single integer n — the number of items (1 ≤ n ≤ 105). The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — the initial inventory numbers of the items. | 1,200 | Print n numbers — the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. | standard output | |
PASSED | 189163716a820e50ca73453710bbedf2 | train_002.jsonl | 1439224200 | Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. | 256 megabytes | import javafx.util.Pair;
import java.awt.geom.Line2D;
import java.io.*;
import java.util.*;
public class Main {
private final static InputReader ir = new InputReader(System.in);
private final static OutputWriter ow = new OutputWriter(System.out);
private final static int INF = Integer.MAX_VALUE;
private final static int NINF = Integer.MIN_VALUE;
private final static double PI = Math.PI;
public static void main(String[] args) throws IOException {
try {
task();
} finally {
boolean exc = false;
try {
ir.close();
} catch (IOException e) {
e.printStackTrace();
exc = true;
}
try {
ow.close();
} catch (IOException e) {
e.printStackTrace();
exc = true;
}
if (exc) System.exit(1);
}
}
private static void task() throws IOException {
int n = ir.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; ++i) {
a[i] = ir.nextInt() - 1;
}
boolean[] used1 = new boolean[n];
int cnt = 0;
for (int i = 0; i < n; ++i) {
if (a[i] < n) {
if (!used1[a[i]]) {
used1[a[i]] = true;
cnt++;
}
}
}
int[] free = new int[n - cnt];
int cur = 0;
for (int i = 0; i < n; ++i) {
if (!used1[i])
free[cur++] = i;
}
boolean[] used2 = new boolean[n];
for (int i = 0; i < n; ++i) {
if (a[i] >= n || used2[a[i]]) {
a[i] = free[--cur];
}
used2[a[i]] = true;
}
for (int i = 0; i < n; ++i) {
ow.print((a[i] + 1) + " ");
}
/*
int n = ir.nextInt(), w = ir.nextInt(), v = ir.nextInt(), u = ir.nextInt();
ArrayList<Pair<Integer, Integer>> cord = new ArrayList<>(n);
for (int i = 0; i < n; ++i) {
cord.add(new Pair<>(ir.nextInt(), ir.nextInt()));
}
// int ymin = cord.stream().min(Comparator.comparing(Pair::getValue)).get().getValue();
// double safetime =
boolean go = true;
for (int i = 0; i < n && go; ++i) {
int x = cord.get(i).getKey();
int y = cord.get(i).getValue();
double time = (double) x / w;
double s = time * u;
if (s < y) {
go = false;
}
}
if (go) {
ow.print((double) w / u);
} else {
cord.sort(Comparator.comparing(Pair::getValue));
double ans = 0.0;
double pos = 0;
for (int i = 0; i < n; ++i) {
int x = cord.get(i).getKey();
int y = cord.get(i).getValue();
double time = (double) x / w;
double s = time * u + pos;
if (s >= y) {
ans = Math.max(ans, time);
pos = s;
} else { // ждать
}
}
ow.print(ans);
}
*/
}
private static int max(int... objects) {
if (objects.length == 0)
throw new IllegalArgumentException("objects.length == 0");
int max = objects[0];
for (int i = 1; i < objects.length; ++i) {
if (max < objects[i])
max = objects[i];
}
return max;
}
private static int min(int... objects) {
if (objects.length == 0)
throw new IllegalArgumentException("objects.length == 0");
int min = objects[0];
for (int i = 1; i < objects.length; ++i) {
if (min > objects[i])
min = objects[i];
}
return min;
}
private static long pow(int x, int n) {
if (x == 0) return 0;
if (x == 1 || n == 0) return 1;
if (x == 2) return x << (n - 1);
if (n == 1) return x;
long t = pow(x, n / 2);
if (n % 2 == 0) return t * t;
else return t * t * x;
}
private static double pow(double x, int n) {
if (x == 0.0) return 0;
if (x == 1.0 || n == 0) return 1;
if (n == 1) return x;
double t = pow(x, n / 2);
if (n % 2 == 0) return t * t;
else return t * t * x;
}
private static int abs(int a) {
return (a >= 0 ? a : -a);
}
}
class InputReader implements AutoCloseable {
private final InputStream in;
private int capacity;
private byte[] buffer;
private int len = 0;
private int cur = 0;
public InputReader(InputStream stream) {
this(stream, 100_000);
}
public InputReader(InputStream stream, int capacity) {
this.in = stream;
this.capacity = capacity;
buffer = new byte[capacity];
}
private boolean update() {
if (cur >= len) {
try {
cur = 0;
len = in.read(buffer, 0, capacity);
if (len <= 0)
return false;
} catch (IOException e) {
throw new InputMismatchException();
}
}
return true;
}
private int read() {
if (update())
return buffer[cur++];
else return -1;
}
public boolean isEmpty() {
return !update();
}
private boolean isSpace(int c) {
return c == '\n' || c == '\t' || c == '\r' || c == ' ';
}
private boolean isEscape(int c) {
return c == '\n' || c == '\t' || c == '\r' || c == -1;
}
private int readSkipSpace() {
int c;
do {
c = read();
} while (isSpace(c));
return c;
}
public int nextInt() {
int c = readSkipSpace();
if (c < 0)
throw new InputMismatchException();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c == -1) break;
if (c < '0' || c > '9')
throw new InputMismatchException();
res = res * 10 + c - '0';
if (res < 0)
throw new InputMismatchException();
c = read();
} while (!isSpace(c));
res *= sgn;
return res;
}
public int[] getAllInts() {
List<Integer> list = new LinkedList<>();
while (true) {
try {
int t = nextInt();
list.add(t);
} catch (InputMismatchException e) {
break;
}
}
int[] a = new int[list.size()];
Iterator<Integer> it = list.iterator();
for (int i = 0; it.hasNext(); ++i)
a[i] = it.next();
return a;
}
public int[] getIntArray1D(int n) {
int[] array = new int[n];
for (int i = 0; i < n; ++i) {
array[i] = nextInt();
}
return array;
}
public int[][] getIntArray2D(int n, int m) {
int[][] array = new int[n][m];
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j)
array[i][j] = nextInt();
}
return array;
}
public long nextLong() {
int c = readSkipSpace();
if (c < 0)
throw new InputMismatchException();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c == -1) break;
if (c < '0' || c > '9')
throw new InputMismatchException();
res = res * 10 + c - '0';
if (res < 0)
throw new InputMismatchException();
c = read();
} while (!isSpace(c));
res *= sgn;
return res;
}
public long[] getAllLongs() {
List<Long> list = new LinkedList<>();
while (true) {
try {
long t = nextLong();
list.add(t);
} catch (InputMismatchException e) {
break;
}
}
long[] a = new long[list.size()];
Iterator<Long> it = list.iterator();
for (int i = 0; it.hasNext(); ++i)
a[i] = it.next();
return a;
}
public long[] getLongArray1D(int n) {
long[] array = new long[n];
for (int i = 0; i < n; ++i) {
array[i] = nextLong();
}
return array;
}
public long[][] getLongArray2D(int n, int m) {
long[][] array = new long[n][m];
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j)
array[i][j] = nextLong();
}
return array;
}
public int nextChar() {
int c = readSkipSpace();
if (c < 0)
throw new InputMismatchException();
return c;
}
public String nextLine(int initialCapacity) {
StringBuilder res = new StringBuilder(initialCapacity);
int c = readSkipSpace();
do {
res.append((char) (c));
c = read();
} while (!isEscape(c));
return res.toString();
}
@Override
public void close() throws IOException {
in.close();
}
}
class OutputWriter implements Flushable, AutoCloseable {
private byte[] buf;
private final int capacity;
private int count;
private OutputStream out;
public OutputWriter(OutputStream stream) {
this(stream, 10_000);
}
public OutputWriter(OutputStream stream, int capacity) {
if (capacity < 0)
throw new IllegalArgumentException("capacity < 0");
out = stream;
this.capacity = capacity;
if (capacity != 0) {
buf = new byte[capacity];
}
}
public void write(int b) throws IOException {
if (capacity != 0) {
if (count >= capacity)
flushBuffer();
buf[count++] = (byte) b;
} else {
out.write(b);
}
}
public void write(byte[] bytes, int off, int len) throws IOException {
if (capacity != 0) {
if (len >= capacity) {
flushBuffer();
out.write(bytes, off, len);
return;
}
if (len > capacity - count)
flushBuffer();
System.arraycopy(bytes, off, buf, count, len);
count += len;
} else out.write(bytes, off, len);
}
public void write(byte[] bytes) throws IOException {
write(bytes, 0, bytes.length);
}
public void println() throws IOException {
print("\n");
}
public void print(Object object) throws IOException {
write(String.valueOf(object).getBytes());
}
public void println(Object object) throws IOException {
print(object);
println();
}
public void print(int... ints) throws IOException {
print(" ", ints);
}
public void println(int... ints) throws IOException {
print(ints);
println();
}
public void println(String separator, int... ints) throws IOException {
print(separator, ints);
println();
}
public void print(String separator, int... ints) throws IOException {
if (ints.length == 0) throw new IllegalArgumentException("ints.length == 0");
for (int i = 0; i < ints.length; ++i) {
if (i != 0) print(separator);
print(ints[i]);
}
}
private void flushBuffer() throws IOException {
if (count > 0) {
out.write(buf, 0, count);
count = 0;
}
}
@Override
public void flush() throws IOException {
flushBuffer();
out.flush();
}
@Override
public void close() throws IOException {
flush();
out.close();
}
}
| Java | ["3\n1 3 2", "4\n2 2 3 3", "1\n2"] | 1 second | ["1 3 2", "2 1 3 4", "1"] | NoteIn the first test the numeration is already a permutation, so there is no need to change anything.In the second test there are two pairs of equal numbers, in each pair you need to replace one number.In the third test you need to replace 2 by 1, as the numbering should start from one. | Java 8 | standard input | [
"greedy",
"math"
] | 1cfd0e6504bba7db9ec79e2f243b99b4 | The first line contains a single integer n — the number of items (1 ≤ n ≤ 105). The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — the initial inventory numbers of the items. | 1,200 | Print n numbers — the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. | standard output | |
PASSED | b6fed5d24f6eba124b854c5c47dfb389 | train_002.jsonl | 1439224200 | Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. | 256 megabytes | //package codeforces;
import java.io.IOException;
import java.util.*;
public class B569 {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] arr = new int[n];
HashMap<Integer, Integer> map1 = new HashMap<>();
HashMap<Integer, Integer> map2 = new HashMap<>();
for (int i = 1 ; i <= n; i++) map1.put(i, i);
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
map1.remove(arr[i]);
}
LinkedList<Integer> q = new LinkedList<>();
for (Integer key: map1.keySet()) q.push(key);
for (int i = 0; i < n; i++) {
if (map2.containsKey(arr[i]) || arr[i] > n) arr[i] = q.poll();
map2.put(arr[i], arr[i]);
System.out.print(arr[i] + " ");
}
}
}
class tuple {
public int value, index;
tuple(int a, int b) {
value = a;
index = b;
}
} | Java | ["3\n1 3 2", "4\n2 2 3 3", "1\n2"] | 1 second | ["1 3 2", "2 1 3 4", "1"] | NoteIn the first test the numeration is already a permutation, so there is no need to change anything.In the second test there are two pairs of equal numbers, in each pair you need to replace one number.In the third test you need to replace 2 by 1, as the numbering should start from one. | Java 8 | standard input | [
"greedy",
"math"
] | 1cfd0e6504bba7db9ec79e2f243b99b4 | The first line contains a single integer n — the number of items (1 ≤ n ≤ 105). The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — the initial inventory numbers of the items. | 1,200 | Print n numbers — the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. | standard output | |
PASSED | 2b09ed79273ec65e4b4f13c8edbaed97 | train_002.jsonl | 1439224200 | Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. | 256 megabytes |
import java.awt.Point;
import java.awt.geom.Line2D;
import java.io.BufferedReader;
import java.io.File;
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.security.GuardedObject;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Scanner;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
import java.io.InputStream;
import java.math.BigInteger;
import javax.activation.CommandInfo;
/**
* 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;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
long var=System.currentTimeMillis();
solver.solve(1, in, out);
/*if(System.getProperty("ONLINE_JUDGE")==null){
out.println("["+(double)(System.currentTimeMillis()-var)/1000+"]");
}*/
out.close();
}
}
class Pair {
long x,y,index;
Pair(long x,long y,int index){
this.x=x;
this.y=y;
this.index=index;
}
public String toString(){
return this.x+" "+this.y+" ";
}
}
class tupple{
long x,y,z;
ArrayList<String> list=new ArrayList<>();
tupple(long x,long y,long z){
this.x=x;
this.y=y;
this.z=z;
}
tupple(tupple cl){
this.x=cl.x;
this.y=cl.y;
this.z=cl.z;
this.list=cl.list;
}
}
class Edge{
int u;
int v;
int time;
long cost;
public Edge(int u,int v){
this.u=u;
this.v=v;
time=Integer.MAX_VALUE;
}
public int other(int x){
if(u==x)return v;
return u;
}
}
class Ss{
Integer a[]=new Integer[3];
Ss(Integer a[]){
this.a=a;
}
public int hashCode(){
return a[0].hashCode()+a[1].hashCode()+a[2].hashCode();
}
public boolean equals(Object o){
Ss x=(Ss)o;
for(int i=0;i<3;i++){
if(x.a[i]!=this.a[i]){
return false;
}
}
return true;
}
}
class queary{
int type;
int l;
int r;
int index;
queary(int type,int l,int r){
this.type=type;
this.l=l;
this.r=r;
}
}
class boat implements Comparable<boat>{
int capacity;
int index;
boat(int capacity,int index)
{
this.capacity=capacity;
this.index=index;
}
@Override
public int compareTo(boat o) {
// TODO Auto-generated method stub
return this.capacity-o.capacity;
}
}
class angle{
double x,y,angle;
int index;
angle(int x,int y,double angle){
this.x=x;
this.y=y;
this.angle=angle;
}
}
class TaskC {
static long mod=(long)(1e9+7);
// SegTree tree;
// int min[];
static int prime_len=100001;
static int prime[]=new int[prime_len];
static ArrayList<Integer> primes=new ArrayList<>();
static{
for(int i=2;i<=Math.sqrt(prime.length);i++){
for(int j=i*i;j<prime.length;j+=i){
prime[j]=i;
}
}
for(int i=2;i<prime.length;i++){
if(prime[i]==0){
primes.add(i);
}
}
// System.out.println("end");
// prime[0]=true;
// prime[1]=1;
}
/*
* long pp[]=new long[10000001];
pp[0]=0;
pp[1]=1;
for(int i=2;i<pp.length;i++){
if(prime[i]!=0){
int gcd=(int)greatestCommonDivisor(i/prime[i], prime[i]);
pp[i]=(pp[i/prime[i]]*pp[prime[i]]*gcd)/pp[(int)gcd];
}
else
pp[i]=i-1;
}
* */
boolean visited[][];
char mat[][];
static int time=0;
public void solve(int testNumber, FastScanner in, PrintWriter out) throws IOException {
int n=in.nextInt();
Pair a[]=new Pair[n];
int arr[]=new int[n+1];
ArrayList<Pair> list=new ArrayList<>();
ArrayList<Pair> list1=new ArrayList<>();
for(int i=0;i<n;i++){
int x=in.nextInt();
a[i]=new Pair(x, x, i);
if(a[i].x<=n){
arr[x]++;
if(arr[x]>1){
list1.add(a[i]);
}
}
else{
list.add(a[i]);
}
}
for(int i=1;i<=n && !list.isEmpty();i++){
if(arr[i]==0){
arr[i]=1;
Pair p=list.remove(list.size()-1);
p.x=i;
}
}
for(int i=1;i<=n && !list1.isEmpty();i++){
if(arr[i]==0){
arr[i]=1;
Pair p=list1.remove(list1.size()-1);
p.x=i;
}
}
Arrays.sort(a,new Comparator<Pair>() {
@Override
public int compare(Pair o1, Pair o2) {
// TODO Auto-generated method stub
return (int)(o1.index-o2.index);
}
});
for(int i=0;i<n;i++){
out.print(a[i].x+" ");;
}
out.println();
}
static void dfs(List<Integer>[] graph, boolean[] used, List<Integer> res, int u,int parent,List<Integer> collection) {
used[u] = true;
Integer uu=new Integer(u);
collection.add(uu);
for (int v : graph[u]){
if (!used[v]){
dfs(graph, used, res, v,u,collection);
}
else if(collection.contains(v)){
System.out.println("Impossible");
System.exit(0);
}
}
collection.remove(uu);
res.add(u);
}
public static List<Integer> topologicalSort(List<Integer>[] graph) {
int n = graph.length;
boolean[] used = new boolean[n];
List<Integer> res = new ArrayList<>();
for (int i = 0; i < n; i++)
if (!used[i])
dfs(graph, used, res, i,-1,new ArrayList<Integer>());
Collections.reverse(res);
return res;
}
static class pairs{
String company,color;
String type;
boolean visit=false;
pairs(String company,String color,String type){
this.company=company;
this.color=color;
this.type=type;
}
}
BigInteger BMOD=BigInteger.valueOf(mod);
private long inv(long q) {
return BigInteger.valueOf(q).modInverse(BMOD).longValue();
}
static void dfs1(List<Integer>[] graph, boolean[] used, List<Integer> res, int u) {
used[u] = true;
for (int v : graph[u])
if (!used[v])
dfs1(graph, used, res, v);
res.add(u);
}
public static List<Integer> topologicalSort1(List<Integer>[] graph) {
int n = graph.length;
boolean[] used = new boolean[n];
List<Integer> res = new ArrayList<>();
for (int i = n-1; i >0; i--)
if (!used[i])
dfs1(graph, used, res, i);
Collections.reverse(res);
return res;
}
public static long[][] mulmatrix(long m1[][],long m2[][],long mod){
long ans[][]=new long[m1.length][m2[0].length];
for(int i=0;i<m1.length;i++){
for(int j=0;j<m2[0].length;j++){
for(int k=0;k<m1.length;k++){
ans[i][j]+=(m1[i][k]*m2[k][j]);
ans[i][j]%=mod;
}
}
}
return ans;
}
public static long[][] matrixexpo(long m[][],String n,long mod){
if(n.equals("1")){
return m.clone();
}
if(n.equals("10")){
return mulmatrix(m, m , mod);
}
else{
long temp [][]=matrixexpo(m,n.substring(0,n.length()-1),mod);
temp=mulmatrix(temp, temp, mod);
if(n.charAt(n.length()-1)=='0')return temp;
else return mulmatrix(temp, m,mod);
}
}
public static boolean isCompatible(long x[],long y[]){
for(int i=0;i<x.length-1;i++){
if(x[i]==y[i] && x[i+1]==y[i+1] && x[i]==x[i+1] && y[i]==y[i+1]){
return false;
}
}
return true;
}
int phi(int n) {
int res = n;
for (int i = 2; i * i <= n; ++i) {
if (n % i == 0) {
while (n % i == 0) {
n /= i;
}
res -= res / i;
}
}
if (n != 1) {
res -= res / n;
}
return res;
}
long pow(long x,long y,long mod){
if(y<=0){
return 1;
}
if(y==1){
return x%mod;
}
long temp=pow(x,y/2,mod);
if(y%2==0){
return (temp*temp)%mod;
}
else{
return (((temp*temp)%mod)*x)%mod;
}
}
/* long DP(int id,int mask){
//System.out.println("hi"+dp[id][mask]+" "+id+" "+Integer.toBinaryString(mask));
if(id==0 && mask==0){
dp[0][mask]=1;
return 1;
}
else if(id==0){
dp[0][mask]=0;
return 0;
}
if(dp[id][mask]!=-1){
return dp[id][mask];
}
long ans=0;
for(int i=0;i<n;i++){
if((mask & (1<<i))!=0 && c[i][id]>=1){
ans+=DP(id-1,mask ^ (1 << i));
ans%=mod;
}
}
ans+=DP(id-1,mask);
ans%=mod;
dp[id][mask]=ans;
return ans;
}*/
static long greatestCommonDivisor (long m, long n){
long x;
long y;
while(m%n != 0){
x = n;
y = m%n;
m = x;
n = y;
}
return n;
}
long no_of_primes(long m,long n,long k){
long count=0,i,j;
int primes []=new int[(int)(n-m+2)];
if(m==1) primes[0] = 1;
for(i=2; i<=Math.sqrt(n); i++)
{
j = (m/i); j *= i;
if(j<m)
j+=i;
for(; j<=n; j+=i)
{
if(j!=i)
primes[(int)(j-m)] = 1;
}
}
for(i=0; i<=n-m; i++)
if(primes[(int)i]==0 && (i-1)%k==0)
count++;
return count;
}
}
class SegTree {
int n;
long t[];
long mod=(long)(1000000007);
SegTree(int n,long t[]){
this.n=n;
this.t=t;
build();
}
void build() { // build the tree
for (int i = n - 1; i > 0; --i)
t[i]=Math.max(t[i<<1],t[i<<1|1]);
}
void modify(int p, long value) { // set value at position p
for (t[p += n]=value; p > 1; p >>= 1) t[p>>1] = Math.max(t[p], t[p^1]);
}
long query(int l, int r) { // sum on interval [l, r)
long res=Integer.MIN_VALUE;
for (l += n, r += n; l < r; l >>= 1, r >>= 1) {
if ((l&1)!=0) res=Math.max(res,t[l++]);
if ((r&1)!=0) res=Math.max(res,t[--r]);
}
return res;
}
//
//
//
}
class FastScanner
{
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar;
private int snumChars;
private SpaceCharFilter filter;
public FastScanner(InputStream stream) {
this.stream = stream;
}
public int snext() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = snext();
while (isSpaceChar(c))
c = snext();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = snext();
while (isSpaceChar(c))
c = snext();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
class UF {
private int[] parent; // parent[i] = parent of i
private byte[] rank; // rank[i] = rank of subtree rooted at i (never more than 31)
private int count; // number of components
public UF(int N) {
if (N < 0) throw new IllegalArgumentException();
count = N;
parent = new int[N];
rank = new byte[N];
for (int i = 0; i < N; i++) {
parent[i] = i;
rank[i] = 0;
}
}
public int find(int p) {
if (p < 0 || p >= parent.length) throw new IndexOutOfBoundsException();
while (p != parent[p]) {
parent[p] = parent[parent[p]]; // path compression by halving
p = parent[p];
}
return p;
}
public int count() {
return count;
}
public boolean connected(int p, int q) {
return find(p) == find(q);
}
public boolean union(int p, int q) {
int rootP = find(p);
int rootQ = find(q);
if (rootP == rootQ) return false;
// make root of smaller rank point to root of larger rank
if (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ;
else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP;
else {
parent[rootQ] = rootP;
rank[rootP]++;
}
count--;
return true;
}
}
| Java | ["3\n1 3 2", "4\n2 2 3 3", "1\n2"] | 1 second | ["1 3 2", "2 1 3 4", "1"] | NoteIn the first test the numeration is already a permutation, so there is no need to change anything.In the second test there are two pairs of equal numbers, in each pair you need to replace one number.In the third test you need to replace 2 by 1, as the numbering should start from one. | Java 8 | standard input | [
"greedy",
"math"
] | 1cfd0e6504bba7db9ec79e2f243b99b4 | The first line contains a single integer n — the number of items (1 ≤ n ≤ 105). The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — the initial inventory numbers of the items. | 1,200 | Print n numbers — the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. | standard output | |
PASSED | b891394a496e1ad5cc9b45290366f8db | train_002.jsonl | 1439224200 | Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. | 256 megabytes | import java.io.*;
import java.util.*;
public class B {
private static final long modulo = 1000000007;
//
private static void solve() {
int N = in.nextInt();
int a[] = new int[N];
Set<Integer> hasSet = new HashSet<>();
Set<Integer> wasSet = new HashSet<>();
Queue<Integer> queue = new LinkedList<>();
for (int i = 0; i < N; i++) {
a[i] = in.nextInt();
if (a[i] >= 1 && a[i] <= N) {
//
} else {
a[i] = 1;
}
hasSet.add(a[i]);
}
for (int i = 1; i <= N; i++) {
if (!hasSet.contains(i)) {
queue.add(i);
}
}
for (int i = 0; i < N; i++) {
if (!wasSet.contains(a[i])) {
wasSet.add(a[i]);
} else {
a[i] = queue.poll();
}
}
for (int i = 0; i < N - 1; i++) {
out.print(a[i] + " ");
}
out.print(a[N - 1]);
}
private static long inverse(long a) {
long result = 1;
int n = (int) modulo - 2;
while (n != 0) {
if ((n & 1) == 1)
result = (result * a) % modulo;
a = (a * a) % modulo;
n >>= 1;
}
return result;
}
private static long pow(long a, long n) {
if (n == 0) return 1;
if (n % 2 == 0) {
long ans = pow(a, n / 2);
return ans * ans;
} else {
return a * pow(a, n - 1);
}
}
public static void main(String[] args) {
solve();
closeStreams();
}
private static void closeStreams() {
in.close();
out.close();
}
private static final FastScanner in = new FastScanner();
private static final PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
public static class FastScanner {
private BufferedReader br;
private 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;
}
void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} | Java | ["3\n1 3 2", "4\n2 2 3 3", "1\n2"] | 1 second | ["1 3 2", "2 1 3 4", "1"] | NoteIn the first test the numeration is already a permutation, so there is no need to change anything.In the second test there are two pairs of equal numbers, in each pair you need to replace one number.In the third test you need to replace 2 by 1, as the numbering should start from one. | Java 8 | standard input | [
"greedy",
"math"
] | 1cfd0e6504bba7db9ec79e2f243b99b4 | The first line contains a single integer n — the number of items (1 ≤ n ≤ 105). The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — the initial inventory numbers of the items. | 1,200 | Print n numbers — the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. | standard output | |
PASSED | 99b430fa6b5d21bc06086e46f4a2e113 | train_002.jsonl | 1439224200 | Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. | 256 megabytes | import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
public class CodeForce {
static boolean flag=false;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
//int t=Integer.parseInt(br.readLine()); while(t-->0) {
int n = Integer.parseInt(br.readLine());
int[] count=new int[100001];
String[] sr=br.readLine().split(" ");
int[] arr=new int[n];
for(int i=0;i<n;i++)
{
int x=Integer.parseInt(sr[i]);
arr[i]=x;
count[x]++;}
int j=1;
for(int i=0;i<n;i++)
{
if((count[arr[i]]>1)||(arr[i]>n))
{
while(j<=n)
{
if(count[j]==0)
{ count[j]++;System.out.print(j+" "); j++;break;}
j++;
}
count[arr[i]]--;
}
else
System.out.print(arr[i]+" ");
}
}
}
| Java | ["3\n1 3 2", "4\n2 2 3 3", "1\n2"] | 1 second | ["1 3 2", "2 1 3 4", "1"] | NoteIn the first test the numeration is already a permutation, so there is no need to change anything.In the second test there are two pairs of equal numbers, in each pair you need to replace one number.In the third test you need to replace 2 by 1, as the numbering should start from one. | Java 8 | standard input | [
"greedy",
"math"
] | 1cfd0e6504bba7db9ec79e2f243b99b4 | The first line contains a single integer n — the number of items (1 ≤ n ≤ 105). The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — the initial inventory numbers of the items. | 1,200 | Print n numbers — the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. | standard output | |
PASSED | 2e60997c3806a53bf8b72712e7a48411 | train_002.jsonl | 1439224200 | Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. | 256 megabytes |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
public class Inventory {
public static void main(String[] args) throws Exception{
BufferedReader inp = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(inp.readLine());
String[] x = inp.readLine().split("\\s+");
int[] a = new int[n];
for(int i = 0; i < n; i++)
a[i] = Integer.parseInt(x[i]);
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < n; i++){
if(!map.containsKey(a[i]))
map.put(a[i], 0);
map.put(a[i], map.get(a[i]) + 1);
}
//System.out.println(map);
if(n > 1){
int i = 1; // i= 1 ----> n
int j = 0;
while(i <= n && j < n){
if(map.get(a[j]) > 1 || a[j] > n){ //corrections are to be made here
if(map.get(i) == null){ //"i" isn't present in the hasmap
map.put(a[j], map.get(a[j]) - 1);
a[j] = i++;
j++;
}
else
i++;
}
else
j++;
}
for(int k = 0; k < n; k++)
System.out.print(a[k] + " ");
}
else
System.out.println(1);
}
}
| Java | ["3\n1 3 2", "4\n2 2 3 3", "1\n2"] | 1 second | ["1 3 2", "2 1 3 4", "1"] | NoteIn the first test the numeration is already a permutation, so there is no need to change anything.In the second test there are two pairs of equal numbers, in each pair you need to replace one number.In the third test you need to replace 2 by 1, as the numbering should start from one. | Java 8 | standard input | [
"greedy",
"math"
] | 1cfd0e6504bba7db9ec79e2f243b99b4 | The first line contains a single integer n — the number of items (1 ≤ n ≤ 105). The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — the initial inventory numbers of the items. | 1,200 | Print n numbers — the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. | standard output | |
PASSED | 5e44e096b565e2b160eaf3ebebbb1612 | train_002.jsonl | 1439224200 | Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. | 256 megabytes | import java.awt.event.ComponentAdapter;
import java.io.*;
import java.util.*;
import java.util.Arrays;
import java.util.function.Consumer;
import java.util.function.Predicate;
public class Main {
static MyScanner in;
static PrintWriter out;
//static Timer t = new Timer();
public static void main(String[] args) throws IOException {
in = new MyScanner();
out = new PrintWriter(System.out, true);
int n = in.nextInt();
int[] arr = in.nextInts(n);
int[] bools = new int[n + 1];
for(int a : arr)
if (a <= n && bools[a] == 0)
bools[a] = 1;
int last_pos = 0;
for (int a : arr) {
if (a <= n && bools[a] == 1) {
out.print(a);
bools[a] = 2;
} else {
while (bools[++last_pos] != 0) ;
out.print(last_pos);
}
out.print(' ');
}
out.println();
}
}
class MyScanner {
private final BufferedReader br;
private StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public MyScanner(String path) throws IOException {
br = new BufferedReader(new FileReader(new File(path)));
//br = new BufferedReader(new InputStreamReader(new FileInputStream(
//new File(path)), "cp1251"));
}
String next() throws IOException {
while (st == null || !st.hasMoreElements())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
String nextLine() throws IOException {
st = null;
return br.readLine();
}
boolean hasNext() {
if (st != null && st.hasMoreElements())
return true;
try {
while (st == null || !st.hasMoreElements())
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
return false;
}
return true;
}
String[] nextStrings(int n) throws IOException {
String[] arr = new String[n];
for (int i = 0; i < n; i++)
arr[i] = next();
return arr;
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
int[] nextInts(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
Integer[] nextIntegers(int n) throws IOException {
Integer[] arr = new Integer[n];
for (int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
int[][] next2Ints(int n, int m) throws IOException {
int[][] arr = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
arr[i][j] = nextInt();
return arr;
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
long[] nextLongs(int n) throws IOException {
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = nextLong();
return arr;
}
long[][] next2Longs(int n, int m) throws IOException {
long[][] arr = new long[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
arr[i][j] = nextLong();
return arr;
}
double nextDouble() throws IOException {
return Double.parseDouble(next().replace(',', '.'));
}
double[] nextDoubles(int size) throws IOException {
double[] arr = new double[size];
for (int i = 0; i < size; i++)
arr[i] = nextDouble();
return arr;
}
boolean nextBool() throws IOException {
String s = next();
if (s.equalsIgnoreCase("true") || s.equals("1"))
return true;
if (s.equalsIgnoreCase("false") || s.equals("0"))
return false;
throw new IOException("Boolean expected, String found!");
}
}
| Java | ["3\n1 3 2", "4\n2 2 3 3", "1\n2"] | 1 second | ["1 3 2", "2 1 3 4", "1"] | NoteIn the first test the numeration is already a permutation, so there is no need to change anything.In the second test there are two pairs of equal numbers, in each pair you need to replace one number.In the third test you need to replace 2 by 1, as the numbering should start from one. | Java 8 | standard input | [
"greedy",
"math"
] | 1cfd0e6504bba7db9ec79e2f243b99b4 | The first line contains a single integer n — the number of items (1 ≤ n ≤ 105). The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — the initial inventory numbers of the items. | 1,200 | Print n numbers — the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. | standard output | |
PASSED | 0829f94bff8c905a9859f4f28b482bcd | train_002.jsonl | 1439224200 | Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. | 256 megabytes |
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class C {
public static Scanner scan = new Scanner(System.in);
public static void solve () {
int n=scan.nextInt();
int[] a= new int[n];
HashSet<Integer> h= new HashSet<Integer>();
for(int i=0;i<n;i++) a[i]=scan.nextInt();
for (Integer integer : a) h.add(integer);
Queue<Integer> toAdd= new LinkedList<>();
for (int i = 1; i <=n; i++) {
if(!h.contains(i)) toAdd.add(i);
}
//System.out.println(toAdd);
h = new HashSet<Integer>();
int[] res = new int[n];
for(int i=0;i<n;i++) {
if(a[i]>=1 && a[i]<=n && !h.contains(a[i])) {
h.add(a[i]);
res[i]=a[i];
}
else res[i]=toAdd.poll();
System.out.print(res[i]+" ");
}
}
public static void main(String[] args) {
solve();
scan.close();
}
}
| Java | ["3\n1 3 2", "4\n2 2 3 3", "1\n2"] | 1 second | ["1 3 2", "2 1 3 4", "1"] | NoteIn the first test the numeration is already a permutation, so there is no need to change anything.In the second test there are two pairs of equal numbers, in each pair you need to replace one number.In the third test you need to replace 2 by 1, as the numbering should start from one. | Java 8 | standard input | [
"greedy",
"math"
] | 1cfd0e6504bba7db9ec79e2f243b99b4 | The first line contains a single integer n — the number of items (1 ≤ n ≤ 105). The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — the initial inventory numbers of the items. | 1,200 | Print n numbers — the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. | standard output | |
PASSED | 32d277bf44df5de9ca6fc28ec3463972 | train_002.jsonl | 1439224200 | Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. | 256 megabytes |
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Second {
//static long m=1000000007;
/*public static long gcd(long x,long y)
{
if(x%y==0)
return y;
else return gcd(y,x%y);
}*/
public static int prime(int n)
{
int f=1;
if(n==1)
return 0;
for(int i=2;i<=(Math.sqrt(n));)
{
if(n%i==0)
{
f=0;
break;
}
if(i==2)
i++;
else
i+=2;
}
if(f==1)
return 1;
else
return 0;
}
static BigInteger ways(int N, int K) {
BigInteger ret = BigInteger.ONE;
for(int i=N;i>=N-K+1;i--)
{
ret = ret.multiply(BigInteger.valueOf(i));
}
for (int j = 1; j<=K; j++) {
ret = ret.divide(BigInteger.valueOf(j));
}
ret=ret.mod(BigInteger.valueOf(1000000007));
return ret;
}
public static BigInteger fact(int n)
{
BigInteger f=BigInteger.ONE;
for(int i=1;i<=n;i++)
{
f=f.multiply(BigInteger.valueOf(i));
}
//f=f.mod(BigInteger.valueOf(m));
return f;
}
public static int gcd(int x,int y)
{
if(x%y==0)
return y;
else return gcd(y,x%y);
}
public static int max(int a,int b)
{
if(a>b)
return a;
else
return b;
}
public static int min(int a,int b)
{
if(a>b)
return b;
else
return a;
}
public static void main(String[] args) throws Exception{
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb=new StringBuilder("");
//int t=Integer.parseInt(br.readLine());
// while(t-->0)
//{
//int n=Integer.parseInt(br.readLine());
//String l[]=br.readLine().split(" ");
//l=br.readLine().split(" ");
// int m=Integer.parseInt(l[0]);
//char ch=a.charAt();
// char c[]=new char[n];
//int a[]=new int[n];
//int a[]=new int[n][n];
//HashMap<Integer,Integer>hm=new HashMap<Integer,Integer>();
//HashMap<Integer,String>hm=new HashMap<Integer,String>();
//HashMap<Integer,Long>hm=new HashMap<Integer,Long>();
//hm.put(1,1);
//HashSet<Integer>hs=new HashSet<Integer>();
//HashSet<Long>hs=new HashSet<Long>();
//HashSet<String>hs=new HashSet<String>();
//hs.add(x);
//Stack<Integer>s=new Stack<Integer>();
//s.push(x);
//s.pop(x);
//Queue<Integer>q=new LinkedList<Integer>();
//q.add(x);
//q.remove(x);
//long a[]=new long[n];
//long x=Long.parseLong(l[0]);
//for(int i=0;i<n;i++)
//{
//a[i]=Long.parseLong(l[i]);
//}
//int min=100000000;
// String a=br.readLine();
//for(int i=0;i<n;i++)
//{
//a[i]=Integer.parseInt(l[i]);
//}
// char a[]=c.toCharArray();
//char ch=l[0].charAt(0);
//long c1=(long)Math.ceil(n/(double)a);
//Arrays.sort(a);
HashMap<Integer,Integer>hm=new HashMap<Integer,Integer>();
int n=Integer.parseInt(br.readLine());
String l[]=br.readLine().split(" ");
int a[]=new int[n];
int b[]=new int[n];
boolean c[]=new boolean[n+1];
boolean d[]=new boolean[n+1];
for(int i=0;i<n;i++)
{
a[i]=Integer.parseInt(l[i]);
if(a[i]<=n)
c[a[i]]=true;
if(hm.get(a[i])==null)
hm.put(a[i],1);
else
{
int x=hm.get(a[i]);
hm.put(a[i],x+1);
}
}
int j=1;
for(int i=0;i<n;i++)
{
if(a[i]>n)
{
for(;j<=n;j++)
{
if(!c[j])
{
a[i]=j;
c[j]=true;
break;
}
}
}
else if(a[i]<=n&&!d[a[i]])
{
int x=hm.get(a[i]);
if(x==1)
{
hm.remove(a[i]);
}
else
{
d[a[i]]=true;
}
}
else
{
for(;j<=n;j++)
{
if(!c[j])
{
a[i]=j;
c[j]=true;
break;
}
}
}
}
for(int i=0;i<n;i++)
{
System.out.print(a[i]+" ");
}
// sb.append("").append("\n");
// System.out.println(" ");
/*for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
}
}*/
//}
}
} | Java | ["3\n1 3 2", "4\n2 2 3 3", "1\n2"] | 1 second | ["1 3 2", "2 1 3 4", "1"] | NoteIn the first test the numeration is already a permutation, so there is no need to change anything.In the second test there are two pairs of equal numbers, in each pair you need to replace one number.In the third test you need to replace 2 by 1, as the numbering should start from one. | Java 8 | standard input | [
"greedy",
"math"
] | 1cfd0e6504bba7db9ec79e2f243b99b4 | The first line contains a single integer n — the number of items (1 ≤ n ≤ 105). The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — the initial inventory numbers of the items. | 1,200 | Print n numbers — the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. | standard output | |
PASSED | c4f542c2b4c77f8d968e4b60722a2757 | train_002.jsonl | 1439224200 | Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. | 256 megabytes | import java.util.*;
public class inventory
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
int n=in.nextInt();
int a[]=new int[n+1];
int b[]=new int[n+1];
//int c[]=new int[n+1];
int ind[]=new int[n+1];
int i,j,k=1,min,pos=-1;
for(i=1;i<=n;i++)
{
a[i]=in.nextInt();
if(a[i]<=n && b[a[i]]==0)
b[a[i]]=1;
else
{
// c[k]=a[i];
ind[k]=i;
k++;
}
}
k=1;
for(i=1;i<=n;i++)
{
if(b[i]==0)
{
a[ind[k]]=i;
k++;
//a[ind[pos]]=i;
}
}
System.out.print(a[1]);
for(i=2;i<=n;i++)
System.out.print(" "+a[i]);
}
} | Java | ["3\n1 3 2", "4\n2 2 3 3", "1\n2"] | 1 second | ["1 3 2", "2 1 3 4", "1"] | NoteIn the first test the numeration is already a permutation, so there is no need to change anything.In the second test there are two pairs of equal numbers, in each pair you need to replace one number.In the third test you need to replace 2 by 1, as the numbering should start from one. | Java 8 | standard input | [
"greedy",
"math"
] | 1cfd0e6504bba7db9ec79e2f243b99b4 | The first line contains a single integer n — the number of items (1 ≤ n ≤ 105). The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — the initial inventory numbers of the items. | 1,200 | Print n numbers — the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. | standard output | |
PASSED | 85775c3afc8145b98b645bebe318e25b | train_002.jsonl | 1439224200 | Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. | 256 megabytes | /*package whatever //do not write package name here */
import java.io.*;
import java.util.*;
public class GFG {
public static void main (String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[]a=new int[n];
int []b=new int[n];
Arrays.fill(b,0);
TreeSet<Integer> ts=new TreeSet<Integer>();
for(int i=1;i<=n;i++)ts.add(i);
for(int i=0;i<n;++i){
a[i]=sc.nextInt();
if(a[i]>n){
a[i]=1;
}
ts.remove(a[i]);
b[a[i]-1]=1;
}
for(int i=0;i<n;i++){
if(b[a[i]-1]>0){
b[a[i]-1]--;
}else{
a[i]=ts.pollFirst();
}
}
System.out.println(Arrays.toString(a).replace("[","").replace("]","").replace(",",""));
}
} | Java | ["3\n1 3 2", "4\n2 2 3 3", "1\n2"] | 1 second | ["1 3 2", "2 1 3 4", "1"] | NoteIn the first test the numeration is already a permutation, so there is no need to change anything.In the second test there are two pairs of equal numbers, in each pair you need to replace one number.In the third test you need to replace 2 by 1, as the numbering should start from one. | Java 8 | standard input | [
"greedy",
"math"
] | 1cfd0e6504bba7db9ec79e2f243b99b4 | The first line contains a single integer n — the number of items (1 ≤ n ≤ 105). The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — the initial inventory numbers of the items. | 1,200 | Print n numbers — the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. | standard output | |
PASSED | 4f4894420e83c71069d9ede13b59216e | train_002.jsonl | 1439224200 | Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. | 256 megabytes | import java.util.*;
public class Inventory {
private static Scanner sc;
public static void main(String[] args) {
sc = new Scanner(System.in);
int n = sc.nextInt();
int [] array = new int [n];
int [] check = new int [n];
int x;
for(int i = 0; i < n; i++) {
x = sc.nextInt();
if( x > n)
x = 1;
if(check[x-1] == 0)
array[i] = x;
check[x-1]++;
}
int j = 0;
for(int i = 0; i < n; i++) {
if(array[i] ==0) {
for(; j < n; j++) {
if(check[j] == 0){
array[i] = j+1;
check[j]++;
break;
}
}
}
}
for(int i = 0; i < n; i++)
System.out.print(array[i] + " ");
}
}
| Java | ["3\n1 3 2", "4\n2 2 3 3", "1\n2"] | 1 second | ["1 3 2", "2 1 3 4", "1"] | NoteIn the first test the numeration is already a permutation, so there is no need to change anything.In the second test there are two pairs of equal numbers, in each pair you need to replace one number.In the third test you need to replace 2 by 1, as the numbering should start from one. | Java 8 | standard input | [
"greedy",
"math"
] | 1cfd0e6504bba7db9ec79e2f243b99b4 | The first line contains a single integer n — the number of items (1 ≤ n ≤ 105). The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — the initial inventory numbers of the items. | 1,200 | Print n numbers — the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. | standard output | |
PASSED | 8d852281cde102da8c2cf43f5d4b7308 | train_002.jsonl | 1439224200 | Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. | 256 megabytes | import javafx.util.Pair;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.*;
public class Main {
public static Scanner scanner;
public static List<Integer> labels = new ArrayList<>();
public static List<Integer> unusedIndexes = new ArrayList<>();
public static boolean[] check = new boolean[100005];
public static void main(String args[]) throws FileNotFoundException {
// scanner = new Scanner(new FileInputStream("cf.in"));
scanner = new Scanner(System.in);
int n = scanner.nextInt();
for (int i = 0; i < n; ++i) {
int x = scanner.nextInt();
check[x] = true;
labels.add(x);
}
for (int i = 1; i <= n; ++i)
if (!check[i])
unusedIndexes.add(i);
else
check[i] = false;
int lastUnusedIndex = 0;
for (int i = 0; i < n; ++i) {
if (labels.get(i) > n || check[labels.get(i)])
labels.set(i, unusedIndexes.get(lastUnusedIndex++));
else
check[labels.get(i)] = true;
}
labels.forEach(integer -> System.out.print(integer + " "));
}
}
| Java | ["3\n1 3 2", "4\n2 2 3 3", "1\n2"] | 1 second | ["1 3 2", "2 1 3 4", "1"] | NoteIn the first test the numeration is already a permutation, so there is no need to change anything.In the second test there are two pairs of equal numbers, in each pair you need to replace one number.In the third test you need to replace 2 by 1, as the numbering should start from one. | Java 8 | standard input | [
"greedy",
"math"
] | 1cfd0e6504bba7db9ec79e2f243b99b4 | The first line contains a single integer n — the number of items (1 ≤ n ≤ 105). The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — the initial inventory numbers of the items. | 1,200 | Print n numbers — the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. | standard output | |
PASSED | 4068c39d51ab0b048b8f58393f903681 | train_002.jsonl | 1439224200 | Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. | 256 megabytes | import java.io.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.TreeSet;
/**
* Created by Shreyans Sheth [bholagabbar] on 8/10/2015 at 9:53 PM using IntelliJ IDEA (Fast IO Template)
*/
public class B
{
public static void main(String[] args) throws Exception
{
//System.setIn(new FileInputStream("E:/Shreyans/Documents/Code/CODE/src/Stdin_File_Read.txt"));
InputReader in = new InputReader(System.in);
OutputWriter out = new OutputWriter(System.out);
int n=in.readInt();
ArrayList<Integer>al=new ArrayList<Integer>();
TreeSet<Integer>ts=new TreeSet<Integer>();
for(int i=1;i<=n;i++)
ts.add(i);
int []a=new int[n];
for(int i=0;i<n;i++)
{
a[i]=in.readInt();
ts.remove(a[i]);
}
ArrayList<Integer>ans=new ArrayList<Integer>();
HashSet<Integer>hs=new HashSet<Integer>();
for(int i=0;i<n;i++)
{
if(a[i]<=n && !hs.contains(a[i]))
{
ans.add(a[i]);
hs.add(a[i]);
}
else if((a[i]<=n && hs.contains(a[i])))
ans.add(ts.pollFirst());
else if(a[i]>n)
ans.add(ts.pollFirst());
}
for(int i:ans)
out.print(i+" ");
{
out.close();
}
}
//FAST IO
private 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 String readString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public double readDouble()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.')
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.')
{
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public long readLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next()
{
return readString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
private 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]);
}
writer.flush();
}
public void printLine(Object... objects)
{
print(objects);
writer.println();
writer.flush();
}
public void close()
{
writer.close();
}
public void flush()
{
writer.flush();
}
}
} | Java | ["3\n1 3 2", "4\n2 2 3 3", "1\n2"] | 1 second | ["1 3 2", "2 1 3 4", "1"] | NoteIn the first test the numeration is already a permutation, so there is no need to change anything.In the second test there are two pairs of equal numbers, in each pair you need to replace one number.In the third test you need to replace 2 by 1, as the numbering should start from one. | Java 8 | standard input | [
"greedy",
"math"
] | 1cfd0e6504bba7db9ec79e2f243b99b4 | The first line contains a single integer n — the number of items (1 ≤ n ≤ 105). The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — the initial inventory numbers of the items. | 1,200 | Print n numbers — the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. | standard output | |
PASSED | d3d872ec2f998494ec3c94e6b3c5c7d3 | train_002.jsonl | 1439224200 | Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. | 256 megabytes | import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int size = in.nextInt();
boolean[] can_use_SN = new boolean[size + 1];
int[] SN = new int[size];
boolean[] need_to_renumber = new boolean[size];
for (int i = 1; i <= size; i++) {
can_use_SN[i] = true;
}
for (int i = 0; i < size; i++) {
SN[i] = in.nextInt();
if (SN[i] <= size && can_use_SN[SN[i]]) {
can_use_SN[SN[i]] = false;
} else {
need_to_renumber[i] = true;
}
}
int ptr = 1;
for (int i = 0; i < size; i++) {
if (need_to_renumber[i]) {
while (!can_use_SN[ptr]) {
ptr++;
}
can_use_SN[ptr] = false;
System.out.print(ptr);
} else {
System.out.print(SN[i]);
}
System.out.print(" ");
}
}
} | Java | ["3\n1 3 2", "4\n2 2 3 3", "1\n2"] | 1 second | ["1 3 2", "2 1 3 4", "1"] | NoteIn the first test the numeration is already a permutation, so there is no need to change anything.In the second test there are two pairs of equal numbers, in each pair you need to replace one number.In the third test you need to replace 2 by 1, as the numbering should start from one. | Java 8 | standard input | [
"greedy",
"math"
] | 1cfd0e6504bba7db9ec79e2f243b99b4 | The first line contains a single integer n — the number of items (1 ≤ n ≤ 105). The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — the initial inventory numbers of the items. | 1,200 | Print n numbers — the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. | standard output | |
PASSED | 3fa57014f42872eb7c5266a58191caab | train_002.jsonl | 1439224200 | Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. | 256 megabytes | import java.util.HashSet;
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
HashSet<Integer> numbers_to_use = new HashSet<>();
int size = in.nextInt();
for (int i = 1; i <= size; i++) {
numbers_to_use.add(i);
}
int[] SN = new int[size];
boolean[] need_to_renumber = new boolean[size];
for (int i = 0; i < size; i++) {
SN[i] = in.nextInt();
if (numbers_to_use.contains(SN[i])){
numbers_to_use.remove(SN[i]);
}else{
need_to_renumber[i] = true;
}
}
Integer[] renumbers = numbers_to_use.toArray(new Integer[numbers_to_use.size()]);
int ptr = 0;
for (int i=0;i<size;i++){
if (need_to_renumber[i]){
System.out.print(renumbers[ptr]);
ptr++;
}
else{
System.out.print(SN[i]);
}
System.out.print(" ");
}
}
} | Java | ["3\n1 3 2", "4\n2 2 3 3", "1\n2"] | 1 second | ["1 3 2", "2 1 3 4", "1"] | NoteIn the first test the numeration is already a permutation, so there is no need to change anything.In the second test there are two pairs of equal numbers, in each pair you need to replace one number.In the third test you need to replace 2 by 1, as the numbering should start from one. | Java 8 | standard input | [
"greedy",
"math"
] | 1cfd0e6504bba7db9ec79e2f243b99b4 | The first line contains a single integer n — the number of items (1 ≤ n ≤ 105). The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — the initial inventory numbers of the items. | 1,200 | Print n numbers — the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. | standard output | |
PASSED | 1517b951c5e59ff0548a32cb28e95a24 | train_002.jsonl | 1439224200 | Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. | 256 megabytes | import java.util.HashMap;
import java.util.Scanner;
public class Inventory {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner t = new Scanner(System.in);
int n = t.nextInt();
int[] a = new int[n];
HashMap<Integer, Integer> map = new HashMap<>();
int step = 1;
for (int i = 0; i < n; i++) {
a[i] = t.nextInt();
map.put(i + 1, 0);
}
for (int i = 0; i < n; i++) {
if (a[i] <= n)
map.put(a[i], map.get(a[i]) + 1);
else {
a[i] = 0;
}
}
for (int i = 0; i < n; i++) {
if (a[i] == 0) {
while (map.get(step) >= 1) {
step++;
}
a[i] = step;
map.put(a[i], 1);
} else if (map.get(a[i]) == 1) {
//
} else if (map.get(a[i]) > 1) {
while (map.get(step) >= 1) {
step++;
}
map.put(a[i], map.get(a[i]) - 1);
a[i] = step;
map.put(a[i], 1);
} else {
//
}
}
for (int i = 0; i < n; i++)
System.out.print(a[i] + " ");
}
}
| Java | ["3\n1 3 2", "4\n2 2 3 3", "1\n2"] | 1 second | ["1 3 2", "2 1 3 4", "1"] | NoteIn the first test the numeration is already a permutation, so there is no need to change anything.In the second test there are two pairs of equal numbers, in each pair you need to replace one number.In the third test you need to replace 2 by 1, as the numbering should start from one. | Java 8 | standard input | [
"greedy",
"math"
] | 1cfd0e6504bba7db9ec79e2f243b99b4 | The first line contains a single integer n — the number of items (1 ≤ n ≤ 105). The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — the initial inventory numbers of the items. | 1,200 | Print n numbers — the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. | standard output | |
PASSED | fc61d405b9f91388adb393da6165b32d | train_002.jsonl | 1439224200 | Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main implements Runnable {
public void solve() throws IOException {
int n = nextInt();
int[] a = new int[n];
for(int i = 0; i < n; i++)
a[i] = nextInt();
boolean[] used = new boolean[100000 + 10];
int[] result = new int[n];
for(int i = 0; i < n; i++){
if(!used[a[i]] && a[i] <= n){
result[i] = a[i];
used[a[i]] = true;
}
}
int curId = 1;
for(int i = 0; i < n; i++){
if(result[i] == 0){
while(used[curId]) curId++;
result[i] = curId++;
}
}
for(int i = 0; i < n; i++){
if(i > 0) out.print(" ");
out.print(result[i]);
}
out.println();
}
//-----------------------------------------------------------
public static void main(String[] args) {
new Main().run();
}
public void debug(Object... arr){
System.out.println(Arrays.deepToString(arr));
}
public void print1Int(int[] a){
for(int i = 0; i < a.length; i++)
System.out.print(a[i] + " ");
System.out.println();
}
public void print2Int(int[][] a){
for(int i = 0; i < a.length; i++){
for(int j = 0; j < a[0].length; j++){
System.out.print(a[i][j] + " ");
}
System.out.println();
}
}
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
tok = null;
solve();
in.close();
out.close();
} catch (IOException e) {
System.exit(0);
}
}
public String nextToken() throws IOException {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
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());
}
PrintWriter out;
BufferedReader in;
StringTokenizer tok;
} | Java | ["3\n1 3 2", "4\n2 2 3 3", "1\n2"] | 1 second | ["1 3 2", "2 1 3 4", "1"] | NoteIn the first test the numeration is already a permutation, so there is no need to change anything.In the second test there are two pairs of equal numbers, in each pair you need to replace one number.In the third test you need to replace 2 by 1, as the numbering should start from one. | Java 8 | standard input | [
"greedy",
"math"
] | 1cfd0e6504bba7db9ec79e2f243b99b4 | The first line contains a single integer n — the number of items (1 ≤ n ≤ 105). The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — the initial inventory numbers of the items. | 1,200 | Print n numbers — the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. | standard output | |
PASSED | 1f13c43a3cce77566e711f6e2a8a63e2 | train_002.jsonl | 1439224200 | Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. | 256 megabytes | /**
* Created by brzezinsky on 08/06/15.
*/
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Solution extends Thread{
public Solution(String inputFileName, String outputFileName) {
try {
if (inputFileName != null) {
this.input = new BufferedReader(new FileReader(inputFileName));
} else {
this.input = new BufferedReader(new InputStreamReader(System.in));
}
if (outputFileName != null) {
this.output = new PrintWriter(outputFileName);
} else {
this.output = new PrintWriter(System.out);
}
this.setPriority(Thread.MAX_PRIORITY);
} catch (Throwable e) {
System.err.println(e.getMessage());
e.printStackTrace();
System.exit(666);
}
}
static class Item implements Comparable<Item>{
int cnt, val;
public Item(int cnt, int val) {
this.cnt = cnt;
this.val = val;
}
@Override
public int compareTo(Item o) {
return Integer.compare(o.cnt, this.cnt) == 0
? Integer.compare(this.val, o.val)
: Integer.compare(o.cnt, this.cnt);
}
}
private void solve() throws Throwable {
int n = nextInt();
int []a = new int[n];
int []mult = new int[100001];
ArrayList<Integer> []positions = new ArrayList[100001];
for (int i = 0; i < positions.length; ++i) {
positions[i] = new ArrayList<>();
}
HashSet<Integer> missing = new HashSet<>();
for (int i = 1; i <= n; ++i) {
missing.add(i);
}
for (int i = 0; i < n; ++i) {
a[i] = nextInt();
missing.remove(a[i]);
positions[a[i]].add(i);
}
int []miss = new int[missing.size()];
int sss = 0;
for (int t : missing) {
miss[sss++] = t;
}
int SIZE = 0;
for (int i = 0; i < positions.length; ++i) {
if (positions[i].size() > 0) {
mult[SIZE++] = i;
}
}
for (int idx = 0, ololo = 0; idx < SIZE && ololo < sss; ++idx) {
int val = mult[idx];
int limit = val <= n ? positions[val].size() - 1 : positions[val].size();
for (int j = 0; j < limit && ololo < sss; ++j) {
a[positions[val].get(j)] = miss[ololo++];
}
}
for (int t: a) {
output.print(t + " ");
}
//
}
public void run() {
try {
solve();
} catch (Throwable e) {
System.err.println(e.getMessage());
e.printStackTrace();
System.exit(666);
} finally {
output.close();
}
}
public static void main(String... args) {
new Solution(null, null).start();
}
private int nextInt() throws IOException {
return Integer.parseInt(next());
}
private double nextDouble() throws IOException {
return Double.parseDouble(next());
}
private long nextLong() throws IOException {
return Long.parseLong(next());
}
private String next() throws IOException {
while (tokens == null || !tokens.hasMoreTokens()) {
tokens = new StringTokenizer(input.readLine());
}
return tokens.nextToken();
}
private StringTokenizer tokens;
private BufferedReader input;
private PrintWriter output;
} | Java | ["3\n1 3 2", "4\n2 2 3 3", "1\n2"] | 1 second | ["1 3 2", "2 1 3 4", "1"] | NoteIn the first test the numeration is already a permutation, so there is no need to change anything.In the second test there are two pairs of equal numbers, in each pair you need to replace one number.In the third test you need to replace 2 by 1, as the numbering should start from one. | Java 8 | standard input | [
"greedy",
"math"
] | 1cfd0e6504bba7db9ec79e2f243b99b4 | The first line contains a single integer n — the number of items (1 ≤ n ≤ 105). The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — the initial inventory numbers of the items. | 1,200 | Print n numbers — the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. | standard output | |
PASSED | 2dca3b321a8fd79c8a6dcd1b4f93f4e7 | train_002.jsonl | 1439224200 | Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
// InputStream inputStream = new FileInputStream(new File("stars.in"));
// OutputStream outputStream = new FileOutputStream(new File("stars.out"));
Input in = new Input(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task task = new Task();
task.solve(in, out);
out.close();
}
}
class Input {
public BufferedReader bufferedReader;
private StringTokenizer stringTokenizer;
public Input(InputStream inputStream) {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
stringTokenizer = null;
}
public String nextString() throws IOException {
while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) {
stringTokenizer = new StringTokenizer(bufferedReader.readLine());
}
return stringTokenizer.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(nextString());
}
public long nextLong() throws IOException {
return Long.parseLong(nextString());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextString());
}
}
class Task {
public void solve(Input in, PrintWriter out) throws IOException {
int n = in.nextInt();
int[] a = new int[n];
int[] p = new int[111111];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
p[a[i]]++;
}
if (n == 1) {
out.print("1");
return;
}
ArrayList<Integer> b = new ArrayList<>();
for (int i = 1; i <= n; i++) {
if(p[i] == 0){
b.add(i);
}
}
/*for (Integer i : b) {
System.out.print(i + " ");
}*/
int j = 0;
for (int i = 0; i < n; i++) {
if (p[a[i]] > 1 || a[i] > n) {
p[a[i]]--;
a[i] = b.get(j);
j++;
}
out.print(a[i] + " ");
}
}
} | Java | ["3\n1 3 2", "4\n2 2 3 3", "1\n2"] | 1 second | ["1 3 2", "2 1 3 4", "1"] | NoteIn the first test the numeration is already a permutation, so there is no need to change anything.In the second test there are two pairs of equal numbers, in each pair you need to replace one number.In the third test you need to replace 2 by 1, as the numbering should start from one. | Java 8 | standard input | [
"greedy",
"math"
] | 1cfd0e6504bba7db9ec79e2f243b99b4 | The first line contains a single integer n — the number of items (1 ≤ n ≤ 105). The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — the initial inventory numbers of the items. | 1,200 | Print n numbers — the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. | standard output | |
PASSED | 483ef108a5b80990bc1f20b4055b0169 | train_002.jsonl | 1439224200 | Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. | 256 megabytes | import java.io.*;
import java.util.StringTokenizer;
public class CF569B {
public static void main(String[] args) {
InputReader cin = new InputReader(System.in);
PrintWriter cout = new PrintWriter(System.out);
Solution sol = new Solution();
sol.solve(cin, cout);
cout.flush();
}
static class Solution {
void solve(InputReader cin, PrintWriter cout) {
int n = cin.nextInt();
int[] a = new int[n];
int[] c = new int[n];
boolean[] b = new boolean[100005];
for (int i = 0; i < n; i++) {
a[i] = cin.nextInt();
if (a[i] <= n && !b[a[i]]) {
b[a[i]] = true;
}
}
int j = 0;
for (int i = 1; i <= n; i++) {
if (!b[i]) {
c[j++] = i;
}
}
for (int i = 0; i < n; i++) {
if (b[a[i]]) {
cout.print(a[i]);
b[a[i]] = false;
} else {
cout.print(c[--j]);
}
if (i == n - 1) {
cout.println();
} else {
cout.print(" ");
}
}
}
}
static class InputReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public BufferedReader getReader() {
return reader;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["3\n1 3 2", "4\n2 2 3 3", "1\n2"] | 1 second | ["1 3 2", "2 1 3 4", "1"] | NoteIn the first test the numeration is already a permutation, so there is no need to change anything.In the second test there are two pairs of equal numbers, in each pair you need to replace one number.In the third test you need to replace 2 by 1, as the numbering should start from one. | Java 8 | standard input | [
"greedy",
"math"
] | 1cfd0e6504bba7db9ec79e2f243b99b4 | The first line contains a single integer n — the number of items (1 ≤ n ≤ 105). The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — the initial inventory numbers of the items. | 1,200 | Print n numbers — the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. | standard output | |
PASSED | 25e610189578ac00b05774bc9f72edfe | train_002.jsonl | 1439224200 | Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. | 256 megabytes | import java.io.*;
import java.util.StringTokenizer;
public class CF569B {
public static void main(String[] args) {
InputReader cin = new InputReader(System.in);
int n = cin.nextInt();
int[] a = new int[n];
int[] c = new int[n];
boolean[] b = new boolean[100005];
for (int i = 0; i < n; i++) {
a[i] = cin.nextInt();
if (a[i] <= n && !b[a[i]]) {
b[a[i]] = true;
}
}
int j = 0;
for (int i = 1; i <= n; i++) {
if (!b[i]) {
c[j++] = i;
}
}
for (int i = 0; i < n; i++) {
if (b[a[i]]) {
System.out.print(a[i]);
b[a[i]] = false;
} else {
System.out.print(c[--j]);
}
if (i == n - 1) {
System.out.println();
} else {
System.out.print(" ");
}
}
}
static class InputReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public BufferedReader getReader() {
return reader;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["3\n1 3 2", "4\n2 2 3 3", "1\n2"] | 1 second | ["1 3 2", "2 1 3 4", "1"] | NoteIn the first test the numeration is already a permutation, so there is no need to change anything.In the second test there are two pairs of equal numbers, in each pair you need to replace one number.In the third test you need to replace 2 by 1, as the numbering should start from one. | Java 8 | standard input | [
"greedy",
"math"
] | 1cfd0e6504bba7db9ec79e2f243b99b4 | The first line contains a single integer n — the number of items (1 ≤ n ≤ 105). The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — the initial inventory numbers of the items. | 1,200 | Print n numbers — the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. | standard output | |
PASSED | 554deb7d719bc35753592f54968f3a97 | train_002.jsonl | 1439224200 | Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. | 256 megabytes |
import java.util.*;
import java.io.*;
public class marte{
private int contor=0;
private int raspuns=0;
public static void main (String args[]) throws Exception{
Scanner input=new Scanner(System.in);
HashMap<String, String> map1= new HashMap<String, String>();
HashMap<String, Integer> map2= new HashMap<String, Integer>();
HashMap<Integer, Integer> map= new HashMap<Integer, Integer>();
HashMap<Integer, Integer> maxime= new HashMap<Integer, Integer>();
HashMap<Integer, String> suplim= new HashMap<Integer, String>();
int n=input.nextInt();
int v[]=new int[n
+2];
int initial[]=new int[n+2];
int rest=0;
int poz=0;
int a;
for(int i=1;i<=n;i++)
{a=input.nextInt();
if(a>n) a=n+1;
//System.out.println("a="+a);
v[a]++;
// if(v[a]>1) rest++;
initial[i]=a;
}
for(int i=1;i<=n;i++) if(v[i]==0) rest++;
// System.out.println("rest="+rest);
int m[]=new int[rest];
for(int i=1;i<=n;i++) if (v[i]==0)
{ m[poz]=i;poz++;}
// for(int i=0;i<rest;i++) System.out.println(m[i]);
poz=0;
for(int i=1;i<=n+1;i++)
{
// System.out.println("i="+i+
// " v[initial[i]]="+v[initial[i]]);
if(v[initial[i]]==1 && initial[i]<=n) {
System.out.print(initial[i]+" ");
v[initial[i]]--;}
else{
if(v[initial[i]]>1 ||initial[i]>n){
System.out.print(m[poz]+" ");
poz++;
v[initial[i]]--;}
}
}
}
}
| Java | ["3\n1 3 2", "4\n2 2 3 3", "1\n2"] | 1 second | ["1 3 2", "2 1 3 4", "1"] | NoteIn the first test the numeration is already a permutation, so there is no need to change anything.In the second test there are two pairs of equal numbers, in each pair you need to replace one number.In the third test you need to replace 2 by 1, as the numbering should start from one. | Java 8 | standard input | [
"greedy",
"math"
] | 1cfd0e6504bba7db9ec79e2f243b99b4 | The first line contains a single integer n — the number of items (1 ≤ n ≤ 105). The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — the initial inventory numbers of the items. | 1,200 | Print n numbers — the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. | standard output | |
PASSED | aeb30b7c35c2649ac64a581b7598864c | train_002.jsonl | 1439224200 | Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. | 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.ArrayList;
import java.util.InputMismatchException;
public final class Main
{
public static void main(String[] args) throws Exception
{
InputReader in = new InputReader(System.in);
OutputWriter out = new OutputWriter(System.out);
int n = in.readInt();
boolean[] p = new boolean[100001];
ArrayList<Integer> a = new ArrayList();
int[] z = new int[n];
for( int i=0 ; i<n ; i++ )
{
z[i] = in.readInt();
if( p[z[i]] || z[i]>n )
{
a.add(i);
}
else
{
p[z[i]] = true;
}
}
int ind=0;
for( int i=1 ; i<=n ; i++ )
{
if( !p[i] )
{
z[a.get(ind)] = i;
p[i] = true;
ind++;
}
}
for( int i=0 ; i<n ; i++ )
{
out.print(z[i]+" ");
}
out.printLine();
out.close();
}
private 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 String readString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public double readDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next()
{
return readString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
private static class OutputWriter
{
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream)
{
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer)
{
this.writer = new PrintWriter(writer);
}
public void print(Object... objects)
{
for (int i = 0; i < objects.length; i++)
{
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object... objects)
{
print(objects);
writer.println();
}
public void close()
{
writer.close();
}
public void flush()
{
writer.flush();
}
}
} | Java | ["3\n1 3 2", "4\n2 2 3 3", "1\n2"] | 1 second | ["1 3 2", "2 1 3 4", "1"] | NoteIn the first test the numeration is already a permutation, so there is no need to change anything.In the second test there are two pairs of equal numbers, in each pair you need to replace one number.In the third test you need to replace 2 by 1, as the numbering should start from one. | Java 8 | standard input | [
"greedy",
"math"
] | 1cfd0e6504bba7db9ec79e2f243b99b4 | The first line contains a single integer n — the number of items (1 ≤ n ≤ 105). The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — the initial inventory numbers of the items. | 1,200 | Print n numbers — the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. | standard output | |
PASSED | a9844cf8c1263a70d20b0f527e023a58 | train_002.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.Scanner;
public class RGB{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int q = sc.nextInt();
for (int j = 0 ; j < q ; j ++){
int n = sc.nextInt(); int k = sc.nextInt();
int[] R = new int[n]; int[] s_r = new int[n];
int[] G = new int[n];int[] s_g = new int[n];
int[] B = new int[n]; int[] s_b = new int[n];
sc.nextLine();
char[] res = sc.nextLine().toCharArray();
for (int i = 0 ; i < n ; i++)
{
//RGB
if (((i%3)==0) && (res[i]=='R'))
{
R[i]++;
}
if(((i%3)==1) && (res[i]=='G'))
{
R[i]++;
}
if(((i%3)==2) && (res[i]=='B'))
{
R[i]++;
}
// GBR
if (((i%3)==0) && (res[i]=='G'))
{
G[i]++;
}
if(((i%3)==1) && (res[i]=='B'))
{
G[i]++;
}
if(((i%3)==2) && (res[i]=='R'))
{
G[i]++;
}
// BRG
if (((i%3)==0) && (res[i]=='B'))
{
B[i]++;
}
if(((i%3)==1) && (res[i]=='R'))
{
B[i]++;
}
if(((i%3)==2) && (res[i]=='G'))
{
B[i]++;
}
if (i > 0){
s_r[i] = s_r[i-1] + R[i];
s_g[i] = s_g[i-1] + G[i];
s_b[i] = s_b[i-1] + B[i];
}
else
{
s_r[i] = R[i];
s_g[i] = G[i];
s_b[i] = B[i];
}
}
// for (int i = 0 ; i < n ; i ++){
// System.out.print("S_r[i]: " + s_r[i] + " S_b[i]: " + s_b[i] + " S_g[i]: " + s_g[i]);
// System.out.println();
// }
int max = 0;
if (k==n){
int temp = 0;
int temp_r = s_r[n-1];
if (temp_r > temp)
temp = temp_r;
int temp_g = s_g[n-1];
if (temp_g > temp)
temp = temp_g;
int temp_b = s_b[n-1];
if (temp_b > temp)
temp = temp_b;
System.out.println(k-temp);
}
else{
for (int i = 0 ; i <= n - k ; i++) {
int temp_r = s_r[i+k-1] - s_r[i] + R[i];
if (temp_r > max) max = temp_r ;
int temp_g = s_g[i+k - 1] - s_g[i] + G[i] ;
if (temp_g > max) max = temp_g;
int temp_b = s_b[i+k - 1] - s_b[i] + B[i];
if (temp_b > max) max = temp_b;
}
System.out.println(k-max);
}
}
}
} | Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 85987c867d193c18a9b115416bad15cf | train_002.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.Scanner;
public class RGB{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int q = sc.nextInt();
for (int j = 0 ; j < q ; j ++){
int n = sc.nextInt(); int k = sc.nextInt();
int[] R = new int[n]; int[] s_r = new int[n];
int[] G = new int[n];int[] s_g = new int[n];
int[] B = new int[n]; int[] s_b = new int[n];
sc.nextLine();
char[] res = sc.nextLine().toCharArray();
for (int i = 0 ; i < n ; i++)
{
//RGB
if (((i%3)==0) && (res[i]=='R'))
R[i]++;
if(((i%3)==1) && (res[i]=='G'))
R[i]++;
if(((i%3)==2) && (res[i]=='B'))
R[i]++;
// GBR
if (((i%3)==0) && (res[i]=='G'))
G[i]++;
if(((i%3)==1) && (res[i]=='B'))
G[i]++;
if(((i%3)==2) && (res[i]=='R'))
G[i]++;
// BRG
if (((i%3)==0) && (res[i]=='B'))
B[i]++;
if(((i%3)==1) && (res[i]=='R'))
B[i]++;
if(((i%3)==2) && (res[i]=='G'))
B[i]++;
if (i > 0){
s_r[i] = s_r[i-1] + R[i];
s_g[i] = s_g[i-1] + G[i];
s_b[i] = s_b[i-1] + B[i];
}
else
{
s_r[i] = R[i];
s_g[i] = G[i];
s_b[i] = B[i];
}
}
int max = 0;
if (k==n){
int temp = 0;
int temp_r = s_r[n-1];
if (temp_r > temp)
temp = temp_r;
int temp_g = s_g[n-1];
if (temp_g > temp)
temp = temp_g;
int temp_b = s_b[n-1];
if (temp_b > temp)
temp = temp_b;
System.out.println(k-temp);
}
else{
for (int i = 0 ; i <= n - k ; i++) {
int temp_r = s_r[i+k-1] - s_r[i] + R[i];
if (temp_r > max) max = temp_r ;
int temp_g = s_g[i+k - 1] - s_g[i] + G[i] ;
if (temp_g > max) max = temp_g;
int temp_b = s_b[i+k - 1] - s_b[i] + B[i];
if (temp_b > max) max = temp_b;
}
System.out.println(k-max);
}
}
}
} | Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 2cb77ce7ae850658966f209eadd5eff3 | train_002.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.*;
import java.util.*;
public class D1_RGBSubstring {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader inp = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Solver solver = new Solver();
solver.solve(inp, out);
out.close();
}
private static class Solver {
private void solve(InputReader inp, PrintWriter out) {
int q = inp.nextInt();
for (int i = 0; i < q; i++) {
out.println(solve(inp.nextInt(), inp.nextInt(), inp.next().toCharArray()));
}
}
private int solve(int n, int k, char[] s) {
int[][] dp = new int[n+1][9];
for (int i = 1; i <= n; i++) {
for (int j = 0; j <= 8; j++) dp[i][j] = dp[i-1][j];
if (s[i-1] == 'R') dp[i][i % 3]++;
else if (s[i-1] == 'G') dp[i][3 + (i % 3)]++;
else dp[i][6 + (i % 3)]++;
}
int min = Integer.MAX_VALUE;
int l = 1, r = l + k - 1;
while (r <= n) {
min = Math.min(min, query(dp, k, l, r, 'R'));
min = Math.min(min, query(dp, k, l, r, 'G'));
min = Math.min(min, query(dp, k, l, r, 'B'));
l++;
r++;
}
return min;
}
private int query(int[][] dp, int k, int l, int r, int startColor) {
int res = k;
if (startColor == 'R') {
res -= dp[r][l%3] - dp[l-1][l%3]; // amount of red on same mod as index
res -= dp[r][3+(l+1)%3] - dp[l-1][3+(l+1)%3]; // amount of green on same mod as index + 1
res -= dp[r][6+(l+2)%3] - dp[l-1][6+(l+2)%3]; // amount of blue on same mod as index + 2
} else if (startColor == 'G') {
res -= dp[r][3+l%3] - dp[l-1][3+l%3];
res -= dp[r][6+(l+1)%3] - dp[l-1][6+(l+1)%3];
res -= dp[r][(l+2)%3] - dp[l-1][(l+2)%3];
} else {
res -= dp[r][6+l%3] - dp[l-1][6+l%3];
res -= dp[r][(l+1)%3] - dp[l-1][(l+1)%3];
res -= dp[r][3+(l+2)%3] - dp[l-1][3+(l+2)%3];
}
return res;
}
}
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
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 | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 7ba7f2cce4d1c854318bb5f09b93e1ac | train_002.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.*;
import java.util.*;
import java.lang.*;
public class D1 {
public static void main(String[] args) {
FastReader in = new FastReader();
PrintWriter out = new PrintWriter(System.out);
char[] sub = {'R','G','B'};
int T = in.nextInt();
for(int tt=0;tt<T;tt++) {
int n = in.nextInt(), k = in.nextInt();
char[] string = in.next().toCharArray();
long ans = (int)1e9;
for(int i=0;i<n-k+1;i++) {
for(int j=0;j<3;j++) {
int cnt = 0;
for(int pos =i;pos<i+k;pos++) {
if(string[pos]!=sub[(j+pos)%3]) cnt++;
}
ans = Math.min(ans,cnt);
}
}
out.println(ans);
}
out.close();
}
static final Random random=new Random();
// static void ruffleSort(Pair[] a) {
// int n=a.length;//shuffle, then sort
// for (int i=0; i<n; i++) {
// int oi=random.nextInt(n);
// Pair temp=a[oi];
// a[oi]=a[i]; a[i]=temp;
// }
// Arrays.sort(a);
// }
static void ruffleSort(int[] a) {
int n=a.length;//shuffle, then sort
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static void ruffleSort(char[] a) {
int n=a.length;//shuffle, then sort
for (int i=0; i<n; i++) {
int oi=random.nextInt(n);
char temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
}
}
//class Pair implements Comparable<Pair>{
// int a;
// int b;
// public Pair(int a, int b) {
// this.a = a;
// this.b = b;
// }
// public int compareTo(Pair o) {
// if(this.a==o.a)
// return this.b - o.b;
// return this.a - o.a;
// }
//} | Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 73daee61716a3df2e0585e493bc568bf | train_002.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static int[] arr = new int[200005];
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
String s = "RGB";
int T = Integer.parseInt(br.readLine());
while(T-- > 0)
{
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken());
int p1 = 0, p2 = 1, p3 = 2;
int[] a = new int[n+1];
int[] b = new int[n+1];
int[] c = new int[n+1];
String str = br.readLine();
for(int i=1; i<=str.length(); i++)
{
if(str.charAt(i-1) == s.charAt(p1)) {
a[i] = a[i-1];
}
else {
a[i] = a[i-1]+1;
}
if(str.charAt(i-1) == s.charAt(p2)) {
b[i] = b[i-1];
}
else {
b[i] = b[i-1]+1;
}
if(str.charAt(i-1) == s.charAt(p3)) {
c[i] = c[i-1];
}
else {
c[i] = c[i-1]+1;
}
p1 = (p1+1) % 3;
p2 = (p2+1) % 3;
p3 = (p3+1) % 3;
}
int min = 987654321;
for(int i=0; i<=str.length()-k; i++)
{
min = Math.min(min, Math.min(c[i+k] - c[i], Math.min(b[i+k] - b[i], a[i+k] - a[i])));
}
bw.write(min+"\n");
}
bw.close();
}
} | Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | f2e1eb3f3f6154e14911d09cf056aa64 | train_002.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class RGBS {
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 char next(char c) {
if(c=='R') return 'G';
if(c=='G') return 'B';
return 'R';
}
static String RGB(int k, char c) {
char now = c;
StringBuilder sb = new StringBuilder();
for(int i = 1; i <= k; i++) {
sb.append(now);
now = next(now);
}
return sb.toString();
}
static int df(String s1, String s2) {
int tmp = 0;
for(int i = 0; i < s1.length(); i++) {
if(s1.charAt(i)!=s2.charAt(i)) tmp++;
}
return tmp;
}
static int dif(String s, String[] fix) {
int res = Integer.MAX_VALUE;
for(int i = 0; i < fix.length; i++) res = Math.min(res, df(s,fix[i]));
return res;
}
public static void main(String[] args) {
FastReader sc = new FastReader();
OutputStream outputstream = System.out;
PrintWriter out = new PrintWriter(outputstream);
int q = sc.nextInt();
while(q--!=0) {
int n = sc.nextInt();
int k = sc.nextInt();
String str = sc.next();
String[] fix = {RGB(k,'R'),RGB(k,'G'),RGB(k,'B')};
int ans = Integer.MAX_VALUE;
for(int i = 0; i <= n - k; i++) {
String sub = str.substring(i,i+k);
int dif = dif(sub,fix);
ans = Math.min(ans, dif);
}
out.println(ans);
}
out.close();
}
}
| Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 7973768dbacb747f119c55979b767e0b | train_002.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class RGBS {
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 char next(char c) {
if(c=='R') return 'G';
if(c=='G') return 'B';
return 'R';
}
static String R(int k) {
char now = 'R';
StringBuilder sb = new StringBuilder();
for(int i = 1; i <= k; i++) {
sb.append(now);
now = next(now);
}
return sb.toString();
}
static String G(int k) {
char now = 'G';
StringBuilder sb = new StringBuilder();
for(int i = 1; i <= k; i++) {
sb.append(now);
now = next(now);
}
return sb.toString();
}
static String B(int k) {
char now = 'B';
StringBuilder sb = new StringBuilder();
for(int i = 1; i <= k; i++) {
sb.append(now);
now = next(now);
}
return sb.toString();
}
static int dif(String s, String R, String G, String B) {
int res = Integer.MAX_VALUE;
int tmp = 0;
for(int i = 0; i < s.length(); i++) {
if(s.charAt(i)!=R.charAt(i)) tmp++;
}
res = Math.min(res, tmp);
tmp = 0;
for(int i = 0; i < s.length(); i++) {
if(s.charAt(i)!=G.charAt(i)) tmp++;
}
res = Math.min(res, tmp);
tmp = 0;
for(int i = 0; i < s.length(); i++) {
if(s.charAt(i)!=B.charAt(i)) tmp++;
}
res = Math.min(res, tmp);
return res;
}
public static void main(String[] args) {
FastReader sc = new FastReader();
OutputStream outputstream = System.out;
PrintWriter out = new PrintWriter(outputstream);
int q = sc.nextInt();
while(q--!=0) {
int n = sc.nextInt();
int k = sc.nextInt();
String str = sc.next();
String R = R(k);
String G = G(k);
String B = B(k);
int ans = Integer.MAX_VALUE;
for(int i = 0; i <= n - k; i++) {
String sub = str.substring(i,i+k);
int dif = dif(sub,R,G,B);
ans = Math.min(ans, dif);
}
out.println(ans);
}
out.close();
}
}
| Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 5ad8f2dc2e06e9b1c4eaf58e31014ecd | train_002.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class RGBS {
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 char next(char c) {
if(c=='R') return 'G';
if(c=='G') return 'B';
return 'R';
}
static String RGB(int k, char c) {
char now = c;
StringBuilder sb = new StringBuilder();
for(int i = 1; i <= k; i++) {
sb.append(now);
now = next(now);
}
return sb.toString();
}
static int dif(String s, String R, String G, String B) {
int res = Integer.MAX_VALUE;
int tmp = 0;
for(int i = 0; i < s.length(); i++) {
if(s.charAt(i)!=R.charAt(i)) tmp++;
}
res = Math.min(res, tmp);
tmp = 0;
for(int i = 0; i < s.length(); i++) {
if(s.charAt(i)!=G.charAt(i)) tmp++;
}
res = Math.min(res, tmp);
tmp = 0;
for(int i = 0; i < s.length(); i++) {
if(s.charAt(i)!=B.charAt(i)) tmp++;
}
res = Math.min(res, tmp);
return res;
}
public static void main(String[] args) {
FastReader sc = new FastReader();
OutputStream outputstream = System.out;
PrintWriter out = new PrintWriter(outputstream);
int q = sc.nextInt();
while(q--!=0) {
int n = sc.nextInt();
int k = sc.nextInt();
String str = sc.next();
String R = RGB(k,'R');
String G = RGB(k,'G');
String B = RGB(k,'B');
int ans = Integer.MAX_VALUE;
for(int i = 0; i <= n - k; i++) {
String sub = str.substring(i,i+k);
int dif = dif(sub,R,G,B);
ans = Math.min(ans, dif);
}
out.println(ans);
}
out.close();
}
}
| Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | c9107e9d09c51f0f139a17e3522cbfd3 | train_002.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.*;
import java.util.*;
public class a {
public static void main(String[] args) { new a(); }
FS in = new FS();
PrintWriter out = new PrintWriter(System.out);
int q;
int n, k;
int[][] diff, cs;
char[] str, p = {'R', 'G', 'B'};
a() {
q = in.nextInt();
while (q-- > 0) {
n = in.nextInt();
k = in.nextInt();
str = in.next().toCharArray();
diff = new int[3][n];
for (int i = 0; i < 3; i++)
for (int j = 0; j < n; j++)
diff[i][j] = str[j] != p[(i + j) % 3] ? 1 : 0;
cs = new int[3][n + 1];
for (int i = 0; i < 3; i++)
for (int j = 1; j <= n; j++)
cs[i][j] = cs[i][j - 1] + diff[i][j - 1];
int min = k + 1;
for (int i = 0; i < 3; i++)
for (int j = 0; j + k <= n; j++)
min = min(min, cs[i][j + k] - cs[i][j]);
out.println(min);
}
out.close();
}
int abs(int x) { if (x < 0) return -x; return x; }
long abs(long x) { if (x < 0) return -x; return x; }
int max(int x, int y) { if (x < y) return y; return x; }
int min(int x, int y) { if (x > y) return y; return x; }
long max(long x, long y) { if (x < y) return y; return x; }
long min(long x, long y) { if (x > y) return y; return x; }
int gcd(int x, int y) { while (y != 0) { x = y^(x^(y = x)); y %= x; } return x; }
long gcd(long x, long y) { while (y != 0) { x = y^(x^(y = x)); y %= x; } return x; }
long lcm(int x, int y) { long xy = x; xy *= y; return xy / gcd(x, y); }
long lcm(long x, long y) { return (x * y) / gcd(x, y); }
class FS {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens()) {
try { st = new StringTokenizer(br.readLine()); }
catch (Exception e) {}
} return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble() { return Double.parseDouble(next()); }
void intArr(int sz, int[] x) { for (int i = 0; i < sz; i++) x[i] = nextInt(); }
void longArr(int sz, long[] x) { for (int i = 0; i < sz; i++) x[i] = nextLong(); }
void doubleArr(int sz, double[] x) { for (int i = 0; i < sz; i++) x[i] = nextDouble(); }
}
}
| Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | aa8d0d8a83b16f5c66db90a99d059c00 | train_002.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | /*
9 2
1 1 1 1 1 0 0 0 0
1 2
1 5
5 6
5 7
2 3
2 4
3 8
3 9
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
public class Question {
static long[] arr1;
static long[] arr2;
static int[] arr;
static int[][] dp;
static int n;
static long MOD = 998244353 ;
static long ans = 0;
static String str1 ;
static String str2 ;
static int[] primes = new int[]{2,3,5,7,11,13,17,19,23,29,31,37,41,43,47};
static ArrayList<Integer> list;
static int aa;
public static void main (String[] args) throws IOException {
Reader.init(System.in);
int t = Reader.nextInt();
while (t-->0){
int n = Reader.nextInt();
int k = Reader.nextInt();
String s =Reader.next();
char[] arr = s.toCharArray();
int cnt1 = 0;
int cnt2 = 0;
int cnt3 = 0;
int l = 0;
int r = k-1;
char[] my1 = new char[]{'R','G','B'};
char[] my2 = new char[]{'G','B','R'};
char[] my3 = new char[]{'B','R','G'};
int ans = Integer.MAX_VALUE;
for (int i = 0 ; i< k ; i++){
if (my1[i%3]!=arr[i]){
cnt1++;
}
if (my2[i%3]!=arr[i]){
cnt2++;
}
if (my3[i%3]!=arr[i]){
cnt3++;
}
}
ans = Math.min(ans,Math.min(cnt1,Math.min(cnt2,cnt3)));
for (int i = k ; i < n ; i++){
ans = Math.min(ans,Math.min(cnt1,Math.min(cnt2,cnt3)));
if (my1[i%3]!=arr[i]){
cnt1++;
}
if (my2[i%3]!=arr[i]){
cnt2++;
}
if (my3[i%3]!=arr[i]){
cnt3++;
}
if (my1[l%3]!=arr[l]){
cnt1--;
}
if (my2[l%3]!=arr[l]){
cnt2--;
}
if (my3[l%3]!=arr[l]){
cnt3--;
}
l++;
ans = Math.min(ans,Math.min(cnt1,Math.min(cnt2,cnt3)));
}
System.out.println(ans);
}
}
static long count(String a, String b)
{
int m = a.length();
int n = b.length();
// Create a table to store
// results of sub-problems
long lookup[][] = new long[m + 1][n + 1];
// If first string is empty
for (int i = 0; i <= n; ++i)
lookup[0][i] = 0;
// If second string is empty
for (int i = 0; i <= m; ++i)
lookup[i][0] = 1;
// Fill lookup[][] in
// bottom up manner
for (int i = 1; i <= m; i++)
{
for (int j = 1; j <= n; j++)
{
// If last characters are
// same, we have two options -
// 1. consider last characters
// of both strings in solution
// 2. ignore last character
// of first string
if (a.charAt(i - 1) == b.charAt(j - 1))
lookup[i][j] = lookup[i - 1][j - 1] +
lookup[i - 1][j];
else
// If last character are
// different, ignore last
// character of first string
lookup[i][j] = lookup[i - 1][j];
}
}
return lookup[m][n];
}
public static void sortbyColumn(int arr[][], int col)
{
// Using built-in sort function Arrays.sort
Arrays.sort(arr, new Comparator<int[]>() {
@Override
// Compare values according to columns
public int compare(final int[] entry1,
final int[] entry2) {
// To sort in descending order revert
// the '>' Operator
if (entry1[col] > entry2[col])
return 1;
else
return -1;
}
}); // End of function call sort().
}
static int fun(int i , int mask){
if (i < n){
//System.out.println(i + " " + Integer.toBinaryString(mask));
}
if (i==n){
return 0;
}
else if (dp[i][mask]!=-1){
return dp[i][mask];
}
else{
int flag = 0;
for (int j = 0 ; j < 16 ; j++) {
if (((mask>>j) &1 ) == 1 && ((list.get(i)>>j) &1 ) == 1) {
flag =1;
}
}
if (flag==0){
dp[i][mask] =Math.max(1 + fun(i + 1, (mask | (list.get(i)))), fun(i + 1, mask));
}
else{
dp[i][mask] = fun(i + 1, mask);
}
return dp[i][mask];
}
}
/*static int lcs(int i , int j){
if (i ==0 || j==0){
return 0;
}
else if (dp[i][j]!=-1){
return dp[i][j];
}
else if (str1.charAt(i-1)==str2.charAt(j-1)){
return dp[i][j] = 1 + lcs(i-1,j-1);
}
else {
return dp[i][j] = Math.max(lcs(i-1,j),lcs(i,j-1));
}
}
*/
/*static long fun(int i , int cnt){
if (i >= n){
return 0;
}
if (dp[i][cnt%2]!=-1){
return dp[i][cnt%2];
}
else{
if (cnt%2==0){
return dp[i][cnt%2] = arr1[i] + Math.max(fun(i+1,cnt+1),fun(i+2,cnt+1));
}
else{
return dp[i][cnt%2] = arr2[i] + Math.max(fun(i+1,cnt+1),fun(i+2,cnt+1));
}
}
}*/
/*static long grid(int i , int j){
//System.out.println(i + " " + j);
if (i>= n || i < 0 || j >= m || j < 0){
return 0;
}
else if (arr[i][j]==-1){
return 0;
}
else if (i==n-1 && j==m-1){
return 1;
}
else if (dp[i][j]!=-1){
//System.out.println(dp[i][j]);
return dp[i][j];
}
else{
long tmp =0;
tmp+=grid(i+1 , j);
tmp%=MOD;
tmp+=grid(i,j+1);
tmp%=MOD;
return dp[i][j] = tmp;
}
}*/
/*static int dfs(int n){
//System.out.println(n +" " + dp[n]);
if (dp[n]!=-1){
return dp[n];
}
else{
int max = 1;
Iterator i = adj[n].iterator();
while (i.hasNext()){
int j = (int)i.next();
max = Math.max(max,1+dfs(j));
}
return dp[n] = max;
}
}*/
static boolean isSubSequence(String str1, String str2, int m, int n)
{
// Base Cases
if (m == 0)
return true;
if (n == 0)
return false;
// If last characters of two strings are matching
if (str1.charAt(m-1) == str2.charAt(n-1))
return isSubSequence(str1, str2, m-1, n-1);
// If last characters are not matching
return isSubSequence(str1, str2, m, n-1);
}
}
class Tnode{
int lSub;
int rSub;
int left;
int right;
}
class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input) );
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt( next() );
}
static long nextLong() throws IOException {
return Long.parseLong( next() );
}
static double nextDouble() throws IOException {
return Double.parseDouble( next() );
}
}
/*class MergeSort
{
// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r)
{
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
*//* Create temp arrays *//*
int L[] = new int [n1];
int R[] = new int [n2];
*//*Copy data to temp arrays*//*
for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];
*//* Merge the temp arrays *//*
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarry array
int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
*//* Copy remaining elements of L[] if any *//*
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
*//* Copy remaining elements of R[] if any *//*
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
// Main function that sorts arr[l..r] using
// merge()
void sort(int arr[], int l, int r)
{
if (l < r)
{
// Find the middle point
int m = (l+r)/2;
// Sort first and second halves
sort(arr, l, m);
sort(arr , m+1, r);
// Merge the sorted halves
merge(arr, l, m, r);
}
}
*//* A utility function to print array of size n *//*
static void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
// Driver method
}
class Node{
int data;
int freq;
public Node(int data, int freq) {
this.data = data;
this.freq = freq;
}
}
class GFG {
// limit for array size
static int N = 1000000;
static int n; // array size
// Max size of tree
static int []tree = new int[2 * N];
// function to build the tree
static void build( char []arr,int n)
{
// insert leaf nodes in tree
for (int i = 0; i < n-1; i++) {
if (arr[i]!=arr[i+1]) {
System.out.println(i);
tree[n + i] = 1;
}
}
// build the tree by calculating
// parents
for (int i = n - 1; i > 0; --i)
tree[i] = tree[i << 1] +
tree[i << 1 | 1];
}
static int query(int l, int r)
{
int res = 0;
// loop to find the sum in the range
for (l += n, r += n; l < r;
l >>= 1, r >>= 1)
{
if ((l & 1) > 0)
res += tree[l++];
if ((r & 1) > 0)
res += tree[--r];
}
return res;
}
// driver program to test the
// above function
}
class SegmentTree{
int[] arr ;
int[] tree;
SegmentTree(int[] arr ,int n){
this.arr = arr;
tree = new int[2*n];
}
void updateRangeUtil(int si, int ss, int se, int us,
int ue, int val)
{
if (ss>se || ss>ue || se<us)
return ;
if (ss==se)
{
tree[si] |= val;
return;
}
int mid = (ss+se)/2;
updateRangeUtil(si*2+1, ss, mid, us, ue, val);
updateRangeUtil(si*2+2, mid+1, se, us, ue, val);
tree[si] = tree[si*2+1] + tree[si*2+2];
}
void constructSTUtil(int ss, int se, int si)
{
// out of range as ss can never be greater than se
if (ss > se)
return ;
// If there is one element in array, store it in
// current node of segment tree and return
if (ss == se)
{
//tree[si] = arr[ss];
System.out.println(tree[si]);
return;
}
// If there are more than one elements, then recur
// for left and right subtrees and store the sum
// of values in this node
int mid = (ss + se)/2;
constructSTUtil(ss, mid, si*2+1);
constructSTUtil(mid+1, se, si*2+2);
//tree[si] = tree[si*2 + 1] + tree[si*2 + 2];
}
}
class Heap{
int[] Heap;
int size;
int maxSize;
public Heap(int maxSize){
this.maxSize = maxSize;
this.size = 0;
Heap = new int[maxSize + 1];
Heap[0] = Integer.MIN_VALUE;
}
int parent(int pos){
return pos/2;
}
int left(int pos){
return 2*pos;
}
int right(int pos){
return 2*pos + 1;
}
boolean isLeaf(int pos){
if (pos>=size/2 && pos<=size){
return true;
}
return false;
}
void swap(int i , int j){
int temp = Heap[i];
Heap[i] = Heap[j];
Heap[j]= temp;
}
void minHeapify(int pos){
if (!isLeaf(pos)){
if (Heap[pos]>Heap[left(pos)] || Heap[pos] > Heap[right(pos)]){
if (Heap[left(pos)] < Heap[right(pos)]) {
swap(pos, left(pos));
minHeapify(left(pos));
}
// Swap with the right child and heapify
// the right child
else {
swap(pos, right(pos));
minHeapify(right(pos));
}
}
}
}
}
class Graph{
}
class DijkstraNode implements Comparator<DijkstraNode>{
public int node;
public int cost;
public int[] visited;
public boolean[] settled;
public DijkstraNode(int node, int cost,int vertices) {
this.node = node;
this.cost = cost;
visited = new int[vertices];
settled = new boolean[vertices];
}
@Override
public int compare(DijkstraNode node1 , DijkstraNode node2){
if (node1.cost < node2.cost){
return -1;
}
if (node1.cost > node2.cost){
return 1;
}
return 0;
}
ArrayList<Integer> list = new ArrayList<>(10000);
}*/
/*
public class DPQ {
private int dist[];
private Set<Integer> settled;
private PriorityQueue<Node> pq;
private int V; // Number of vertices
List<List<Node> > adj;
public DPQ(int V)
{
this.V = V;
dist = new int[V];
settled = new HashSet<Integer>();
pq = new PriorityQueue<Node>(V, new Node());
}
// Function for Dijkstra's Algorithm
public void dijkstra(List<List<Node> > adj, int src)
{
this.adj = adj;
for (int i = 0; i < V; i++)
dist[i] = Integer.MAX_VALUE;
// Add source node to the priority queue
pq.add(new Node(src, 0));
// Distance to the source is 0
dist[src] = 0;
while (settled.size() != V) {
// remove the minimum distance node
// from the priority queue
int u = pq.remove().node;
// adding the node whose distance is
// finalized
settled.add(u);
e_Neighbours(u);
}
}
// Function to process all the neighbours
// of the passed node
private void e_Neighbours(int u)
{
int edgeDistance = -1;
int newDistance = -1;
// All the neighbors of v
for (int i = 0; i < adj.get(u).size(); i++) {
Node v = adj.get(u).get(i);
// If current node hasn't already been processed
if (!settled.contains(v.node)) {
edgeDistance = v.cost;
newDistance = dist[u] + edgeDistance;
// If new distance is cheaper in cost
if (newDistance < dist[v.node])
dist[v.node] = newDistance;
// Add the current node to the queue
pq.add(new Node(v.node, dist[v.node]));
}
}
}
// Driver code
public static void main(String arg[])
{
int V = 5;
int source = 0;
// Adjacency list representation of the
// connected edges
List<List<Node> > adj = new ArrayList<List<Node> >();
// Initialize list for every node
for (int i = 0; i < V; i++) {
List<Node> item = new ArrayList<Node>();
adj.add(item);
}
// Inputs for the DPQ graph
adj.get(0).add(new Node(1, 9));
adj.get(0).add(new Node(2, 6));
adj.get(0).add(new Node(3, 5));
adj.get(0).add(new Node(4, 3));
adj.get(2).add(new Node(1, 2));
adj.get(2).add(new Node(3, 4));
// Calculate the single source shortest path
DPQ dpq = new DPQ(V);
dpq.dijkstra(adj, source);
// Print the shortest path to all the nodes
// from the source node
System.out.println("The shorted path from node :");
for (int i = 0; i < dpq.dist.length; i++)
System.out.println(source + " to " + i + " is "
+ dpq.dist[i]);
}
}
*/
// Class to represent a node in the graph
/*class BinarySearchTree {
*//* Class containing left and right child of current node and key value*//*
class Node {
int key;
Node left, right;
public Node(int item) {
key = item;
left = right = null;
}
}
// Root of BST
Node root;
// Constructor
BinarySearchTree() {
root = null;
}
// This method mainly calls insertRec()
void insert(int key) {
root = insertRec(root, key);
}
*//* A recursive function to insert a new key in BST *//*
Node insertRec(Node root, int key) {
*//* If the tree is empty, return a new node *//*
if (root == null) {
root = new Node(key);
return root;
}
*//* Otherwise, recur down the tree *//*
if (key < root.key)
root.left = insertRec(root.left, key);
else if (key > root.key)
root.right = insertRec(root.right, key);
*//* return the (unchanged) node pointer *//*
return root;
}
// This method mainly calls InorderRec()
void inorder() {
inorderRec(root);
}
// A utility function to do inorder traversal of BST
void inorderRec(Node root) {
if (root != null) {
inorderRec(root.left);
System.out.println(root.key);
inorderRec(root.right);
}
}
// Driver Program to test above functions
public static void main(String[] args) {
BinarySearchTree tree = new BinarySearchTree();
*//* Let us create following BST
50
/ \
30 70
/ \ / \
20 40 60 80 *//*
tree.insert(50);
tree.insert(30);
tree.insert(20);
tree.insert(40);
tree.insert(70);
tree.insert(60);
tree.insert(80);
// print inorder traversal of the BST
tree.inorder();
}
} */
/*int maxPathSumUtil(Node node, Res res) {
// Base cases
if (node == null)
return 0;
if (node.left == null && node.right == null)
return node.data;
// Find maximum sum in left and right subtree. Also
// find maximum root to leaf sums in left and right
// subtrees and store them in ls and rs
int ls = maxPathSumUtil(node.left, res);
int rs = maxPathSumUtil(node.right, res);
// If both left and right children exist
if (node.left != null && node.right != null) {
// Update result if needed
res.val = Math.max(res.val, ls + rs + node.data);
// Return maxium possible value for root being
// on one side
return Math.max(ls, rs) + node.data;
}
// If any of the two children is empty, return
// root sum for root being on one side
return (node.left == null) ? rs + node.data
: ls + node.data;
} */
| Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 3649c9735fd9abc64b3174839e0a67eb | train_002.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
public class DIV_3_575 {
static Reader r = new Reader();
static PrintWriter out = new PrintWriter(System.out);
private static void solve1() throws IOException {
int t = r.nextInt();
StringBuilder res = new StringBuilder();
while (t-- > 0) {
long a = r.nextLong();
long b = r.nextLong();
long c = r.nextLong();
long ans = (a + b + c) / 2;
res.append(ans).append("\n");
}
out.print(res);
out.close();
}
private static void solve2() throws IOException {
int t = r.nextInt();
StringBuilder res = new StringBuilder();
while (t-- > 0) {
int n = r.nextInt();
int k = r.nextInt();
long arr[] = r.nextLongArray(n);
ArrayList<Integer> pos = new ArrayList<Integer>();
for (int i = 0; i < n; i++) {
if ((arr[i] & 1) != 0) {
pos.add(i + 1);
}
}
StringBuilder ans = new StringBuilder();
if (pos.size() >= k && ((pos.size() - k + 1) & 1) != 0) {
ans.append("YES").append("\n");
int idx = 0;
while (k-- > 1 && idx < pos.size()) {
ans.append(pos.get(idx++) + " ");
}
ans.append(n);
ans.append("\n");
} else {
ans.append("NO").append("\n");
}
res.append(ans);
}
out.print(res);
out.close();
}
static class Pair {
int fi, se;
public Pair(int fi, int se) {
this.fi = fi;
this.se = se;
}
}
static Pair x[], y[];
static int idx, max = (int) 1e5;
private static void hori(Pair o, int x_) {
Pair ele = new Pair(0, 0);
if (o.fi == 0 && o.se == 0) {
ele = new Pair(x_, x_);
} else if (o.fi == 0 && o.se == 1) {
ele = new Pair(x_, max);
} else if (o.fi == 1 && o.se == 0) {
ele = new Pair(-max, x_);
} else if (o.fi == 1 && o.se == 1) {
ele = new Pair(-max, max);
}
x[idx] = ele;
}
private static void verti(Pair o, int y_) {
Pair ele = new Pair(0, 0);
if (o.fi == 0 && o.se == 0) {
ele = new Pair(y_, y_);
} else if (o.fi == 0 && o.se == 1) {
ele = new Pair(-max, y_);
} else if (o.fi == 1 && o.se == 0) {
ele = new Pair(y_, max);
} else if (o.fi == 1 && o.se == 1) {
ele = new Pair(-max, max);
}
y[idx++] = ele;
}
private static boolean doIntersect(Pair o1, Pair o2) {
if (o1.fi >= o2.fi && o1.fi <= o2.se || o1.se >= o2.fi && o1.se <= o2.se || o2.fi >= o1.fi && o2.fi <= o1.se
|| o2.se >= o1.fi && o2.se <= o1.se) {
return true;
}
return false;
}
private static void solve3() throws IOException {
int t = r.nextInt();
StringBuilder res = new StringBuilder();
while (t-- > 0) {
int n = r.nextInt();
x = new Pair[n + 1];
y = new Pair[n + 1];
idx = 1;
for (int i = 1; i <= n; i++) {
int l = r.nextInt();
int m = r.nextInt();
int lt = r.nextInt();
int top = r.nextInt();
int rt = r.nextInt();
int down = r.nextInt();
Pair hori = new Pair(lt, rt);
Pair verti = new Pair(top, down);
hori(hori, l);
verti(verti, m);
}
Pair ex = x[1], ye = y[1];
boolean flag = true;
for (int i = 2; i <= n; i++) {
if (!doIntersect(ex, x[i]) || !doIntersect(ye, y[i])) {
flag = false;
break;
}
ex.fi = Math.max(ex.fi, x[i].fi);
ex.se = Math.min(ex.se, x[i].se);
ye.fi = Math.max(ye.fi, y[i].fi);
ye.se = Math.min(ye.se, y[i].se);
}
res.append(flag ? 1 + " " + (ex.fi + " " + ye.fi) : 0).append("\n");
}
out.print(res);
out.close();
}
private static void solve4() throws IOException {
int t = r.nextInt();
StringBuilder res = new StringBuilder();
StringBuilder seq = new StringBuilder("RGB");
while (seq.length() < (int) 2e5) {
seq.append("RGB");
}
while (t-- > 0) {
int n = r.nextInt();
int k = r.nextInt();
String s = r.next();
int ans = Integer.MAX_VALUE;
for (int i = 0; i < n - k + 1; i++) {
char l[] = s.substring(i, i + k).toCharArray();
char m[] = new char[k];
for (int a = 0; a < 3; a++) {
m = seq.substring(a, a + k).toCharArray();
int cnt = 0;
for (int j = 0; j < k; j++) {
if (l[j] != m[j])
cnt++;
}
ans = Math.min(ans, cnt);
}
if (ans == 0)
break;
}
res.append(ans).append("\n");
}
out.print(res);
out.close();
}
private static void solve5() throws IOException {
int t = r.nextInt();
StringBuilder res = new StringBuilder();
while (t-- > 0) {
int n = r.nextInt();
res.append(false).append("\n");
}
out.print(res);
out.close();
}
private static void solve6() throws IOException {
int t = r.nextInt();
StringBuilder res = new StringBuilder();
while (t-- > 0) {
int n = r.nextInt();
res.append(false).append("\n");
}
out.print(res);
out.close();
}
public static void main(String[] args) throws IOException {
// solve1();
// solve2();
// solve3();
solve4();
// solve5();
// solve6();
}
static class Reader {
final private int BUFFER_SIZE = 1 << 12;
boolean consume = false;
private byte[] buffer;
private int bufferPointer, bytesRead;
private boolean reachedEnd = false;
public Reader() {
buffer = new byte[BUFFER_SIZE];
bufferPointer = 0;
bytesRead = 0;
}
public boolean hasNext() {
return !reachedEnd;
}
private void fillBuffer() throws IOException {
bytesRead = System.in.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) {
buffer[0] = -1;
reachedEnd = true;
}
}
private void consumeSpaces() throws IOException {
while (read() <= ' ' && reachedEnd == false)
;
bufferPointer--;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) {
fillBuffer();
}
return buffer[bufferPointer++];
}
public String next() throws IOException {
StringBuilder sb = new StringBuilder();
consumeSpaces();
byte c = read();
do {
sb.append((char) c);
} while ((c = read()) > ' ');
if (consume) {
consumeSpaces();
}
;
if (sb.length() == 0) {
return null;
}
return sb.toString();
}
public String nextLine() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
return str;
}
public int nextInt() throws IOException {
consumeSpaces();
int ret = 0;
byte c = read();
boolean neg = (c == '-');
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (consume) {
consumeSpaces();
}
if (neg) {
return -ret;
}
return ret;
}
public long nextLong() throws IOException {
consumeSpaces();
long ret = 0;
byte c = read();
boolean neg = (c == '-');
if (neg) {
c = read();
}
do {
ret = ret * 10L + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (consume) {
consumeSpaces();
}
if (neg) {
return -ret;
}
return ret;
}
public double nextDouble() throws IOException {
consumeSpaces();
double ret = 0;
double div = 1;
byte 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 (consume) {
consumeSpaces();
}
if (neg) {
return -ret;
}
return ret;
}
public int[] nextIntArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public long[] nextLongArray(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = nextLong();
}
return a;
}
public int[][] nextIntMatrix(int n, int m) throws IOException {
int[][] grid = new int[n][m];
for (int i = 0; i < n; i++) {
grid[i] = nextIntArray(m);
}
return grid;
}
public char[][] nextCharacterMatrix(int n) throws IOException {
char[][] a = new char[n][];
for (int i = 0; i < n; i++) {
a[i] = next().toCharArray();
}
return a;
}
public void close() throws IOException {
if (System.in == null) {
return;
} else {
System.in.close();
}
}
}
} | Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | e3d71a3bd0c2361ab783818cb9a3b58a | train_002.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
public class DIV_3_575 {
static Reader r = new Reader();
static PrintWriter out = new PrintWriter(System.out);
private static void solve1() throws IOException {
int t = r.nextInt();
StringBuilder res = new StringBuilder();
while (t-- > 0) {
long a = r.nextLong();
long b = r.nextLong();
long c = r.nextLong();
long ans = (a + b + c) / 2;
res.append(ans).append("\n");
}
out.print(res);
out.close();
}
private static void solve2() throws IOException {
int t = r.nextInt();
StringBuilder res = new StringBuilder();
while (t-- > 0) {
int n = r.nextInt();
int k = r.nextInt();
long arr[] = r.nextLongArray(n);
ArrayList<Integer> pos = new ArrayList<Integer>();
for (int i = 0; i < n; i++) {
if ((arr[i] & 1) != 0) {
pos.add(i + 1);
}
}
StringBuilder ans = new StringBuilder();
if (pos.size() >= k && ((pos.size() - k + 1) & 1) != 0) {
ans.append("YES").append("\n");
int idx = 0;
while (k-- > 1 && idx < pos.size()) {
ans.append(pos.get(idx++) + " ");
}
ans.append(n);
ans.append("\n");
} else {
ans.append("NO").append("\n");
}
res.append(ans);
}
out.print(res);
out.close();
}
static class Pair {
int fi, se;
public Pair(int fi, int se) {
this.fi = fi;
this.se = se;
}
}
static Pair x[], y[];
static int idx, max = (int) 1e5;
private static void hori(Pair o, int x_) {
Pair ele = new Pair(0, 0);
if (o.fi == 0 && o.se == 0) {
ele = new Pair(x_, x_);
} else if (o.fi == 0 && o.se == 1) {
ele = new Pair(x_, max);
} else if (o.fi == 1 && o.se == 0) {
ele = new Pair(-max, x_);
} else if (o.fi == 1 && o.se == 1) {
ele = new Pair(-max, max);
}
x[idx] = ele;
}
private static void verti(Pair o, int y_) {
Pair ele = new Pair(0, 0);
if (o.fi == 0 && o.se == 0) {
ele = new Pair(y_, y_);
} else if (o.fi == 0 && o.se == 1) {
ele = new Pair(-max, y_);
} else if (o.fi == 1 && o.se == 0) {
ele = new Pair(y_, max);
} else if (o.fi == 1 && o.se == 1) {
ele = new Pair(-max, max);
}
y[idx++] = ele;
}
private static boolean doIntersect(Pair o1, Pair o2) {
if (o1.fi >= o2.fi && o1.fi <= o2.se || o1.se >= o2.fi && o1.se <= o2.se || o2.fi >= o1.fi && o2.fi <= o1.se
|| o2.se >= o1.fi && o2.se <= o1.se) {
return true;
}
return false;
}
private static void solve3() throws IOException {
int t = r.nextInt();
StringBuilder res = new StringBuilder();
while (t-- > 0) {
int n = r.nextInt();
x = new Pair[n + 1];
y = new Pair[n + 1];
idx = 1;
for (int i = 1; i <= n; i++) {
int l = r.nextInt();
int m = r.nextInt();
int lt = r.nextInt();
int top = r.nextInt();
int rt = r.nextInt();
int down = r.nextInt();
Pair hori = new Pair(lt, rt);
Pair verti = new Pair(top, down);
hori(hori, l);
verti(verti, m);
}
Pair ex = x[1], ye = y[1];
boolean flag = true;
for (int i = 2; i <= n; i++) {
if (!doIntersect(ex, x[i]) || !doIntersect(ye, y[i])) {
flag = false;
break;
}
ex.fi = Math.max(ex.fi, x[i].fi);
ex.se = Math.min(ex.se, x[i].se);
ye.fi = Math.max(ye.fi, y[i].fi);
ye.se = Math.min(ye.se, y[i].se);
}
res.append(flag ? 1 + " " + (ex.fi + " " + ye.fi) : 0).append("\n");
}
out.print(res);
out.close();
}
private static void solve4() throws IOException {
int t = r.nextInt();
StringBuilder res = new StringBuilder();
StringBuilder seq = new StringBuilder("RGB");
while (seq.length() < (int) 2e5) {
seq.append("RGB");
}
while (t-- > 0) {
int n = r.nextInt();
int k = r.nextInt();
String s = r.next();
int ans = Integer.MAX_VALUE;
for (int i = 0; i < n - k + 1; i++) {
char l[] = s.substring(i, i + k).toCharArray();
for (int a = 0; a < 3; a++) {
char m[] = seq.substring(a, a + k).toCharArray();
int cnt = 0;
for (int j = 0; j < k; j++) {
if (l[j] != m[j])
cnt++;
}
ans = Math.min(ans, cnt);
if (ans == 0)
break;
}
if (ans == 0)
break;
}
res.append(ans).append("\n");
}
out.print(res);
out.close();
}
private static void solve5() throws IOException {
int t = r.nextInt();
StringBuilder res = new StringBuilder();
while (t-- > 0) {
int n = r.nextInt();
res.append(false).append("\n");
}
out.print(res);
out.close();
}
private static void solve6() throws IOException {
int t = r.nextInt();
StringBuilder res = new StringBuilder();
while (t-- > 0) {
int n = r.nextInt();
res.append(false).append("\n");
}
out.print(res);
out.close();
}
public static void main(String[] args) throws IOException {
// solve1();
// solve2();
// solve3();
solve4();
// solve5();
// solve6();
}
static class Reader {
final private int BUFFER_SIZE = 1 << 12;
boolean consume = false;
private byte[] buffer;
private int bufferPointer, bytesRead;
private boolean reachedEnd = false;
public Reader() {
buffer = new byte[BUFFER_SIZE];
bufferPointer = 0;
bytesRead = 0;
}
public boolean hasNext() {
return !reachedEnd;
}
private void fillBuffer() throws IOException {
bytesRead = System.in.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) {
buffer[0] = -1;
reachedEnd = true;
}
}
private void consumeSpaces() throws IOException {
while (read() <= ' ' && reachedEnd == false)
;
bufferPointer--;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) {
fillBuffer();
}
return buffer[bufferPointer++];
}
public String next() throws IOException {
StringBuilder sb = new StringBuilder();
consumeSpaces();
byte c = read();
do {
sb.append((char) c);
} while ((c = read()) > ' ');
if (consume) {
consumeSpaces();
}
;
if (sb.length() == 0) {
return null;
}
return sb.toString();
}
public String nextLine() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
return str;
}
public int nextInt() throws IOException {
consumeSpaces();
int ret = 0;
byte c = read();
boolean neg = (c == '-');
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (consume) {
consumeSpaces();
}
if (neg) {
return -ret;
}
return ret;
}
public long nextLong() throws IOException {
consumeSpaces();
long ret = 0;
byte c = read();
boolean neg = (c == '-');
if (neg) {
c = read();
}
do {
ret = ret * 10L + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (consume) {
consumeSpaces();
}
if (neg) {
return -ret;
}
return ret;
}
public double nextDouble() throws IOException {
consumeSpaces();
double ret = 0;
double div = 1;
byte 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 (consume) {
consumeSpaces();
}
if (neg) {
return -ret;
}
return ret;
}
public int[] nextIntArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public long[] nextLongArray(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = nextLong();
}
return a;
}
public int[][] nextIntMatrix(int n, int m) throws IOException {
int[][] grid = new int[n][m];
for (int i = 0; i < n; i++) {
grid[i] = nextIntArray(m);
}
return grid;
}
public char[][] nextCharacterMatrix(int n) throws IOException {
char[][] a = new char[n][];
for (int i = 0; i < n; i++) {
a[i] = next().toCharArray();
}
return a;
}
public void close() throws IOException {
if (System.in == null) {
return;
} else {
System.in.close();
}
}
}
} | Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 0ccec2c728b5afe566cab8da453d74cc | train_002.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.*;
import java.util.StringTokenizer;
public class ProblemD {
public static InputStream inputStream = System.in;
public static OutputStream outputStream = System.out;
public static void main(String[] args) {
MyScanner scanner = new MyScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
int t = scanner.nextInt();
for (int p = 0; p < t; p++) {
int n = scanner.nextInt();
int k = scanner.nextInt();
String s = scanner.next();
int ans = Integer.MAX_VALUE;
int[][] dp = new int[n + 3][3];
for (int i = 0; i < 3; i++) {
char c = getChar(i);
int x = 0;
for (int j = 0; j < k; j++) {
if (s.charAt(j) != c) {
x++;
}
c = getNext(c);
}
dp[k - 1][i] = x;
ans = Math.min(ans, x);
}
for (int i = k; i < n; i++) {
for (int j = 0; j < 3; j++) {
int ind = (j + 2) % 3;
int x = dp[i - 1][ind];
if (s.charAt(i - k) != getChar(ind)) {
x--;
}
if (s.charAt(i) != getChar((j + k - 1) % 3)) {
x++;
}
dp[i][j] = x;
ans = Math.min(ans, x);
}
}
out.println(ans);
}
out.flush();
}
private static char getChar(int i) {
if (i == 0) {
return 'R';
}
if (i == 1) {
return 'G';
}
return 'B';
}
private static char getNext(char c) {
if (c == 'R') {
return 'G';
}
if (c == 'G') {
return 'B';
}
return 'R';
}
private static class MyScanner {
private BufferedReader bufferedReader;
private StringTokenizer stringTokenizer;
private MyScanner(InputStream inputStream) {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
}
private String next() {
while (stringTokenizer == null || !stringTokenizer.hasMoreElements()) {
try {
stringTokenizer = new StringTokenizer(bufferedReader.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return stringTokenizer.nextToken();
}
private int nextInt() {
return Integer.parseInt(next());
}
private long nextLong() {
return Long.parseLong(next());
}
private double nextDouble() {
return Double.parseDouble(next());
}
private String nextLine() {
String str = "";
try {
str = bufferedReader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
private static class Pair<F, S> {
private F first;
private S second;
public Pair() {}
public Pair(F first, S second) {
this.first = first;
this.second = second;
}
}
private static class Triple<F, S, T> {
private F first;
private S second;
private T third;
public Triple() {}
public Triple(F first, S second, T third) {
this.first = first;
this.second = second;
this.third = third;
}
}
}
| Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 3227ca2e24002f126ab2f637c3cb8036 | train_002.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.List;
public class Main {
private static final String NO = "NO";
private static final String YES = "YES";
InputStream is;
PrintWriter out;
String INPUT = "";
private static final long MOD = 998244353L;
private static final int MAX = 100000;
void solve() {
int Q = ni();
while (Q-- > 0) {
int N = ni();
int K = ni();
char[] str = ns().toCharArray();
char s[] = new char[] { 'R', 'G', 'B' };
int ans = K;
for (int i = 0; i < 3; i++) {
int cur = 0;
int l = 0;
for (int j = 0; j < N; j++) {
if (str[j] != s[(j + i) % 3])
cur++;
if (j >= K) {
if (str[j - K] != s[(j - K + i) % 3])
cur--;
}
if (j >= K - 1)
ans = Math.min(ans, cur);
// tr(i, j, cur);
}
}
out.println(ans);
}
}
long power(long a, long b) {
long x = 1, y = a;
while (b > 0) {
if (b % 2 != 0) {
x = (x * y) % MOD;
}
y = (y * y) % MOD;
b /= 2;
}
return x % MOD;
}
private long gcd(long a, long b) {
while (a != 0) {
long tmp = b % a;
b = a;
a = tmp;
}
return b;
}
void run() throws Exception {
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
if (!INPUT.isEmpty())
tr(System.currentTimeMillis() - s + "ms");
}
public static void main(String[] args) throws Exception {
new Main().run();
}
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private boolean vis[];
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) {
if (!(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 Integer[] na2(int n) {
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++)
a[i] = ni();
return a;
}
private int[][] na(int n, int m) {
int[][] a = new int[n][];
for (int i = 0; i < n; i++)
a[i] = na(m);
return a;
}
private Integer[][] na2(int n, int m) {
Integer[][] a = new Integer[n][];
for (int i = 0; i < n; i++)
a[i] = na2(m);
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 static void tr(Object... o) {
System.out.println(Arrays.deepToString(o));
}
} | Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 175479158761d533547d234edf2ac5b2 | train_002.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
import java.io.*;
import static java.lang.Math.*;
public class Test {
FastIO sc;
int n;
int[] dp;
int M = 1000000007;
void solve() throws Exception {
int t = sc.nextInt();
while (t-- != 0) {
StringBuilder s = new StringBuilder();
s.append("RGB");
while (s.length() < 2 * 1_00_00_0)
s.append(s);
int n = sc.nextInt(), k = sc.nextInt();
char[] giv = sc.next().toCharArray();
int ans = Integer.MAX_VALUE;
for (int i = 0; i < 3; i++) {
char[] temp = s.substring(i, i + k).toCharArray();
// System.out.println(Arrays.toString(temp));
for (int j = 0; j < giv.length; j++) {
// System.out.println(j+k);
if (j + k > giv.length)
break;
else {
int c = 0;
// System.out.println(j + " " + (j + k));
for (int j2 = j; j2 < j + k; j2++) {
if (temp[j2 - j] != giv[j2]) {
c++;
}
// System.out.print(giv[j2]);
}
// System.out.println();
ans = min(ans, c);
}
}
// System.out.println("===================");
}
System.out.println(ans);
}
}
void run() {
try {
sc = new FastIO();
solve();
sc.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(abs(-1));
}
}
public static void main(String[] args) {
try {
Locale.setDefault(Locale.US);
} catch (Exception ignore) {
}
new Test().run();
}
class FastIO extends PrintWriter {
private BufferedReader in;
private StringTokenizer stok;
FastIO() {
super(System.out);
in = new BufferedReader(new InputStreamReader(System.in));
}
FastIO(String s) throws FileNotFoundException {
super("".equals(s) ? "output.txt" : s + ".out");
in = new BufferedReader(new FileReader("".equals(s) ? "input.txt" : s + ".in"));
}
@Override
public void close() {
super.close();
try {
in.close();
} catch (IOException ignored) {
}
}
String next() {
while (stok == null || !stok.hasMoreTokens()) {
try {
stok = new StringTokenizer(in.readLine());
} catch (Exception e) {
return null;
}
}
return stok.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
try {
return in.readLine();
} catch (IOException e) {
return null;
}
}
char[] nextCharArray() {
return next().toCharArray();
}
}
class Pair {
int mon, fac;
Pair(int mon, int fac) {
this.mon = mon;
this.fac = fac;
}
}
void randomShuffle(int[] a) {
Random random = new Random();
for (int i = 1; i < a.length; i++) {
int x = random.nextInt(i + 1);
int xchg = a[i];
a[i] = a[x];
a[x] = xchg;
}
}
static boolean even(int n) {
int r = n & 1;
return r != 1 ? true : false;
}
} | Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 92494475a3e0b57a2698a63f9a3fbeb5 | train_002.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
import java.io.*;
import static java.lang.Math.*;
public class Test {
FastIO sc;
int n;
int[] dp;
int M = 1000000007;
void solve() throws Exception {
int t = sc.nextInt();
while (t-- != 0) {
int n = sc.nextInt(), k = sc.nextInt();
char[] giv = sc.next().toCharArray();
int ans = Integer.MAX_VALUE;
for (int i = 0; i < 3; i++) {
char[] s = { 'R', 'G', 'B' };
for (int j = 0; j < giv.length; j++) {
// System.out.println(j+k);
if (j + k > giv.length)
break;
else {
int c = 0;
int f = i;
// System.out.println(j + " " + (j + k));
for (int j2 = j; j2 < j + k; j2++) {
if (s[(f++) % 3] != giv[j2]) {
c++;
}
// System.out.print(giv[j2]);
}
// System.out.println();
ans = min(ans, c);
}
}
// System.out.println("===================");
}
System.out.println(ans);
}
}
void run() {
try {
sc = new FastIO();
solve();
sc.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(abs(-1));
}
}
public static void main(String[] args) {
try {
Locale.setDefault(Locale.US);
} catch (Exception ignore) {
}
new Test().run();
}
class FastIO extends PrintWriter {
private BufferedReader in;
private StringTokenizer stok;
FastIO() {
super(System.out);
in = new BufferedReader(new InputStreamReader(System.in));
}
FastIO(String s) throws FileNotFoundException {
super("".equals(s) ? "output.txt" : s + ".out");
in = new BufferedReader(new FileReader("".equals(s) ? "input.txt" : s + ".in"));
}
@Override
public void close() {
super.close();
try {
in.close();
} catch (IOException ignored) {
}
}
String next() {
while (stok == null || !stok.hasMoreTokens()) {
try {
stok = new StringTokenizer(in.readLine());
} catch (Exception e) {
return null;
}
}
return stok.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
try {
return in.readLine();
} catch (IOException e) {
return null;
}
}
char[] nextCharArray() {
return next().toCharArray();
}
}
class Pair {
int mon, fac;
Pair(int mon, int fac) {
this.mon = mon;
this.fac = fac;
}
}
void randomShuffle(int[] a) {
Random random = new Random();
for (int i = 1; i < a.length; i++) {
int x = random.nextInt(i + 1);
int xchg = a[i];
a[i] = a[x];
a[x] = xchg;
}
}
static boolean even(int n) {
int r = n & 1;
return r != 1 ? true : false;
}
} | Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 9dc754f010bcb33c3b8898e7314c3404 | train_002.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class RGBSubstring {
public static void main(String[] args) {
FastReader input=new FastReader();
int t=input.nextInt();
while(t-->0)
{
String a="RGB";
String b="BRG";
String c="GBR";
int n,k;
n=input.nextInt();
k=input.nextInt();
String s=input.next();
int q=k/3;
int r=k%3;
String s1="";
for(int i=0;i<q;i++)
{
s1+=a;
}
s1+=a.substring(0,r);
String s2="";
for(int i=0;i<q;i++)
{
s2+=b;
}
s2+=b.substring(0,r);
String s3="";
for(int i=0;i<q;i++)
{
s3+=c;
}
s3+=c.substring(0,r);
int min=Integer.MAX_VALUE;
for(int i=0;i<=n-k;i++)
{
String str=s.substring(i,i+k);
min=Math.min(min,changes(str,s1));
min=Math.min(min,changes(str,s2));
min=Math.min(min,changes(str,s3));
}
System.out.println(min);
}
}
public static int changes(String a,String b)
{
int c=0;
for(int i=0;i<a.length();i++)
{
if(a.charAt(i)!=b.charAt(i))
{
c++;
}
}
return c;
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 941569924bcd198d51617821b366f7ea | train_002.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int q = sc.nextInt();
for (int query = 0; query < q; query++) {
int n = sc.nextInt();
int k = sc.nextInt();
String s = sc.next();
long maxsymb = 0;
long[] symb = new long[3];
for (int i = 0; i < n - k + 1; i++) {
for (int l = 0; l < 3; l++) {
symb[l] = 0;
}
int pos1 = 0;
int pos2 = 1;
int pos3 = 2;
for (int j = 0; j < k; j++) {
char c = s.charAt(i + j);
if (c == 'R') {
symb[pos1]++;
} else if (c == 'B') {
symb[pos2]++;
} else {
symb[pos3]++;
}
pos1 = (pos1 + 1) % 3;
pos2 = (pos2 + 1) % 3;
pos3 = (pos3 + 1) % 3;
}
for (int l = 0; l < 3; l++) {
if (maxsymb < symb[l]) {
maxsymb = symb[l];
}
}
}
System.out.println(k - maxsymb);
}
}
} | Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | a69189a4c9870c370bc03b4576c27b4e | train_002.jsonl | 1487606700 | Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are k different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he wants to know the minimum number of days he should wait before sending a ranger to collect the orbs such that the probability of him getting at least one of each kind of orb is at least , where ε < 10 - 7.To better prepare himself, he wants to know the answer for q different values of pi. Since he is busy designing the battle strategy with Sam, he asks you for your help. | 256 megabytes | import java.util.Scanner;
/**
* Created by drproduck on 2/22/17.
*/
public class D {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int k = in.nextInt();
int q = in.nextInt();
double[] dp = new double[k + 1];
int[] res = new int[1001];
int qq = 1;
dp[0] = 1;
for (int n = 1; qq <= 1000; n++) { // n is number of day, qq is bound for query
for (int i = k; i > 0; i--) {
dp[i] = i / (double) k * dp[i] + (k - i + 1) / (double) k * dp[i - 1];
}
double a = (qq - Math.pow(10, -7))/2000;
while (qq <= 1000 && dp[k] >= (qq - Math.pow(10, -7)) / 2000.0) {
res[qq] = n;
qq++;
}
dp[0] = 0;
}
while (q-- > 0) {
System.out.println(res[in.nextInt()]);
}
}
}
| Java | ["1 1\n1", "2 2\n1\n2"] | 2 seconds | ["1", "2\n2"] | null | Java 8 | standard input | [
"dp",
"probabilities",
"math"
] | a2b71d66ea1fdc3249e37be3ab0e67ef | First line consists of two space separated integers k, q (1 ≤ k, q ≤ 1000) — number of different kinds of orbs and number of queries respectively. Each of the next q lines contain a single integer pi (1 ≤ pi ≤ 1000) — i-th query. | 2,200 | Output q lines. On i-th of them output single integer — answer for i-th query. | standard output | |
PASSED | bc301254e402dcba074609e82b0ddea8 | train_002.jsonl | 1487606700 | Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are k different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he wants to know the minimum number of days he should wait before sending a ranger to collect the orbs such that the probability of him getting at least one of each kind of orb is at least , where ε < 10 - 7.To better prepare himself, he wants to know the answer for q different values of pi. Since he is busy designing the battle strategy with Sam, he asks you for your help. | 256 megabytes | //Codeforces Round 399
import java.io.*;
import java.util.*;
public class TaskD {
public static void main (String[] args) throws IOException {
FastScanner fs = new FastScanner(System.in);
PrintWriter pw = new PrintWriter(new BufferedOutputStream(System.out));
int k = fs.nextInt();
int q = fs.nextInt();
double[][] d = new double[1001][10000];
double w = 1;
for (int i = 1; i < 10000; i++) {
w *= 1/((double)k);
d[1][i] = w;
}
w = 1;
for (int i = 1; i <= k; i++) {
w *= ((double)(i))/((double)k);
d[i][i] = w;
}
for (int i = 2; i <= k; i++) {
for (int j = i+1; j < 10000; j++) {
d[i][j] = (d[i][j-1] + d[i-1][j-1])*((double)(i))/((double)k);
}
}
for (int i = k; i < 10000; i++) {
d[k][i] = d[k][i]*2000;
}
/*for (int i = 1; i < 1+10; i++ ) {
pw.println(d[1][i]);
}
pw.println();
for (int i = k; i < k+10; i++ ) {
pw.println(d[k][i]);
}*/
for (int i = 0; i < q; i++) {
double p = ((double)(fs.nextInt())) - 1E-7;
int lf = 0;
int rt = 9999;
while (rt - lf > 1) {
int md = (lf+rt) >> 1;
if (d[k][md] > p) {
rt = md;
} else {
lf = md;
}
}
if (d[k][lf] > p) {
rt = lf;
}
pw.println(rt);
}
pw.close();
}
static class FastScanner {
BufferedReader reader;
StringTokenizer tokenizer;
FastScanner(InputStream i) {
reader = new BufferedReader(new InputStreamReader(i));
tokenizer = new StringTokenizer("");
}
String next() throws IOException {
while(!tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(reader.readLine());
return tokenizer.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
}
} | Java | ["1 1\n1", "2 2\n1\n2"] | 2 seconds | ["1", "2\n2"] | null | Java 8 | standard input | [
"dp",
"probabilities",
"math"
] | a2b71d66ea1fdc3249e37be3ab0e67ef | First line consists of two space separated integers k, q (1 ≤ k, q ≤ 1000) — number of different kinds of orbs and number of queries respectively. Each of the next q lines contain a single integer pi (1 ≤ pi ≤ 1000) — i-th query. | 2,200 | Output q lines. On i-th of them output single integer — answer for i-th query. | standard output | |
PASSED | 87e14bc3d5ba07f7f1f9839d6ba33f5e | train_002.jsonl | 1487606700 | Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are k different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he wants to know the minimum number of days he should wait before sending a ranger to collect the orbs such that the probability of him getting at least one of each kind of orb is at least , where ε < 10 - 7.To better prepare himself, he wants to know the answer for q different values of pi. Since he is busy designing the battle strategy with Sam, he asks you for your help. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public void solve(int testNumber, FastReader in, PrintWriter out) {
int k = in.nextInt();
int Q = in.nextInt();
int n = 7500;
double[][] dp = new double[k + 1][n + 1];
dp[0][0] = 1.0D;
double K = k;
for (int i = 1; i < n; ++i)
for (int j = 1; j <= k; ++j)
dp[j][i] = dp[j][i - 1] * (j / K) + dp[j - 1][i - 1] * ((K - j + 1) / K);
for (int q = 0; q < Q; ++q) {
double d = in.nextInt();
d /= 2000.0D;
int low = -1;
int high = n;
while (high - low > 1) {
int mid = (high + low) >>> 1;
if (Double.compare(dp[k][mid], d) >= 0) {
high = mid;
} else {
low = mid;
}
}
out.println(high);
}
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar;
private int pnumChars;
public FastReader(InputStream stream) {
this.stream = stream;
}
private int pread() {
if (pnumChars == -1) {
throw new InputMismatchException();
}
if (curChar >= pnumChars) {
curChar = 0;
try {
pnumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (pnumChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = pread();
while (isSpaceChar(c))
c = pread();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = pread();
}
int res = 0;
do {
if (c == ',') {
c = pread();
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = pread();
} while (!isSpaceChar(c));
return res * sgn;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
| Java | ["1 1\n1", "2 2\n1\n2"] | 2 seconds | ["1", "2\n2"] | null | Java 8 | standard input | [
"dp",
"probabilities",
"math"
] | a2b71d66ea1fdc3249e37be3ab0e67ef | First line consists of two space separated integers k, q (1 ≤ k, q ≤ 1000) — number of different kinds of orbs and number of queries respectively. Each of the next q lines contain a single integer pi (1 ≤ pi ≤ 1000) — i-th query. | 2,200 | Output q lines. On i-th of them output single integer — answer for i-th query. | standard output | |
PASSED | 328e679d87b6dd49c5f04d8dcf4aab6f | train_002.jsonl | 1487606700 | Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are k different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he wants to know the minimum number of days he should wait before sending a ranger to collect the orbs such that the probability of him getting at least one of each kind of orb is at least , where ε < 10 - 7.To better prepare himself, he wants to know the answer for q different values of pi. Since he is busy designing the battle strategy with Sam, he asks you for your help. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public void solve(int testNumber, FastReader in, PrintWriter out) {
int k = in.nextInt();
int Q = in.nextInt();
int n = 7500;
double[][] dp = new double[k + 1][n + 1];
dp[0][0] = 1.0D;
double K = k;
for (int i = 1; i < n; ++i) {
for (int j = 1; j <= k; ++j) {
dp[j][i] = dp[j][i - 1] * (j / K) + dp[j - 1][i - 1] * ((K - j + 1) / K);
}
}
for (int q = 0; q < Q; ++q) {
int p = in.nextInt();
double d = p;
d /= 2000.0D;
int low = -1;
int high = n;
while (high - low > 1) {
int mid = (high + low) >>> 1;
if (Double.compare(dp[k][mid], d) >= 0) {
high = mid;
} else {
low = mid;
}
}
out.println(high);
}
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar;
private int pnumChars;
public FastReader(InputStream stream) {
this.stream = stream;
}
private int pread() {
if (pnumChars == -1) {
throw new InputMismatchException();
}
if (curChar >= pnumChars) {
curChar = 0;
try {
pnumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (pnumChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = pread();
while (isSpaceChar(c))
c = pread();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = pread();
}
int res = 0;
do {
if (c == ',') {
c = pread();
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = pread();
} while (!isSpaceChar(c));
return res * sgn;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
| Java | ["1 1\n1", "2 2\n1\n2"] | 2 seconds | ["1", "2\n2"] | null | Java 8 | standard input | [
"dp",
"probabilities",
"math"
] | a2b71d66ea1fdc3249e37be3ab0e67ef | First line consists of two space separated integers k, q (1 ≤ k, q ≤ 1000) — number of different kinds of orbs and number of queries respectively. Each of the next q lines contain a single integer pi (1 ≤ pi ≤ 1000) — i-th query. | 2,200 | Output q lines. On i-th of them output single integer — answer for i-th query. | standard output | |
PASSED | f91877aa155db516864641eafae1e2ce | train_002.jsonl | 1487606700 | Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are k different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he wants to know the minimum number of days he should wait before sending a ranger to collect the orbs such that the probability of him getting at least one of each kind of orb is at least , where ε < 10 - 7.To better prepare himself, he wants to know the answer for q different values of pi. Since he is busy designing the battle strategy with Sam, he asks you for your help. | 256 megabytes | //package Round_399;
import java.io.PrintWriter;
import java.util.Scanner;
public class D {
public D() {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int k = sc.nextInt();
int q = sc.nextInt();
double[] dp = new double[1004];
int[] ans = new int[1004];
dp[0] = 1.;
int d = 1;
double eps = 1e-7;
for (int i = 1; d <= 1000; i++) {
for (int x = k; x > 0; x--)
dp[x] = (x * dp[x] + (k - x + 1) * dp[x - 1]) / k;
while (d <= 1000 && 2000 * dp[k] >= (d - eps))
ans[d++] = i;
dp[0] = 0;
}
for (int i = 0; i < q; i++) {
int p = sc.nextInt();
out.println(ans[p]);
}
sc.close();
out.close();
}
public static void main(String[] args) {
new D();
}
} | Java | ["1 1\n1", "2 2\n1\n2"] | 2 seconds | ["1", "2\n2"] | null | Java 8 | standard input | [
"dp",
"probabilities",
"math"
] | a2b71d66ea1fdc3249e37be3ab0e67ef | First line consists of two space separated integers k, q (1 ≤ k, q ≤ 1000) — number of different kinds of orbs and number of queries respectively. Each of the next q lines contain a single integer pi (1 ≤ pi ≤ 1000) — i-th query. | 2,200 | Output q lines. On i-th of them output single integer — answer for i-th query. | standard output | |
PASSED | e6d2037d1322830a23c888f5f037c4b5 | train_002.jsonl | 1487606700 | Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are k different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he wants to know the minimum number of days he should wait before sending a ranger to collect the orbs such that the probability of him getting at least one of each kind of orb is at least , where ε < 10 - 7.To better prepare himself, he wants to know the answer for q different values of pi. Since he is busy designing the battle strategy with Sam, he asks you for your help. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class D {
public static void main(String[] args) throws IOException {
FastScanner scan = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int n = scan.nextInt(), m = scan.nextInt();
double[][] dp = new double[10005][n+1];
dp[0][0] = 1;
for(int i = 1; i < 10005; i++){
for(int j = 0; j < n+1; j++){
dp[i][j] += dp[i-1][j]*((double)j/n);
if(j > 0)dp[i][j] += dp[i-1][j-1]*((double)(n-j+1)/n);
}
}
for(int i = 0; i < m; i++){
double p = (scan.nextDouble()-1e-7)/2000;
for(int j = 0; j < 10005; j++){
if(dp[j][n] >= p){
out.println(j);
break;
}
}
}
out.close();
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(br.readLine());
} catch (Exception e){e.printStackTrace();}
}
public String next() {
if (st.hasMoreTokens()) return st.nextToken();
try {st = new StringTokenizer(br.readLine());}
catch (Exception 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 String nextLine() {
String line = "";
try {line = br.readLine();}
catch (Exception e) {e.printStackTrace();}
return line;
}
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 double[] nextDoubleArray(int n){
double[] a = new double[n];
for(int i = 0; i < n; i++) a[i] = nextDouble();
return a;
}
public char[][] nextGrid(int n, int m){
char[][] grid = new char[n][m];
for(int i = 0; i < n; i++) grid[i] = next().toCharArray();
return grid;
}
}
}
| Java | ["1 1\n1", "2 2\n1\n2"] | 2 seconds | ["1", "2\n2"] | null | Java 8 | standard input | [
"dp",
"probabilities",
"math"
] | a2b71d66ea1fdc3249e37be3ab0e67ef | First line consists of two space separated integers k, q (1 ≤ k, q ≤ 1000) — number of different kinds of orbs and number of queries respectively. Each of the next q lines contain a single integer pi (1 ≤ pi ≤ 1000) — i-th query. | 2,200 | Output q lines. On i-th of them output single integer — answer for i-th query. | standard output | |
PASSED | 2476e189365887e051f1a1cb4c47ad6e | train_002.jsonl | 1487606700 | Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are k different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he wants to know the minimum number of days he should wait before sending a ranger to collect the orbs such that the probability of him getting at least one of each kind of orb is at least , where ε < 10 - 7.To better prepare himself, he wants to know the answer for q different values of pi. Since he is busy designing the battle strategy with Sam, he asks you for your help. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.StringTokenizer;
public class D {
public static void main(String[] args) throws NumberFormatException, IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int k = sc.nextInt();
int q = sc.nextInt();
int td = k * 10 + 1;
double[][] e = new double[k + 1][td];
e[0][0] = 1;
for(int i = 1; i <= k; i++) {
for(int j = i; j < td; j++) {
e[i][j] = e[i - 1][j - 1] * (k - i + 1) / k + e[i][j - 1] * i / k;
}
}
while(q-->0) {
int p = sc.nextInt();
for(int j = 1; ; j++) {
if(p - e[k][j] * 2000 < 1e-7) {
System.out.println(j);
break;
}
}
}
out.flush();
out.close();
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
Scanner(FileReader f) {
br = new BufferedReader(f);
}
public boolean ready() throws IOException {
return br.ready();
}
Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
String nextLine() throws IOException {
return br.readLine();
}
int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(next());
}
long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(next());
}
}
} | Java | ["1 1\n1", "2 2\n1\n2"] | 2 seconds | ["1", "2\n2"] | null | Java 8 | standard input | [
"dp",
"probabilities",
"math"
] | a2b71d66ea1fdc3249e37be3ab0e67ef | First line consists of two space separated integers k, q (1 ≤ k, q ≤ 1000) — number of different kinds of orbs and number of queries respectively. Each of the next q lines contain a single integer pi (1 ≤ pi ≤ 1000) — i-th query. | 2,200 | Output q lines. On i-th of them output single integer — answer for i-th query. | standard output | |
PASSED | 35a328c3b3a2646d86480d695e6fb700 | train_002.jsonl | 1487606700 | Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are k different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he wants to know the minimum number of days he should wait before sending a ranger to collect the orbs such that the probability of him getting at least one of each kind of orb is at least , where ε < 10 - 7.To better prepare himself, he wants to know the answer for q different values of pi. Since he is busy designing the battle strategy with Sam, he asks you for your help. | 256 megabytes | import java.io.*;
import java.util.*;
public class D {
public static void solution(BufferedReader reader, PrintWriter writer)
throws IOException {
In in = new In(reader);
Out out = new Out(writer);
int k = in.nextInt(), q = in.nextInt();
double EPS = 1e-7;
double[] dp = new double[] { 0, 2000 };
int[] rst = new int[1001];
int from = 0;
if (k == 1)
while (from <= Math.min(dp[k] + EPS, 1000))
rst[from++] = 1;
for (int d = 1;; d++) {
double[] next = new double[Math.min(d + 1, k) + 1];
for (int i = 1; i <= Math.min(d, k); i++) {
next[i] += dp[i] * ((double) i / k);
if (i + 1 <= k)
next[i + 1] += dp[i] * (((double) k - i) / k);
}
if (next.length > k) {
while (from <= Math.min(next[k] + EPS, 1000))
rst[from++] = d + 1;
if (from > 1000)
break;
}
dp = next;
}
for (int i = 0; i < q; i++)
out.println(rst[in.nextInt()]);
}
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(
new InputStreamReader(System.in));
PrintWriter writer = new PrintWriter(
new BufferedWriter(new OutputStreamWriter(System.out)));
solution(reader, writer);
writer.close();
}
protected static class In {
private BufferedReader reader;
private StringTokenizer tokenizer = new StringTokenizer("");
public In(BufferedReader reader) {
this.reader = reader;
}
public String next() throws IOException {
while (!tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(reader.readLine());
return tokenizer.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public int[] nextIntArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public int[] nextIntArray1(int n) throws IOException {
int[] a = new int[n + 1];
for (int i = 1; i <= n; i++)
a[i] = nextInt();
return a;
}
public int[] nextIntArraySorted(int n) throws IOException {
int[] a = nextIntArray(n);
Random r = new Random();
for (int i = 0; i < n; i++) {
int j = i + r.nextInt(n - i);
int t = a[i];
a[i] = a[j];
a[j] = t;
}
Arrays.sort(a);
return a;
}
public long[] nextLongArray(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public long[] nextLongArray1(int n) throws IOException {
long[] a = new long[n + 1];
for (int i = 1; i <= n; i++)
a[i] = nextLong();
return a;
}
public long[] nextLongArraySorted(int n) throws IOException {
long[] a = nextLongArray(n);
Random r = new Random();
for (int i = 0; i < n; i++) {
int j = i + r.nextInt(n - i);
long t = a[i];
a[i] = a[j];
a[j] = t;
}
Arrays.sort(a);
return a;
}
}
protected static class Out {
private PrintWriter writer;
private static boolean local = System
.getProperty("ONLINE_JUDGE") == null;
public Out(PrintWriter writer) {
this.writer = writer;
}
public void print(char c) {
writer.print(c);
}
public void print(int a) {
writer.print(a);
}
public void printb(int a) {
writer.print(a);
writer.print(' ');
}
public void println(Object a) {
writer.println(a);
}
public void println(Object[] os) {
for (int i = 0; i < os.length; i++) {
writer.print(os[i]);
writer.print(' ');
}
writer.println();
}
public void println(int[] a) {
for (int i = 0; i < a.length; i++) {
writer.print(a[i]);
writer.print(' ');
}
writer.println();
}
public void println(long[] a) {
for (int i = 0; i < a.length; i++) {
writer.print(a[i]);
writer.print(' ');
}
writer.println();
}
public void flush() {
writer.flush();
}
public static void db(Object... objects) {
if (local)
System.out.println(Arrays.deepToString(objects));
}
}
}
| Java | ["1 1\n1", "2 2\n1\n2"] | 2 seconds | ["1", "2\n2"] | null | Java 8 | standard input | [
"dp",
"probabilities",
"math"
] | a2b71d66ea1fdc3249e37be3ab0e67ef | First line consists of two space separated integers k, q (1 ≤ k, q ≤ 1000) — number of different kinds of orbs and number of queries respectively. Each of the next q lines contain a single integer pi (1 ≤ pi ≤ 1000) — i-th query. | 2,200 | Output q lines. On i-th of them output single integer — answer for i-th query. | standard output | |
PASSED | a3ba91dc1e6d4fa90932a799afecc2b1 | train_002.jsonl | 1487606700 | Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are k different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he wants to know the minimum number of days he should wait before sending a ranger to collect the orbs such that the probability of him getting at least one of each kind of orb is at least , where ε < 10 - 7.To better prepare himself, he wants to know the answer for q different values of pi. Since he is busy designing the battle strategy with Sam, he asks you for your help. | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) throws Exception {
Scanner scan = new Scanner(System.in);
int k = scan.nextInt();
int q = scan.nextInt();
double[] dp = new double[1004];
int[] answer = new int[1004];
dp[0] = 1.;
int d = 1;
double epsilon = 0.0000001;
for (int i = 1; d <= 1000; i++) {
for (int x = k; x > 0; x--)
dp[x] = (x * dp[x] + (k - x + 1) * dp[x - 1]) / k;
while (d <= 1000 && 2000 * dp[k] >= (d - epsilon))
answer[d++] = i;
dp[0] = 0;
}
for (int i = 0; i < q; i++) {
int p = scan.nextInt();
System.out.println(answer[p]);
}
scan.close();
}
} | Java | ["1 1\n1", "2 2\n1\n2"] | 2 seconds | ["1", "2\n2"] | null | Java 8 | standard input | [
"dp",
"probabilities",
"math"
] | a2b71d66ea1fdc3249e37be3ab0e67ef | First line consists of two space separated integers k, q (1 ≤ k, q ≤ 1000) — number of different kinds of orbs and number of queries respectively. Each of the next q lines contain a single integer pi (1 ≤ pi ≤ 1000) — i-th query. | 2,200 | Output q lines. On i-th of them output single integer — answer for i-th query. | standard output | |
PASSED | ae131bd664df1733b736fa4e5d60150b | train_002.jsonl | 1487606700 | Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are k different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he wants to know the minimum number of days he should wait before sending a ranger to collect the orbs such that the probability of him getting at least one of each kind of orb is at least , where ε < 10 - 7.To better prepare himself, he wants to know the answer for q different values of pi. Since he is busy designing the battle strategy with Sam, he asks you for your help. | 256 megabytes | import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.PrintWriter;
public class D_399 {
public static int mod = 1000000007;
static FastReader scan = new FastReader();
static PrintWriter out = new PrintWriter(System.out);
public static void main(String args[]) {
/******************* code ***********************/
int k = scan.nextInt();
int q = scan.nextInt();
int max = 7500;
double dp[][] = new double[k + 1][max];
dp[0][0] = 1;
double tmp = k;
for (int i = 1; i < max; i++) {
for (int j = 1; j <= k; j++) {
dp[j][i] = (j / tmp) * dp[j][i - 1] + ((k - j + 1) / tmp) * dp[j - 1][i - 1];
}
}
while (q-- > 0) {
int p = scan.nextInt();
double d = p / 2000.0;
int index = binaryupper(dp[k], d, 1, max);
out.println(index);
}
out.close();
}
public static int binaryupper(double[] a, double m, int l, int r) {
int mid;
while (l <= r) {
mid = (l + r) / 2;
if (m > a[mid])
l = mid + 1;
else
r = mid - 1;
}
return l;
}
static class Pair implements Comparable<Pair> {
int x;
int y;
Pair(int xx, int yy) {
x = xx;
y = yy;
}
@Override
public int compareTo(Pair o) {
if (Long.compare(this.y, o.y) != 0)
return Integer.compare(this.y, o.y);
else
return Long.compare(this.x, o.x);
}
}
public static void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
public static long pow(long x, long n, long mod) {
long res = 1;
x %= mod;
while (n > 0) {
if (n % 2 == 1) {
res = (res * x) % mod;
}
x = (x * x) % mod;
n /= 2;
}
return res;
}
/************** Scanner ********************/
static class FastReader {
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;
}
}
}
| Java | ["1 1\n1", "2 2\n1\n2"] | 2 seconds | ["1", "2\n2"] | null | Java 8 | standard input | [
"dp",
"probabilities",
"math"
] | a2b71d66ea1fdc3249e37be3ab0e67ef | First line consists of two space separated integers k, q (1 ≤ k, q ≤ 1000) — number of different kinds of orbs and number of queries respectively. Each of the next q lines contain a single integer pi (1 ≤ pi ≤ 1000) — i-th query. | 2,200 | Output q lines. On i-th of them output single integer — answer for i-th query. | standard output | |
PASSED | 5edebac02aeb6384d2e7b244d14a8407 | train_002.jsonl | 1487606700 | Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are k different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he wants to know the minimum number of days he should wait before sending a ranger to collect the orbs such that the probability of him getting at least one of each kind of orb is at least , where ε < 10 - 7.To better prepare himself, he wants to know the answer for q different values of pi. Since he is busy designing the battle strategy with Sam, he asks you for your help. | 256 megabytes | import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
new Main().solve();
}
int inf = 2000000000;
int mod = 1000000007;
double eps = 0.0000000001;
PrintWriter out;
int n;
int m;
ArrayList<Integer>[] g;
void solve() throws Exception {
Reader in;
BufferedReader br;
try {
//br = new BufferedReader( new FileReader("input.txt") );
in = new Reader("input.txt");
out = new PrintWriter( new BufferedWriter(new FileWriter("output.txt")) );
}
catch (Exception e) {
//br = new BufferedReader( new InputStreamReader( System.in ) );
in = new Reader();
out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out)) );
}
int k = in.nextInt();
int n = in.nextInt();
double[][] dp = new double[8000][1001];
dp[0][0] = 1;
for (int i = 1; i <= 7274; i++)
for (int j = 0; j < 1000; j++)
dp[i][j+1] = dp[i-1][j]*(1.0*(k-j)/k) + dp[i-1][j+1]*(1.0*(j+1)/k);
for (int i = 0; i < n; i++) {
double p = in.nextInt()/2000.0;
int ans = 1;
while (p > dp[ans][k]+eps)
ans++;
out.println(ans);
}
out.flush();
out.close();
}
class Pair implements Comparable<Pair>{
int a;
int b;
Pair(int a, int b) {
this.a = a;
this.b = b;
}
public int compareTo(Pair p) {
if (a > p.a)
return 1;
if (a < p.a)
return -1;
return 0;
}
}
class Item {
int a;
int b;
int c;
Item(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
}
class Reader {
BufferedReader br;
StringTokenizer tok;
Reader(String file) throws IOException {
br = new BufferedReader( new FileReader(file) );
}
Reader() throws IOException {
br = new BufferedReader( new InputStreamReader(System.in) );
}
String next() throws IOException {
while (tok == null || !tok.hasMoreElements())
tok = new StringTokenizer(br.readLine());
return tok.nextToken();
}
int nextInt() throws NumberFormatException, IOException {
return Integer.valueOf(next());
}
long nextLong() throws NumberFormatException, IOException {
return Long.valueOf(next());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.valueOf(next());
}
String nextLine() throws IOException {
return br.readLine();
}
}
} | Java | ["1 1\n1", "2 2\n1\n2"] | 2 seconds | ["1", "2\n2"] | null | Java 8 | standard input | [
"dp",
"probabilities",
"math"
] | a2b71d66ea1fdc3249e37be3ab0e67ef | First line consists of two space separated integers k, q (1 ≤ k, q ≤ 1000) — number of different kinds of orbs and number of queries respectively. Each of the next q lines contain a single integer pi (1 ≤ pi ≤ 1000) — i-th query. | 2,200 | Output q lines. On i-th of them output single integer — answer for i-th query. | standard output | |
PASSED | 208c5d56e270f73067032292a4806336 | train_002.jsonl | 1487606700 | Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are k different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he wants to know the minimum number of days he should wait before sending a ranger to collect the orbs such that the probability of him getting at least one of each kind of orb is at least , where ε < 10 - 7.To better prepare himself, he wants to know the answer for q different values of pi. Since he is busy designing the battle strategy with Sam, he asks you for your help. | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.*;
import java.util.*;
import java.util.Map.Entry;
public class TestClass {
private static InputStream stream;
private static byte[] buf = new byte[1024];
private static int curChar;
private static int numChars;
private static SpaceCharFilter filter;
private static PrintWriter pw;
public static class Pair implements Comparable<Pair> {
long u;
long v;
public Pair(long u, long v) {
this.u = u;
this.v = v;
}
public int hashCode() {
int hu = (int) (u ^ (u >>> 32));
int hv = (int) (v ^ (v >>> 32));
return 31 * hu + hv;
}
public boolean equals(Object o) {
Pair other = (Pair) o;
return u == other.u && v == other.v;
}
public int compareTo(Pair other) {
return Long.compare(u, other.u) != 0 ? Long.compare(u, other.u) : Long.compare(v, other.v);
}
public String toString() {
return u+" "+v;
}
}
private static void soln() {
double dp[][] = new double[7500][1001];
int k = nI();
int q = nI();
int ans[] = new int[q];
Pair p[] = new Pair[q];
for(int i=0;i<q;i++)
p[i] = new Pair(nI(),i);
Arrays.sort(p);
dp[0][0] = 1;
int counter = 0;
double dk = k,pm = 2000;
for(int i=1;i<7500;i++){
for(int j=1;j<=1000;j++)
dp[i][j]+=dp[i-1][j]*(j/dk)+dp[i-1][j-1]*((k-(j-1))/dk);
while(counter!=q){
if(p[counter].u/pm<=dp[i][k]){
ans[(int)p[counter].v] = i;
counter++;
}
else
break;
}
if(counter==q)
break;
}
for(int i=0;i<q;i++)
pw.println(ans[i]);
}
public static void main(String[] args) {
InputReader(System.in);
pw = new PrintWriter(System.out);
soln();
pw.close();
}
// To Get Input
// Some Buffer Methods
public static void InputReader(InputStream stream1) {
stream = stream1;
}
private static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private static boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
private static int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
private static int nI() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
private static long nL() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
private static String nextToken() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private static String nLi() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
private static boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
private interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
} | Java | ["1 1\n1", "2 2\n1\n2"] | 2 seconds | ["1", "2\n2"] | null | Java 8 | standard input | [
"dp",
"probabilities",
"math"
] | a2b71d66ea1fdc3249e37be3ab0e67ef | First line consists of two space separated integers k, q (1 ≤ k, q ≤ 1000) — number of different kinds of orbs and number of queries respectively. Each of the next q lines contain a single integer pi (1 ≤ pi ≤ 1000) — i-th query. | 2,200 | Output q lines. On i-th of them output single integer — answer for i-th query. | standard output | |
PASSED | 6e559d68ff9d7816f03ca2fd4174116e | train_002.jsonl | 1487606700 | Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are k different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he wants to know the minimum number of days he should wait before sending a ranger to collect the orbs such that the probability of him getting at least one of each kind of orb is at least , where ε < 10 - 7.To better prepare himself, he wants to know the answer for q different values of pi. Since he is busy designing the battle strategy with Sam, he asks you for your help. | 256 megabytes | //
// John.java
// Created by Alister Estrada Cueto on 9/25/18.
import java.util.*;
public class John{
public static void main(String [] args){
Scanner sc = new Scanner(System.in);
int k = sc.nextInt();
int q = sc.nextInt();
int[] p = new int[q];
long eps = 1/10000000;
int n = 1004;
for (int i = 0;i < q ;i++ ) {
p[i] = sc.nextInt();
}
double[] prob = new double[n];
int[] ans = new int[n];
prob[0] = 1;
for (int i = 1,m = 1;m<=1000 ;i++ ) {
for (int j = k;j>0 ;j-- ) {
prob[j] = (j * prob[j] + (k-j+1) * prob[j-1])/k;
}
while(m<= 1000 && 2000*prob[k] >= (m-eps)){
ans[m] = i;
m++;
}
prob[0] = 0;
}
for (int i = 0;i < p.length ;i++ ) {
System.out.println(ans[p[i]]);
}
}
} | Java | ["1 1\n1", "2 2\n1\n2"] | 2 seconds | ["1", "2\n2"] | null | Java 8 | standard input | [
"dp",
"probabilities",
"math"
] | a2b71d66ea1fdc3249e37be3ab0e67ef | First line consists of two space separated integers k, q (1 ≤ k, q ≤ 1000) — number of different kinds of orbs and number of queries respectively. Each of the next q lines contain a single integer pi (1 ≤ pi ≤ 1000) — i-th query. | 2,200 | Output q lines. On i-th of them output single integer — answer for i-th query. | standard output | |
PASSED | 4bc5ac1004bdbf64a5e0e2301f321d27 | train_002.jsonl | 1487606700 | Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are k different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he wants to know the minimum number of days he should wait before sending a ranger to collect the orbs such that the probability of him getting at least one of each kind of orb is at least , where ε < 10 - 7.To better prepare himself, he wants to know the answer for q different values of pi. Since he is busy designing the battle strategy with Sam, he asks you for your help. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
public class Main2 {
static long mod = 1000000007L;
public static void main(String[] args) {
FastScanner scanner = new FastScanner();
int k = scanner.nextInt();
int q = scanner.nextInt();
double[] dp = new double[k + 10];
double[] probs = new double[10000];
dp[1] = 1.;
probs[1] = dp[k];
for (int i = 2; i < 10000; i++) {
double[] ndp = new double[k + 10];
for (int j = 1; j <= Math.min(k, i - 1); j++) {
ndp[j] = ndp[j] + (dp[j] * j) / k;
ndp[j + 1] = ndp[j + 1] + (dp[j] * (k - j)) / k;
}
probs[i] = ndp[k];
dp = ndp;
}
for (int i = 0; i < q; i++) {
double p = scanner.nextInt() / 2000.0;
for (int j = k; j < 10000; j++) {
if (probs[j] >= p) {
System.out.println(j);
break;
}
}
}
}
public static class FastScanner {
BufferedReader br;
StringTokenizer st;
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();
}
String nextLine() {
try {
return br.readLine();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException();
}
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
}
}
/*
1 1 1
1 1 2
1 2 1
2 1 1
1 1 3
*/ | Java | ["1 1\n1", "2 2\n1\n2"] | 2 seconds | ["1", "2\n2"] | null | Java 8 | standard input | [
"dp",
"probabilities",
"math"
] | a2b71d66ea1fdc3249e37be3ab0e67ef | First line consists of two space separated integers k, q (1 ≤ k, q ≤ 1000) — number of different kinds of orbs and number of queries respectively. Each of the next q lines contain a single integer pi (1 ≤ pi ≤ 1000) — i-th query. | 2,200 | Output q lines. On i-th of them output single integer — answer for i-th query. | standard output | |
PASSED | eacac43183b51478295b757c9695bd3b | train_002.jsonl | 1487606700 | Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are k different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he wants to know the minimum number of days he should wait before sending a ranger to collect the orbs such that the probability of him getting at least one of each kind of orb is at least , where ε < 10 - 7.To better prepare himself, he wants to know the answer for q different values of pi. Since he is busy designing the battle strategy with Sam, he asks you for your help. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.io.Closeable;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) throws Exception {
Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 29);
thread.start();
thread.join();
}
static class TaskAdapter implements Runnable {
@Override
public void run() {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastInput in = new FastInput(inputStream);
FastOutput out = new FastOutput(outputStream);
DJonAndOrbs solver = new DJonAndOrbs();
solver.solve(1, in, out);
out.close();
}
}
static class DJonAndOrbs {
public void solve(int testNumber, FastInput in, FastOutput out) {
int k = in.readInt();
int q = in.readInt();
int threshold = 10000;
double[][] dp = new double[threshold + 1][k + 1];
dp[0][0] = 1;
for (int i = 0; i < threshold; i++) {
for (int j = 0; j <= k; j++) {
double prob = (double) j / k;
dp[i + 1][j] += prob * dp[i][j];
if (j + 1 <= k) {
dp[i + 1][j + 1] += (1 - prob) * dp[i][j];
}
}
}
for (int i = 0; i < q; i++) {
int p = in.readInt();
double atLeast = p / 2000d;
int ans = 0;
while (dp[ans][k] < atLeast) {
ans++;
}
out.println(ans);
}
}
}
static class FastInput {
private final InputStream is;
private byte[] buf = new byte[1 << 13];
private int bufLen;
private int bufOffset;
private int next;
public FastInput(InputStream is) {
this.is = is;
}
private int read() {
while (bufLen == bufOffset) {
bufOffset = 0;
try {
bufLen = is.read(buf);
} catch (IOException e) {
bufLen = -1;
}
if (bufLen == -1) {
return -1;
}
}
return buf[bufOffset++];
}
public void skipBlank() {
while (next >= 0 && next <= 32) {
next = read();
}
}
public int readInt() {
int sign = 1;
skipBlank();
if (next == '+' || next == '-') {
sign = next == '+' ? 1 : -1;
next = read();
}
int val = 0;
if (sign == 1) {
while (next >= '0' && next <= '9') {
val = val * 10 + next - '0';
next = read();
}
} else {
while (next >= '0' && next <= '9') {
val = val * 10 - next + '0';
next = read();
}
}
return val;
}
}
static class FastOutput implements AutoCloseable, Closeable, Appendable {
private StringBuilder cache = new StringBuilder(10 << 20);
private final Writer os;
public FastOutput append(CharSequence csq) {
cache.append(csq);
return this;
}
public FastOutput append(CharSequence csq, int start, int end) {
cache.append(csq, start, end);
return this;
}
public FastOutput(Writer os) {
this.os = os;
}
public FastOutput(OutputStream os) {
this(new OutputStreamWriter(os));
}
public FastOutput append(char c) {
cache.append(c);
return this;
}
public FastOutput append(int c) {
cache.append(c);
return this;
}
public FastOutput println(int c) {
return append(c).println();
}
public FastOutput println() {
cache.append(System.lineSeparator());
return this;
}
public FastOutput flush() {
try {
os.append(cache);
os.flush();
cache.setLength(0);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return this;
}
public void close() {
flush();
try {
os.close();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public String toString() {
return cache.toString();
}
}
}
| Java | ["1 1\n1", "2 2\n1\n2"] | 2 seconds | ["1", "2\n2"] | null | Java 8 | standard input | [
"dp",
"probabilities",
"math"
] | a2b71d66ea1fdc3249e37be3ab0e67ef | First line consists of two space separated integers k, q (1 ≤ k, q ≤ 1000) — number of different kinds of orbs and number of queries respectively. Each of the next q lines contain a single integer pi (1 ≤ pi ≤ 1000) — i-th query. | 2,200 | Output q lines. On i-th of them output single integer — answer for i-th query. | standard output | |
PASSED | 2d48792b2fdd7bbc56549e88e500c5db | train_002.jsonl | 1487606700 | Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are k different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he wants to know the minimum number of days he should wait before sending a ranger to collect the orbs such that the probability of him getting at least one of each kind of orb is at least , where ε < 10 - 7.To better prepare himself, he wants to know the answer for q different values of pi. Since he is busy designing the battle strategy with Sam, he asks you for your help. | 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.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
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) {
final int maxDay = (int) 2e4;
double[] getAll = new double[maxDay + 1];
int cntTypeOrb = in.readInt();
double[] prevDp = new double[cntTypeOrb + 1];
prevDp[0] = 1;
double[] dp = new double[cntTypeOrb + 1];
for (int d = 1; d <= maxDay; d++) {
for (int ord = 1; ord <= cntTypeOrb; ord++) {
dp[ord] = (double) ord / cntTypeOrb * prevDp[ord] +
(double) (cntTypeOrb - ord + 1) / cntTypeOrb * prevDp[ord - 1];
}
// out.printLine(d, Arrays.toString(dp));
getAll[d] = dp[cntTypeOrb];
System.arraycopy(dp, 0, prevDp, 0, prevDp.length);
Arrays.fill(dp, 0);
}
// out.printLine("all", Arrays.toString(getAll));
int q = in.readInt();
cyc:
for (int iter = 0; iter < q; iter++) {
int p = in.readInt();
for (int d = 0; d < maxDay; d++) {
if (p - 1e-7 <= 2000 * getAll[d]) {
out.printLine(d);
continue cyc;
}
}
out.printLine("no answer");
throw new RuntimeException();
}
}
}
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);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[8192];
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);
}
}
}
| Java | ["1 1\n1", "2 2\n1\n2"] | 2 seconds | ["1", "2\n2"] | null | Java 8 | standard input | [
"dp",
"probabilities",
"math"
] | a2b71d66ea1fdc3249e37be3ab0e67ef | First line consists of two space separated integers k, q (1 ≤ k, q ≤ 1000) — number of different kinds of orbs and number of queries respectively. Each of the next q lines contain a single integer pi (1 ≤ pi ≤ 1000) — i-th query. | 2,200 | Output q lines. On i-th of them output single integer — answer for i-th query. | standard output | |
PASSED | 5755599e6cbe54b93be16eff88f0779b | train_002.jsonl | 1487606700 | Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are k different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he wants to know the minimum number of days he should wait before sending a ranger to collect the orbs such that the probability of him getting at least one of each kind of orb is at least , where ε < 10 - 7.To better prepare himself, he wants to know the answer for q different values of pi. Since he is busy designing the battle strategy with Sam, he asks you for your help. | 256 megabytes | import java.util.*;
public class Ejercicio3{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int k = sc.nextInt();
int q = sc.nextInt();
int[] queries = new int[q];
for(int i=0; i<q; i++){
sc.nextLine();
queries[i]=sc.nextInt();
}
/*int k = 1;
int q = 1;
int[] queries = {1};*/
jonFinder(k, q, queries);
sc.close();
}
public static void jonFinder(int k, int q, int[] queries){
long eps = 1/10000000; // constant stated in the problem
int n = 1004; // number of possible queries that will be precalculated
double[] prob = new double[n]; // where we will keep the probabilities
int[] ans = new int[n];
// we break down the dp[n][x] talked about in the tutorial into just dp[x]
prob[0] = 1; // initialization
for(int i=1, max=1; max<= 1000; i++){
for(int x=k; x>0; x--){ // x the number or distinct orbs at the moment
prob[x] = (x * prob[x] + (k - x + 1) * prob[x-1])/k; // result of factorization of k
}
while(max <= 1000 && 2000*prob[k] >= (max-eps)){ //precalculating full results (adding now variable of days)
ans[max] = i; // max is just the maximum value given in the problem, so we keep record of all probabilities
max++;
}
prob[0] = 0;
}
for(int i=0; i<queries.length; i++){
System.out.println(ans[queries[i]]);
}
// mencionar que sin el tutorial esto no hubiera sido posible
}
} | Java | ["1 1\n1", "2 2\n1\n2"] | 2 seconds | ["1", "2\n2"] | null | Java 8 | standard input | [
"dp",
"probabilities",
"math"
] | a2b71d66ea1fdc3249e37be3ab0e67ef | First line consists of two space separated integers k, q (1 ≤ k, q ≤ 1000) — number of different kinds of orbs and number of queries respectively. Each of the next q lines contain a single integer pi (1 ≤ pi ≤ 1000) — i-th query. | 2,200 | Output q lines. On i-th of them output single integer — answer for i-th query. | standard output | |
PASSED | 9583ed5c75acbe9818b1fc6bd04e764c | train_002.jsonl | 1487606700 | Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are k different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he wants to know the minimum number of days he should wait before sending a ranger to collect the orbs such that the probability of him getting at least one of each kind of orb is at least , where ε < 10 - 7.To better prepare himself, he wants to know the answer for q different values of pi. Since he is busy designing the battle strategy with Sam, he asks you for your help. | 256 megabytes | import java.io.*;
import java.util.*;
public class D {
BufferedReader in;
StringTokenizer st;
PrintWriter out;
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(in.readLine());
return st.nextToken();
}
int nextInt() throws Exception {
return Integer.parseInt(next());
}
long nextLong() throws Exception {
return Long.parseLong(next());
}
double nextDouble() throws Exception {
return Double.parseDouble(next());
}
void solve() throws Exception {
int k = nextInt();
int maxans = 8888;
double[][] p = new double[k + 22][maxans + 4];
p[1][1] = 1;
p[0][1] = 0;
for (int cd = 0; cd < maxans; cd++) {
for (int i = 1; i <= k; i++) {
double cp = p[i][cd];
p[i + 1][cd + 1] += 1.0 * p[i][cd] * (k - i) / k;
p[i][cd + 1] += 1.0 * p[i][cd] * i / k;
}
}
int n = nextInt();
int a[] = new int[n];
for (int i = 0; i < n; i++) {
int c = nextInt();
double pr = c * 1.0 / 2000;
for (int ans = 0; ans < maxans; ans++)
if (p[k][ans] - 1e-9 > pr) {
out.println(ans);
ans = Integer.MAX_VALUE / 2;
}
}
}
void run() {
try {
Locale.setDefault(Locale.US);
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
solve();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
public static void main(String[] args) {
new D().run();
}
}
| Java | ["1 1\n1", "2 2\n1\n2"] | 2 seconds | ["1", "2\n2"] | null | Java 8 | standard input | [
"dp",
"probabilities",
"math"
] | a2b71d66ea1fdc3249e37be3ab0e67ef | First line consists of two space separated integers k, q (1 ≤ k, q ≤ 1000) — number of different kinds of orbs and number of queries respectively. Each of the next q lines contain a single integer pi (1 ≤ pi ≤ 1000) — i-th query. | 2,200 | Output q lines. On i-th of them output single integer — answer for i-th query. | standard output | |
PASSED | 1dc8e2f650587c2b5fb9022121497b9c | train_002.jsonl | 1487606700 | Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are k different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he wants to know the minimum number of days he should wait before sending a ranger to collect the orbs such that the probability of him getting at least one of each kind of orb is at least , where ε < 10 - 7.To better prepare himself, he wants to know the answer for q different values of pi. Since he is busy designing the battle strategy with Sam, he asks you for your help. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
/**
* @author Don Li
*/
public class JonOrbs {
int N = 1005;
double eps = 1e-7;
void solve() {
int k = in.nextInt(), q = in.nextInt();
int[] res = new int[N];
double[] dp = new double[k + 1];
dp[0] = 1;
for (int i = 0, d = 1; d < N; i++) {
for (int j = k; j > 0; j--) {
dp[j] = dp[j] * j / k + dp[j - 1] * (k - (j - 1)) / k;
}
dp[0] = 0;
while (d < N && 2000 * dp[k] >= d - eps) {
res[d] = i + 1;
d++;
}
}
while (q-- > 0) {
out.println(res[in.nextInt()]);
}
}
public static void main(String[] args) {
in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(System.out);
new JonOrbs().solve();
out.close();
}
static FastScanner in;
static PrintWriter out;
static class FastScanner {
BufferedReader in;
StringTokenizer st;
public FastScanner(BufferedReader in) {
this.in = in;
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
public double nextDouble() {
return Double.parseDouble(nextToken());
}
}
}
| Java | ["1 1\n1", "2 2\n1\n2"] | 2 seconds | ["1", "2\n2"] | null | Java 8 | standard input | [
"dp",
"probabilities",
"math"
] | a2b71d66ea1fdc3249e37be3ab0e67ef | First line consists of two space separated integers k, q (1 ≤ k, q ≤ 1000) — number of different kinds of orbs and number of queries respectively. Each of the next q lines contain a single integer pi (1 ≤ pi ≤ 1000) — i-th query. | 2,200 | Output q lines. On i-th of them output single integer — answer for i-th query. | standard output | |
PASSED | c69d737bc9d4a5fad0636b1d6b249565 | train_002.jsonl | 1487606700 | Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are k different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he wants to know the minimum number of days he should wait before sending a ranger to collect the orbs such that the probability of him getting at least one of each kind of orb is at least , where ε < 10 - 7.To better prepare himself, he wants to know the answer for q different values of pi. Since he is busy designing the battle strategy with Sam, he asks you for your help. | 256 megabytes | import java.io.*;
import java.util.*;
public final class TaskD
{
public static void main(String[] args)
{
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
Solver solver = new Solver(in, out);
solver.solve();
in.close();
out.flush();
out.close();
}
static class Solver
{
int k, q;
double[][] dp;
InputReader in;
PrintWriter out;
void solve()
{
k = in.nextInt();
q = in.nextInt();
dp = new double[k + 1][10005];
dp[0][0] = 1;
for (int i = 1; i <= k; i++)
for (int j = i; j <= 10000; j++)
dp[i][j] = dp[i - 1][j - 1] * (k - i + 1.0) / k + dp[i][j - 1] * i / k;
while (q-- > 0)
{
double p = in.nextInt() / 2000.0;
for (int i = 0; i <= 10000; i++)
{
if (dp[k][i] >= p)
{
out.println(i);
break;
}
}
}
}
public Solver(InputReader in, PrintWriter out)
{
this.in = in;
this.out = out;
}
}
static class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c & 15;
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c)
{
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public void close()
{
try
{
stream.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}
| Java | ["1 1\n1", "2 2\n1\n2"] | 2 seconds | ["1", "2\n2"] | null | Java 8 | standard input | [
"dp",
"probabilities",
"math"
] | a2b71d66ea1fdc3249e37be3ab0e67ef | First line consists of two space separated integers k, q (1 ≤ k, q ≤ 1000) — number of different kinds of orbs and number of queries respectively. Each of the next q lines contain a single integer pi (1 ≤ pi ≤ 1000) — i-th query. | 2,200 | Output q lines. On i-th of them output single integer — answer for i-th query. | standard output | |
PASSED | 5ed2f4e27105adc0b0e06fc49c2701b0 | train_002.jsonl | 1487606700 | Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are k different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he wants to know the minimum number of days he should wait before sending a ranger to collect the orbs such that the probability of him getting at least one of each kind of orb is at least , where ε < 10 - 7.To better prepare himself, he wants to know the answer for q different values of pi. Since he is busy designing the battle strategy with Sam, he asks you for your help. | 256 megabytes | import java.io.*;
import java.util.*;
public final class TaskD
{
public static void main(String[] args)
{
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
Solver solver = new Solver(in, out);
solver.solve();
in.close();
out.flush();
out.close();
}
static class Solver
{
int k, q;
double[][] dp;
InputReader in;
PrintWriter out;
void solve()
{
k = in.nextInt();
q = in.nextInt();
dp = new double[k + 1][8005];
dp[0][0] = 1;
for (int i = 1; i <= k; i++)
for (int j = i; j <= 8000; j++)
dp[i][j] = dp[i - 1][j - 1] * (k - i + 1.0) / k + dp[i][j - 1] * i / k;
while (q-- > 0)
{
double p = in.nextInt() / 2000.0;
for (int i = 0; i <= 8000; i++)
{
if (dp[k][i] >= p)
{
out.println(i);
break;
}
}
}
}
public Solver(InputReader in, PrintWriter out)
{
this.in = in;
this.out = out;
}
}
static class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c & 15;
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c)
{
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public void close()
{
try
{
stream.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}
| Java | ["1 1\n1", "2 2\n1\n2"] | 2 seconds | ["1", "2\n2"] | null | Java 8 | standard input | [
"dp",
"probabilities",
"math"
] | a2b71d66ea1fdc3249e37be3ab0e67ef | First line consists of two space separated integers k, q (1 ≤ k, q ≤ 1000) — number of different kinds of orbs and number of queries respectively. Each of the next q lines contain a single integer pi (1 ≤ pi ≤ 1000) — i-th query. | 2,200 | Output q lines. On i-th of them output single integer — answer for i-th query. | standard output | |
PASSED | 0fa4c3cdef890fea42af087a8671a15e | train_002.jsonl | 1487606700 | Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are k different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he wants to know the minimum number of days he should wait before sending a ranger to collect the orbs such that the probability of him getting at least one of each kind of orb is at least , where ε < 10 - 7.To better prepare himself, he wants to know the answer for q different values of pi. Since he is busy designing the battle strategy with Sam, he asks you for your help. | 256 megabytes | import java.io.*;
import java.util.*;
public final class TaskD
{
public static void main(String[] args)
{
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
Solver solver = new Solver(in, out);
solver.solve();
in.close();
out.flush();
out.close();
}
static class Solver
{
int k, q;
double[][] dp;
int x;
InputReader in;
PrintWriter out;
void solve()
{
k = in.nextInt();
q = in.nextInt();
dp = new double[k + 1][10005];
dp[0][0] = 1;
for (int i = 1; i <= k; i++)
for (int j = i; j <= 10000; j++)
dp[i][j] = dp[i - 1][j - 1] * (k - i + 1.0) / k + dp[i][j - 1] * i / k;
while (q-- > 0)
{
double p = in.nextInt() / 2000.0;
for (int i = 0; i <= 10000; i++)
{
if (dp[k][i] > p)
{
out.println(i);
break;
}
}
}
}
public Solver(InputReader in, PrintWriter out)
{
this.in = in;
this.out = out;
}
}
static class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c & 15;
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c)
{
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public void close()
{
try
{
stream.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}
| Java | ["1 1\n1", "2 2\n1\n2"] | 2 seconds | ["1", "2\n2"] | null | Java 8 | standard input | [
"dp",
"probabilities",
"math"
] | a2b71d66ea1fdc3249e37be3ab0e67ef | First line consists of two space separated integers k, q (1 ≤ k, q ≤ 1000) — number of different kinds of orbs and number of queries respectively. Each of the next q lines contain a single integer pi (1 ≤ pi ≤ 1000) — i-th query. | 2,200 | Output q lines. On i-th of them output single integer — answer for i-th query. | standard output | |
PASSED | 67a3153cd26699668e24defa058c86f3 | train_002.jsonl | 1487606700 | Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are k different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he wants to know the minimum number of days he should wait before sending a ranger to collect the orbs such that the probability of him getting at least one of each kind of orb is at least , where ε < 10 - 7.To better prepare himself, he wants to know the answer for q different values of pi. Since he is busy designing the battle strategy with Sam, he asks you for your help. | 256 megabytes | import java.io.*;
import java.util.*;
public final class TaskD
{
public static void main(String[] args)
{
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
Solver solver = new Solver(in, out);
solver.solve();
in.close();
out.flush();
out.close();
}
static class Solver
{
int k, q;
double[][] dp;
InputReader in;
PrintWriter out;
void solve()
{
k = in.nextInt();
q = in.nextInt();
dp = new double[k + 1][10005];
dp[0][0] = 1;
for (int i = 1; i <= k; i++)
for (int j = i; j <= 10000; j++)
dp[i][j] = dp[i - 1][j - 1] * (k - i + 1.0) / k + dp[i][j - 1] * i / k;
while (q-- > 0)
{
double p = in.nextInt() / 2000.0;
for (int i = 0; i <= 10000; i++)
{
if (dp[k][i] > p)
{
out.println(i);
break;
}
}
}
}
public Solver(InputReader in, PrintWriter out)
{
this.in = in;
this.out = out;
}
}
static class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c & 15;
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c)
{
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public void close()
{
try
{
stream.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}
| Java | ["1 1\n1", "2 2\n1\n2"] | 2 seconds | ["1", "2\n2"] | null | Java 8 | standard input | [
"dp",
"probabilities",
"math"
] | a2b71d66ea1fdc3249e37be3ab0e67ef | First line consists of two space separated integers k, q (1 ≤ k, q ≤ 1000) — number of different kinds of orbs and number of queries respectively. Each of the next q lines contain a single integer pi (1 ≤ pi ≤ 1000) — i-th query. | 2,200 | Output q lines. On i-th of them output single integer — answer for i-th query. | standard output | |
PASSED | f3f5a538608179df00faf51c28112c42 | train_002.jsonl | 1487606700 | Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are k different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he wants to know the minimum number of days he should wait before sending a ranger to collect the orbs such that the probability of him getting at least one of each kind of orb is at least , where ε < 10 - 7.To better prepare himself, he wants to know the answer for q different values of pi. Since he is busy designing the battle strategy with Sam, he asks you for your help. | 256 megabytes | import java.util.*;
import java.io.*;
/**
*
* @author umang
*/
public class ProblemD {
public static int mod = (int) (1e9+7);
public static int mod1 = (int) (1e9+6);
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
int k=in.nextInt();
int t=in.nextInt();
int n=8000;
double[][] dp=new double[n][k+1];
dp[0][0]=1;
for(int i=1;i<n;i++){
for(int j=1;j<=k;j++){
dp[i][j]=(j*dp[i-1][j])/(k*1.0)+((k-(j-1))*dp[i-1][j-1])/(k*1.0);
}
}
double e=1e-7;
while(t-->0){
int p=in.nextInt();
double pi=(p-e)/2000.0;
for(int i=1;i<n;i++){
if(dp[i][k]>=pi){
out.println(i);
break;
}
}
}
out.close();
}
public static void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
static class Pair{
int p;
int q;
public Pair(int p,int q){
this.p=p;
this.q=q;
}
}
static class Compare implements Comparator{
@Override
public int compare(Object t, Object t1) {
Pair p1 = (Pair)t;
Pair p2 = (Pair)t1;
if(p1.q<p2.q) return -1;
else if(p1.q>p2.q) return 1;
else return 0;
}
}
public static boolean isPal(String s){
for(int i=0, j=s.length()-1;i<=j;i++,j--){
if(s.charAt(i)!=s.charAt(j)) return false;
}
return true;
}
public static String rev(String s){
StringBuilder sb=new StringBuilder(s);
sb.reverse();
return sb.toString();
}
public static long gcd(long x,long y){
if(x%y==0)
return y;
else
return gcd(y,x%y);
}
public static int gcd(int x,int y){
if(x%y==0)
return y;
else
return gcd(y,x%y);
}
public static long gcdExtended(long a,long b,long[] x){
if(a==0){
x[0]=0;
x[1]=1;
return b;
}
long[] y=new long[2];
long gcd=gcdExtended(b%a, a, y);
x[0]=y[1]-(b/a)*y[0];
x[1]=y[0];
return gcd;
}
public static int abs(int a,int b){
return (int)Math.abs(a-b);
}
public static long abs(long a,long b){
return (long)Math.abs(a-b);
}
public static int max(int a,int b){
if(a>b)
return a;
else
return b;
}
public static int min(int a,int b){
if(a>b)
return b;
else
return a;
}
public static long max(long a,long b){
if(a>b)
return a;
else
return b;
}
public static long min(long a,long b){
if(a>b)
return b;
else
return a;
}
public static long pow(long n,long p,long m){
long result = 1;
if(p==0)
return 1;
if (p==1)
return n;
while(p!=0)
{
if(p%2==1)
result *= n;
if(result>=m)
result%=m;
p >>=1;
n*=n;
if(n>=m)
n%=m;
}
return result;
}
public static long pow(long n,long p){
long result = 1;
if(p==0)
return 1;
if (p==1)
return n;
while(p!=0)
{
if(p%2==1)
result *= n;
p >>=1;
n*=n;
}
return result;
}
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 long[] nextLongArray(int n) {
long a[] = new long[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);
}
}
} | Java | ["1 1\n1", "2 2\n1\n2"] | 2 seconds | ["1", "2\n2"] | null | Java 8 | standard input | [
"dp",
"probabilities",
"math"
] | a2b71d66ea1fdc3249e37be3ab0e67ef | First line consists of two space separated integers k, q (1 ≤ k, q ≤ 1000) — number of different kinds of orbs and number of queries respectively. Each of the next q lines contain a single integer pi (1 ≤ pi ≤ 1000) — i-th query. | 2,200 | Output q lines. On i-th of them output single integer — answer for i-th query. | standard output | |
PASSED | d1368d226ba7bb35133e390166dc6cb7 | train_002.jsonl | 1487606700 | Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are k different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he wants to know the minimum number of days he should wait before sending a ranger to collect the orbs such that the probability of him getting at least one of each kind of orb is at least , where ε < 10 - 7.To better prepare himself, he wants to know the answer for q different values of pi. Since he is busy designing the battle strategy with Sam, he asks you for your help. | 256 megabytes | import java.util.*;
public class jonOrbs{
public static void main(String [] args){
Scanner sc = new Scanner(System.in);
int k = sc.nextInt();
int q = sc.nextInt();
int[] p = new int[q];
long eps = 1/10000000;
int n = 1004;
for (int i = 0;i < q ;i++ ) {
p[i] = sc.nextInt();
}
double[] prob = new double[n];
int[] ans = new int[n];
prob[0] = 1;
for (int i = 1,m = 1;m<=1000 ;i++ ) {
for (int j = k;j>0 ;j-- ) {
prob[j] = (j * prob[j] + (k-j+1) * prob[j-1])/k;
}
while(m<= 1000 && 2000*prob[k] >= (m-eps)){
ans[m] = i;
m++;
}
prob[0] = 0;
}
for (int i = 0;i < p.length ;i++ ) {
System.out.println(ans[p[i]]);
}
}
} | Java | ["1 1\n1", "2 2\n1\n2"] | 2 seconds | ["1", "2\n2"] | null | Java 8 | standard input | [
"dp",
"probabilities",
"math"
] | a2b71d66ea1fdc3249e37be3ab0e67ef | First line consists of two space separated integers k, q (1 ≤ k, q ≤ 1000) — number of different kinds of orbs and number of queries respectively. Each of the next q lines contain a single integer pi (1 ≤ pi ≤ 1000) — i-th query. | 2,200 | Output q lines. On i-th of them output single integer — answer for i-th query. | standard output | |
PASSED | b74e8b8943cd5f16ae608a8736ed8ab8 | train_002.jsonl | 1487606700 | Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are k different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he wants to know the minimum number of days he should wait before sending a ranger to collect the orbs such that the probability of him getting at least one of each kind of orb is at least , where ε < 10 - 7.To better prepare himself, he wants to know the answer for q different values of pi. Since he is busy designing the battle strategy with Sam, he asks you for your help. | 256 megabytes | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class D {
static StringTokenizer st;
static BufferedReader br;
static PrintWriter pw;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int k = nextInt();
int q = nextInt();
double[][]dp = new double[8001][k+1];
dp[0][0] = 1;
for (int i = 1; i <= 8000; i++) {
for (int j = 0; j <= k; j++) {
dp[i][j] = dp[i-1][j] * j / k;
if (j > 0)
dp[i][j] += dp[i-1][j-1] * (k-j+1) / k;
}
}
while (q-->0) {
int p = nextInt();
for (int i = 0; i <= 8000; i++) {
if (dp[i][k] >= p / 2000.) {
pw.println(i);
break;
}
}
}
pw.close();
}
private static int nextInt() throws IOException {
return Integer.parseInt(next());
}
private static long nextLong() throws IOException {
return Long.parseLong(next());
}
private static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
private static String next() throws IOException {
while (st==null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
} | Java | ["1 1\n1", "2 2\n1\n2"] | 2 seconds | ["1", "2\n2"] | null | Java 8 | standard input | [
"dp",
"probabilities",
"math"
] | a2b71d66ea1fdc3249e37be3ab0e67ef | First line consists of two space separated integers k, q (1 ≤ k, q ≤ 1000) — number of different kinds of orbs and number of queries respectively. Each of the next q lines contain a single integer pi (1 ≤ pi ≤ 1000) — i-th query. | 2,200 | Output q lines. On i-th of them output single integer — answer for i-th query. | standard output | |
PASSED | 340e8dbad0173b59750e6b4e50bc5d6a | train_002.jsonl | 1487606700 | Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are k different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he wants to know the minimum number of days he should wait before sending a ranger to collect the orbs such that the probability of him getting at least one of each kind of orb is at least , where ε < 10 - 7.To better prepare himself, he wants to know the answer for q different values of pi. Since he is busy designing the battle strategy with Sam, he asks you for your help. | 256 megabytes | //import java.util.Scanner;
//
//
//public class JonandOrbs {
//
// public static void main(String[] args) {
// Scanner in = new Scanner(System.in);
// int n = in.nextInt(), q = in.nextInt();
// double t1[] = new double[n+1], t2[] = new double[n+1];
// double probs[] = new double[100000];
// t1[0] = 1;
// for(int i = 0; i < 30; i++) {
// for(int j = 0; j <= n; j++) {
// t2[j] += t1[j] * ((double)(n - j)/(double)n);
// if(j != 0) {
// t1[j-1] += t2[j] * ((double)j/ (double)n);
// }
// }
// double[i+1]
// }
//
// for(int i = 0; i < q; i++) {
// double qq = (in.nextDouble() - (1e-7))/2000.0;
// int idx = 0;
// while(memo[idx][0] < qq) {
// idx++;
// }
// System.out.println(idx);
// }
// }
//}
import java.util.Scanner;
public class JonandOrbs {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt(), q = in.nextInt();
double memo[][] = new double[10000][n+1];
memo[0][n] = 1;
for(int i = 0; i < 10000-1; i++) {
for(int j = 0; j <= n; j++) {
memo[i+1][j] += memo[i][j] * ((double)(n - j)/(double)n);
if(j != 0) {
memo[i+1][j-1] += memo[i][j] * ((double)j/ (double)n);
}
}
}
for(int i = 0; i < q; i++) {
double qq = (in.nextDouble() - (1e-7))/2000.0;
int idx = 0;
while(memo[idx][0] < qq) {
idx++;
}
System.out.println(idx);
}
}
} | Java | ["1 1\n1", "2 2\n1\n2"] | 2 seconds | ["1", "2\n2"] | null | Java 8 | standard input | [
"dp",
"probabilities",
"math"
] | a2b71d66ea1fdc3249e37be3ab0e67ef | First line consists of two space separated integers k, q (1 ≤ k, q ≤ 1000) — number of different kinds of orbs and number of queries respectively. Each of the next q lines contain a single integer pi (1 ≤ pi ≤ 1000) — i-th query. | 2,200 | Output q lines. On i-th of them output single integer — answer for i-th query. | standard output | |
PASSED | 4fcadc5bd68e09d45bbe1f177ee8ea95 | train_002.jsonl | 1302879600 | In one very large and very respectable company there is a cloakroom with a coat hanger. It is represented by n hooks, positioned in a row. The hooks are numbered with positive integers from 1 to n from the left to the right.The company workers have a very complicated work schedule. At the beginning of a work day all the employees are not there and the coat hanger in the cloakroom is empty. At some moments of time the employees arrive and some of them leave.When some employee arrives, he hangs his cloak on one of the available hooks. To be of as little discomfort to his colleagues as possible, the hook where the coat will hang, is chosen like this. First the employee chooses the longest segment among available hooks following in a row. If there are several of such segments, then he chooses the one closest to the right. After that the coat is hung on the hook located in the middle of this segment. If the segment has an even number of hooks, then among two central hooks we choose the one closest to the right.When an employee leaves, he takes his coat. As all the company workers deeply respect each other, no one takes somebody else's coat.From time to time the director of this respectable company gets bored and he sends his secretary to see how many coats hang on the coat hanger from the i-th to the j-th hook inclusive. And this whim is always to be fulfilled, otherwise the director gets angry and has a mental breakdown.Not to spend too much time traversing from the director's office to the cloakroom and back again, the secretary asked you to write a program, emulating the company cloakroom's work. | 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.Random;
import java.util.TreeSet;
import java.io.BufferedOutputStream;
import java.util.StringTokenizer;
import java.util.Map;
import java.util.NoSuchElementException;
import java.io.PrintWriter;
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Writer;
import java.util.Map.Entry;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author An Almost Retired Guy
*/
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 {
TreeSet<Segment> segs;
EzIntIntHashMap pos;
HashMap<Integer, Segment> begin;
HashMap<Integer, Segment> end;
TreapBST treap;
TreapBST.Treap root;
void remove(int x) {
int p = pos.remove(x);
root = TreapBST.remove(root, p);
int l = p, r = p;
Segment s;
if (end.containsKey(p - 1)) {
s = end.remove(p - 1);
l = s.left;
segs.remove(s);
}
if (begin.containsKey(p + 1)) {
s = begin.remove(p + 1);
r = s.right;
segs.remove(s);
}
s = new Segment(l, r);
segs.add(s);
begin.put(l, s);
end.put(r, s);
}
void add(int x) {
Segment seg = segs.pollLast(), s;
begin.remove(seg.left);
end.remove(seg.right);
int p = (seg.left + seg.right + 1) / 2;
if (p > seg.left) {
s = new Segment(seg.left, p - 1);
segs.add(s);
begin.put(s.left, s);
end.put(s.right, s);
}
if (p < seg.right) {
s = new Segment(p + 1, seg.right);
segs.add(s);
begin.put(s.left, s);
end.put(s.right, s);
}
pos.put(x, p);
root = TreapBST.insert(root, p);
}
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt(), q = in.nextInt();
segs = new TreeSet<>();
Segment s = new Segment(1, n);
segs.add(s);
pos = new EzIntIntHashMap();
begin = new HashMap<>();
begin.put(1, s);
end = new HashMap<>();
end.put(n, s);
treap = new TreapBST();
for (int i = 0; i < q; i++) {
int x = in.nextInt();
if (x == 0) {
int l = in.nextInt(), r = in.nextInt();
TreapBST.Treap L, M, R;
TreapBST.TreapPair pair = TreapBST.split(root, l);
L = pair.first;
M = pair.second;
pair = TreapBST.split(M, r + 1);
M = pair.first;
R = pair.second;
int ans = TreapBST.getSize(M);
root = TreapBST.merge(TreapBST.merge(L, M), R);
out.println(ans);
} else if (!pos.containsKey(x)) add(x);
else remove(x);
}
}
class Segment implements Comparable<Segment> {
int left;
int right;
Segment(int left, int right) {
this.left = left;
this.right = right;
}
public int compareTo(Segment that) {
if (this.right - this.left != that.right - that.left)
return Integer.compare(this.right - this.left, that.right - that.left);
return Integer.compare(this.left, that.left);
}
}
}
static interface EzIntIntMap {
int size();
EzIntIntMapIterator iterator();
boolean equals(Object object);
int hashCode();
String toString();
}
static class TreapBST {
static Random random = new Random();
public static int getSize(TreapBST.Treap root) {
return root == null ? 0 : root.size;
}
public static TreapBST.TreapPair split(TreapBST.Treap root, int minRight) {
if (root == null)
return new TreapBST.TreapPair(null, null);
if (root.key >= minRight) {
TreapBST.TreapPair leftSplit = split(root.left, minRight);
root.left = leftSplit.second;
root.update();
leftSplit.second = root;
return leftSplit;
} else {
TreapBST.TreapPair rightSplit = split(root.right, minRight);
root.right = rightSplit.first;
root.update();
rightSplit.first = root;
return rightSplit;
}
}
public static TreapBST.Treap merge(TreapBST.Treap left, TreapBST.Treap right) {
if (left == null)
return right;
if (right == null)
return left;
// if (random.nextInt(left.size + right.size) < left.size) {
if (left.prio > right.prio) {
left.right = merge(left.right, right);
left.update();
return left;
} else {
right.left = merge(left, right.left);
right.update();
return right;
}
}
public static TreapBST.Treap insert(TreapBST.Treap root, int key) {
TreapBST.TreapPair t = split(root, key);
return merge(merge(t.first, new TreapBST.Treap(key)), t.second);
}
public static TreapBST.Treap remove(TreapBST.Treap root, int key) {
TreapBST.TreapPair t = split(root, key);
return merge(t.first, split(t.second, key + 1).second);
}
public static class Treap {
int key;
long prio;
TreapBST.Treap left;
TreapBST.Treap right;
int size;
Treap(int key) {
this.key = key;
prio = random.nextLong();
size = 1;
}
void update() {
size = 1 + getSize(left) + getSize(right);
}
}
public static class TreapPair {
public TreapBST.Treap first;
public TreapBST.Treap second;
TreapPair(TreapBST.Treap left, TreapBST.Treap right) {
this.first = left;
this.second = right;
}
}
}
static class OutputWriter extends PrintWriter {
public OutputWriter(OutputStream outputStream) {
super(new BufferedOutputStream(outputStream));
}
public OutputWriter(Writer writer) {
super(writer);
}
public void close() {
super.close();
}
}
static class InputReader {
BufferedReader br;
StringTokenizer st;
public InputReader(InputStream inputStream) {
br = new BufferedReader(new InputStreamReader(inputStream));
}
public String next() {
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(nextLine());
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public String nextLine() {
try {
return br.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
static class EzIntIntHashMap implements EzIntIntMap {
private static final int DEFAULT_CAPACITY = 8;
private static final int REBUILD_LENGTH_THRESHOLD = 32;
private static final int HASHCODE_INITIAL_VALUE = 0x811c9dc5;
private static final int HASHCODE_MULTIPLIER = 0x01000193;
private static final byte FREE = 0;
private static final byte REMOVED = 1;
private static final byte FILLED = 2;
private static final int DEFAULT_NULL_VALUE = (new int[1])[0];
private static final Random rnd = new Random();
private static final int POS_RANDOM_SHIFT_1;
private static final int POS_RANDOM_SHIFT_2;
private static final int STEP_RANDOM_SHIFT_1;
private static final int STEP_RANDOM_SHIFT_2;
private int[] keys;
private int[] values;
private byte[] status;
private int size;
private int removedCount;
private int mask;
private boolean returnedNull;
private final int hashSeed;
static {
POS_RANDOM_SHIFT_1 = rnd.nextInt(10) + 11;
POS_RANDOM_SHIFT_2 = rnd.nextInt(10) + 21;
STEP_RANDOM_SHIFT_1 = rnd.nextInt(10) + 11;
STEP_RANDOM_SHIFT_2 = rnd.nextInt(10) + 21;
}
public EzIntIntHashMap() {
this(DEFAULT_CAPACITY);
}
public EzIntIntHashMap(int capacity) {
if (capacity < 0) {
throw new IllegalArgumentException("Capacity must be non-negative");
}
// Actually we need 4x more memory
int length = 4 * Math.max(1, capacity);
if ((length & (length - 1)) != 0) {
length = Integer.highestOneBit(length) << 1;
}
// Length is a power of 2 now
initEmptyTable(length);
returnedNull = false;
hashSeed = rnd.nextInt();
}
public EzIntIntHashMap(EzIntIntMap map) {
this(map.size());
for (EzIntIntMapIterator it = map.iterator(); it.hasNext(); it.next()) {
put(it.getKey(), it.getValue());
}
}
public EzIntIntHashMap(Map<Integer, Integer> javaMap) {
this(javaMap.size());
for (Map.Entry<Integer, Integer> e : javaMap.entrySet()) {
put(e.getKey(), e.getValue());
}
}
private int getStartPos(int h) {
h ^= hashSeed;
h ^= (h >>> POS_RANDOM_SHIFT_1) ^ (h >>> POS_RANDOM_SHIFT_2);
return h & mask;
}
private int getStep(int h) {
h ^= hashSeed;
h ^= (h >>> STEP_RANDOM_SHIFT_1) ^ (h >>> STEP_RANDOM_SHIFT_2);
return ((h << 1) | 1) & mask;
}
public int size() {
return size;
}
public boolean containsKey(int key) {
final int keyHash = PrimitiveHashCalculator.getHash(key);
int pos = getStartPos(keyHash);
final int step = getStep(keyHash);
for (; status[pos] != FREE; pos = (pos + step) & mask) {
if (status[pos] == FILLED && keys[pos] == key) {
return true;
}
}
return false;
}
public int get(int key) {
final int keyHash = PrimitiveHashCalculator.getHash(key);
int pos = getStartPos(keyHash);
final int step = getStep(keyHash);
for (; status[pos] != FREE; pos = (pos + step) & mask) {
if (status[pos] == FILLED && keys[pos] == key) {
returnedNull = false;
return values[pos];
}
}
returnedNull = true;
return DEFAULT_NULL_VALUE;
}
public int put(int key, int value) {
final int keyHash = PrimitiveHashCalculator.getHash(key);
int pos = getStartPos(keyHash);
final int step = getStep(keyHash);
for (; status[pos] == FILLED; pos = (pos + step) & mask) {
if (keys[pos] == key) {
final int oldValue = values[pos];
values[pos] = value;
returnedNull = false;
return oldValue;
}
}
if (status[pos] == FREE) {
status[pos] = FILLED;
keys[pos] = key;
values[pos] = value;
size++;
if ((size + removedCount) * 2 > keys.length) {
rebuild(keys.length * 2); // enlarge the table
}
returnedNull = true;
return DEFAULT_NULL_VALUE;
}
final int removedPos = pos;
for (pos = (pos + step) & mask; status[pos] != FREE; pos = (pos + step) & mask) {
if (status[pos] == FILLED && keys[pos] == key) {
final int oldValue = values[pos];
values[pos] = value;
returnedNull = false;
return oldValue;
}
}
status[removedPos] = FILLED;
keys[removedPos] = key;
values[removedPos] = value;
size++;
removedCount--;
returnedNull = true;
return DEFAULT_NULL_VALUE;
}
public int remove(int key) {
final int keyHash = PrimitiveHashCalculator.getHash(key);
int pos = getStartPos(keyHash);
final int step = getStep(keyHash);
for (; status[pos] != FREE; pos = (pos + step) & mask) {
if (status[pos] == FILLED && keys[pos] == key) {
final int removedValue = values[pos];
status[pos] = REMOVED;
size--;
removedCount++;
if (keys.length > REBUILD_LENGTH_THRESHOLD) {
if (8 * size <= keys.length) {
rebuild(keys.length / 2); // compress the table
} else if (size < removedCount) {
rebuild(keys.length); // just rebuild the table
}
}
returnedNull = false;
return removedValue;
}
}
returnedNull = true;
return DEFAULT_NULL_VALUE;
}
public EzIntIntMapIterator iterator() {
return new EzIntIntHashMapIterator();
}
private void rebuild(int newLength) {
int[] oldKeys = keys;
int[] oldValues = values;
byte[] oldStatus = status;
initEmptyTable(newLength);
for (int i = 0; i < oldKeys.length; i++) {
if (oldStatus[i] == FILLED) {
put(oldKeys[i], oldValues[i]);
}
}
}
private void initEmptyTable(int length) {
keys = new int[length];
values = new int[length];
status = new byte[length];
size = 0;
removedCount = 0;
mask = length - 1;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
EzIntIntHashMap that = (EzIntIntHashMap) o;
if (size != that.size) {
return false;
}
for (int i = 0; i < keys.length; i++) {
if (status[i] == FILLED) {
int thatValue = that.get(keys[i]);
if (that.returnedNull || thatValue != values[i]) {
return false;
}
}
}
return true;
}
private void randomShuffle(int[] array) {
int n = array.length;
for (int i = 0; i < n; i++) {
int j = i + rnd.nextInt(n - i);
int tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
}
public int hashCode() {
int[] entryHashes = new int[size];
for (int i = 0, j = 0; i < status.length; i++) {
if (status[i] == FILLED) {
int hash = HASHCODE_INITIAL_VALUE;
hash = (hash ^ PrimitiveHashCalculator.getHash(keys[i])) * HASHCODE_MULTIPLIER;
hash = (hash ^ PrimitiveHashCalculator.getHash(values[i])) * HASHCODE_MULTIPLIER;
entryHashes[j++] = hash;
}
}
randomShuffle(entryHashes);
Arrays.sort(entryHashes);
int hash = HASHCODE_INITIAL_VALUE;
for (int i = 0; i < size; i++) {
hash = (hash ^ entryHashes[i]) * HASHCODE_MULTIPLIER;
}
return hash;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append('{');
for (int i = 0; i < keys.length; i++) {
if (status[i] == FILLED) {
if (sb.length() > 1) {
sb.append(", ");
}
sb.append(keys[i]);
sb.append('=');
sb.append(values[i]);
}
}
sb.append('}');
return sb.toString();
}
private class EzIntIntHashMapIterator implements EzIntIntMapIterator {
private int curIndex;
private EzIntIntHashMapIterator() {
curIndex = 0;
while (curIndex < status.length && status[curIndex] != FILLED) {
curIndex++;
}
}
public boolean hasNext() {
return curIndex < status.length;
}
public int getKey() {
if (curIndex == keys.length) {
throw new NoSuchElementException("Iterator doesn't have more entries");
}
return keys[curIndex];
}
public int getValue() {
if (curIndex == values.length) {
throw new NoSuchElementException("Iterator doesn't have more entries");
}
return values[curIndex];
}
public void next() {
if (curIndex == status.length) {
return;
}
curIndex++;
while (curIndex < status.length && status[curIndex] != FILLED) {
curIndex++;
}
}
}
}
static final class PrimitiveHashCalculator {
private PrimitiveHashCalculator() {
}
public static int getHash(int x) {
return x;
}
}
static interface EzIntIntMapIterator {
boolean hasNext();
int getKey();
int getValue();
void next();
}
}
| Java | ["9 11\n1\n2\n0 5 8\n1\n1\n3\n0 3 8\n9\n0 6 9\n6\n0 1 9"] | 4 seconds | ["2\n3\n2\n5"] | null | Java 8 | standard input | [
"data structures"
] | 1250f103aa5fd1ac300a8a71b816b3e4 | The first line contains two integers n, q (1 ≤ n ≤ 109, 1 ≤ q ≤ 105), which are the number of hooks on the hanger and the number of requests correspondingly. Then follow q lines with requests, sorted according to time. The request of the type "0 i j" (1 ≤ i ≤ j ≤ n) — is the director's request. The input data has at least one director's request. In all other cases the request contains a positive integer not exceeding 109 — an employee identificator. Each odd appearance of the identificator of an employee in the request list is his arrival. Each even one is his leaving. All employees have distinct identificators. When any employee arrives, there is always at least one free hook. | 2,400 | For each director's request in the input data print a single number on a single line — the number of coats hanging on the hooks from the i-th one to the j-th one inclusive. | standard output | |
PASSED | 0731fcb0c82b898a632ab87378333377 | train_002.jsonl | 1302879600 | In one very large and very respectable company there is a cloakroom with a coat hanger. It is represented by n hooks, positioned in a row. The hooks are numbered with positive integers from 1 to n from the left to the right.The company workers have a very complicated work schedule. At the beginning of a work day all the employees are not there and the coat hanger in the cloakroom is empty. At some moments of time the employees arrive and some of them leave.When some employee arrives, he hangs his cloak on one of the available hooks. To be of as little discomfort to his colleagues as possible, the hook where the coat will hang, is chosen like this. First the employee chooses the longest segment among available hooks following in a row. If there are several of such segments, then he chooses the one closest to the right. After that the coat is hung on the hook located in the middle of this segment. If the segment has an even number of hooks, then among two central hooks we choose the one closest to the right.When an employee leaves, he takes his coat. As all the company workers deeply respect each other, no one takes somebody else's coat.From time to time the director of this respectable company gets bored and he sends his secretary to see how many coats hang on the coat hanger from the i-th to the j-th hook inclusive. And this whim is always to be fulfilled, otherwise the director gets angry and has a mental breakdown.Not to spend too much time traversing from the director's office to the cloakroom and back again, the secretary asked you to write a program, emulating the company cloakroom's work. | 256 megabytes | import java.util.*;
public class P074D {
private static class BIT {
private final int N;
private int[] tree;
public BIT(int N) {
this.N = N;
tree = new int[N + 1];
}
private void set(int x, int v) {
while (x <= N) {
tree[x] += v;
x += (x & -x);
}
}
private int get(int x) {
int res = 0;
while (x != 0) {
res += tree[x];
x -= (x & -x);
}
return res;
}
}
static class Query {
private final int type; // 0 - director, 1 - employee
private final int i; // for 1-type it's id
private final int j; // for 1-type: 0 - departure, 1 - arrival
public Query(int type, int i, int j) {
this.type = type;
this.i = i;
this.j = j;
}
}
static class Cloak implements Comparable<Cloak> {
private final int id;
private int pos;
private int left;
private int right;
private int space; // to the left neighbor
public Cloak(int id) {
this.id = id;
}
public int compareTo(Cloak other) {
if (space > other.space) return -1;
if (space < other.space) return 1;
if (pos > other.pos) return -1;
if (pos < other.pos) return 1;
return 0;
}
public void setParam(int pos, int left, int right, int space) {
this.pos = pos;
this.left = left;
this.right = right;
this.space = space;
}
}
private Cloak[] cloaks;
private BIT counter;
private TreeSet<Cloak> hanger = new TreeSet<Cloak>();
private final int N;
private final int M;
private int addCloak(int id) {
// find new comer's right neighbor
Cloak rn = hanger.pollFirst();
Cloak ln = cloaks[rn.left];
Cloak clk = cloaks[id];
int pos = (rn.pos + ln.pos + 1) / 2;
int s1 = pos - ln.pos;
int s2 = rn.pos - pos;
clk.setParam(pos, ln.id, rn.id, s1);
ln.right = id;
rn.left = id;
rn.space = s2;
hanger.add(clk);
hanger.add(rn);
//counter.add(pos);
return pos;
}
private int removeCloak(int id) {
Cloak clk = cloaks[id];
hanger.remove(clk);
Cloak rn = cloaks[clk.right];
Cloak ln = cloaks[clk.left];
hanger.remove(rn);
ln.right = rn.id;
rn.left = ln.id;
rn.space = clk.space + rn.space;
hanger.add(rn);
//counter.remove(clk.pos);
return clk.pos;
}
private int query(int i, int j) {
if (i == 1) {
return counter.get(j);
} else {
return counter.get(j) - counter.get(i-1);
}
}
private void init() {
cloaks[0].setParam(0, 0, M + 1, 0);
cloaks[M+1].setParam(N + 1, 0, M + 1, N + 1);
hanger.clear();
hanger.add(cloaks[0]);
hanger.add(cloaks[M+1]);
}
public P074D() {
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
int Q = sc.nextInt();
// preprocess to map employee ID to internal id which is consecutive
// also distinguish arrival and departure
Query[] queries = new Query[Q];
HashMap<Integer, Integer> numEmpAppr = new HashMap<Integer, Integer>();
HashMap<Integer, Integer> empIdMap = new HashMap<Integer, Integer>();
for (int k = 0; k < Q; k++) {
int x = sc.nextInt();
if (x == 0) {
int i = sc.nextInt();
int j = sc.nextInt();
queries[k] = new Query(0, i, j);
} else {
if (!numEmpAppr.containsKey(x)) {
int id = empIdMap.size() + 1;
empIdMap.put(x, id);
numEmpAppr.put(x, 0);
}
numEmpAppr.put(x, numEmpAppr.get(x) + 1);
queries[k] = new Query(1, empIdMap.get(x),
numEmpAppr.get(x) % 2);
}
}
M = empIdMap.size();
cloaks = new Cloak[M+2];
for (int i = 0; i < M + 2; i++) {
cloaks[i] = new Cloak(i);
}
init();
// first process all the query once to find all the hooks that
// have been used
TreeSet<Integer> hooks = new TreeSet<Integer>();
for (int k = 0; k < Q; k++) {
Query q = queries[k];
if (q.type == 1) {
if (q.j == 1) {
int h = addCloak(q.i);
hooks.add(h);
}
else {
removeCloak(q.i);
}
}
}
init();
// create a mapping
HashMap<Integer, Integer> hookMap = new HashMap<Integer, Integer>();
int hookId = 1;
for (int h: hooks) {
hookMap.put(h, hookId);
hookId++;
}
counter = new BIT(hookId-1);
// process again
for (int k = 0; k < Q; k++) {
Query q = queries[k];
if (q.type == 0) {
Integer left = hooks.ceiling(q.i);
if (left == null) {
System.out.println(0);
continue;
}
Integer right = hooks.floor(q.j);
if (right == null) {
System.out.println(0);
continue;
}
System.out.printf("%d\n", query(hookMap.get(left), hookMap.get(right)));
} else {
if (q.j == 1) {
int h = addCloak(q.i);
counter.set(hookMap.get(h), 1);
} else {
int h = removeCloak(q.i);
counter.set(hookMap.get(h), -1);
}
}
}
}
public static void main(String[] args) {
P074D solution = new P074D();
}
}
| Java | ["9 11\n1\n2\n0 5 8\n1\n1\n3\n0 3 8\n9\n0 6 9\n6\n0 1 9"] | 4 seconds | ["2\n3\n2\n5"] | null | Java 6 | standard input | [
"data structures"
] | 1250f103aa5fd1ac300a8a71b816b3e4 | The first line contains two integers n, q (1 ≤ n ≤ 109, 1 ≤ q ≤ 105), which are the number of hooks on the hanger and the number of requests correspondingly. Then follow q lines with requests, sorted according to time. The request of the type "0 i j" (1 ≤ i ≤ j ≤ n) — is the director's request. The input data has at least one director's request. In all other cases the request contains a positive integer not exceeding 109 — an employee identificator. Each odd appearance of the identificator of an employee in the request list is his arrival. Each even one is his leaving. All employees have distinct identificators. When any employee arrives, there is always at least one free hook. | 2,400 | For each director's request in the input data print a single number on a single line — the number of coats hanging on the hooks from the i-th one to the j-th one inclusive. | standard output | |
PASSED | b23fad386fa2797cd13e907eb334da5b | train_002.jsonl | 1302879600 | In one very large and very respectable company there is a cloakroom with a coat hanger. It is represented by n hooks, positioned in a row. The hooks are numbered with positive integers from 1 to n from the left to the right.The company workers have a very complicated work schedule. At the beginning of a work day all the employees are not there and the coat hanger in the cloakroom is empty. At some moments of time the employees arrive and some of them leave.When some employee arrives, he hangs his cloak on one of the available hooks. To be of as little discomfort to his colleagues as possible, the hook where the coat will hang, is chosen like this. First the employee chooses the longest segment among available hooks following in a row. If there are several of such segments, then he chooses the one closest to the right. After that the coat is hung on the hook located in the middle of this segment. If the segment has an even number of hooks, then among two central hooks we choose the one closest to the right.When an employee leaves, he takes his coat. As all the company workers deeply respect each other, no one takes somebody else's coat.From time to time the director of this respectable company gets bored and he sends his secretary to see how many coats hang on the coat hanger from the i-th to the j-th hook inclusive. And this whim is always to be fulfilled, otherwise the director gets angry and has a mental breakdown.Not to spend too much time traversing from the director's office to the cloakroom and back again, the secretary asked you to write a program, emulating the company cloakroom's work. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.BigInteger;
import static java.lang.Math.*;
public class Main implements Runnable {
StringTokenizer tokenizer = new StringTokenizer("");
BufferedReader in;
PrintStream out;
public void debug(String s) {
System.out.println(s);
}
public static void main(String[] args) {
new Thread(new Main()).start();
}
public void run() {
try {
Locale.setDefault(Locale.US);
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintStream(System.out);
Treap tr = new Treap();
int n = nextInt(), q = nextInt();
tr.add(0);
tr.add(n + 1);
HashMap <Integer, Integer> map = new HashMap <Integer, Integer> ();
for (int i = 0; i < q; i++) {
int m = nextInt();
if (m == 0) {
int l = nextInt(), r = nextInt();
int res = tr.count(l, r);
out.println(res);
} else {
if (map.containsKey(m)) {
tr.remove(map.get(m));
map.remove(m);
} else {
int x = tr.add();
map.put(m, x);
}
}
}
//for (int i = 0; i < n; i++) out.print(tr.count(i + 1, i + 1) + " ");
} catch (Exception e) {
e.printStackTrace();
}
}
boolean seekForToken() {
while (!tokenizer.hasMoreTokens()) {
String s = null;
try {
s = in.readLine();
} catch (Exception e) {
e.printStackTrace();
}
if (s == null)
return false;
tokenizer = new StringTokenizer(s);
}
return true;
}
String nextToken() {
return seekForToken() ? tokenizer.nextToken() : null;
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
BigInteger nextBig() {
return new BigInteger(nextToken());
}
}
class Treap {
static Random rand = new Random();
Node root = null;
Node makeNode(int x) {
return new Node(x, rand.nextInt());
}
int add() {
int rx;
Node cur = root;
while (true) {
int bl = cur.ml;
if (cur.R != null) {
if (cur.R.ml == bl) {
cur = cur.R;
continue;
}
if (cur.R.mxl - cur.x == bl) {
rx = cur.x + (bl + 1) / 2;
add(rx);
return rx;
}
}
if (cur.x - cur.L.mxr == bl) {
rx = cur.L.mxr + (bl + 1) / 2;
add(rx);
return rx;
}
cur = cur.L;
}
}
void add(int x) {
Node toAdd = makeNode(x);
Node [] w = split(root, x);
root = merge(merge(w[0], toAdd), w[1]);
}
void remove(int x) {
Node [] w = split(root, x - 1);
Node [] v = split(w[1], x);
root = merge(w[0], v[1]);
}
int count(int xl, int xr) {
Node [] w = split(root, xl - 1);
Node [] v = split(w[1], xr);
int ret = getCnt(v[0]);
root = merge(w[0], merge(v[0], v[1]));
return ret;
}
int getCnt(Node n) {
return n == null ? 0 : n.cnt;
}
int getMl(Node n) {
return n == null ? 0 : n.ml;
}
int M = (Integer.MAX_VALUE / 2) - 5;
int getMxr(Node n) {
return n == null ? M : n.mxr;
}
int getMxl(Node n) {
return n == null ? -M : n.mxl;
}
void updateCnt(Node n) {
n.cnt = getCnt(n.L) + getCnt(n.R) + 1;
n.mxr = n.R == null ? n.x : max(n.x, n.R.mxr);
n.mxl = n.L == null ? n.x : min(n.x, n.L.mxl);
n.ml = max(getMl(n.L), getMl(n.R));
n.ml = max(n.ml, n.x - getMxr(n.L));
n.ml = max(n.ml, getMxl(n.R) - n.x);
}
Node merge(Node n1, Node n2) {
if (n1 == null) return n2;
if (n2 == null) return n1;
if (n1.y < n2.y) {
n2.L = merge(n1, n2.L);
updateCnt(n2);
return n2;
} else {
n1.R = merge(n1.R, n2);
updateCnt(n1);
return n1;
}
}
Node [] split(Node n, int x0) {
if (n == null) return new Node[2];
if (n.x <= x0) {
Node [] w = split(n.R, x0);
n.R = w[0];
updateCnt(n);
return new Node[] {n, w[1]};
} else {
Node [] w = split(n.L, x0);
n.L = w[1];
updateCnt(n);
return new Node[] {w[0], n};
}
}
void debug() {
root.debug(0);
}
}
class Node {
int x, y;
Node L = null, R = null;
int cnt = 1, ml = 0, mxr, mxl;
Node(int x, int y) {
this.x = x;
this.y = y;
mxr = x;
mxl = x;
}
void debug(int h) {
if (R != null) R.debug(h + 1);
String out = "";
for (int i = 0; i < h; i++) out += " ";
System.out.println(out + x + "(" + cnt + ")");
if (L != null) L.debug(h + 1);
}
}
| Java | ["9 11\n1\n2\n0 5 8\n1\n1\n3\n0 3 8\n9\n0 6 9\n6\n0 1 9"] | 4 seconds | ["2\n3\n2\n5"] | null | Java 6 | standard input | [
"data structures"
] | 1250f103aa5fd1ac300a8a71b816b3e4 | The first line contains two integers n, q (1 ≤ n ≤ 109, 1 ≤ q ≤ 105), which are the number of hooks on the hanger and the number of requests correspondingly. Then follow q lines with requests, sorted according to time. The request of the type "0 i j" (1 ≤ i ≤ j ≤ n) — is the director's request. The input data has at least one director's request. In all other cases the request contains a positive integer not exceeding 109 — an employee identificator. Each odd appearance of the identificator of an employee in the request list is his arrival. Each even one is his leaving. All employees have distinct identificators. When any employee arrives, there is always at least one free hook. | 2,400 | For each director's request in the input data print a single number on a single line — the number of coats hanging on the hooks from the i-th one to the j-th one inclusive. | standard output | |
PASSED | bf0bf9a1017b98cd6a39200d0f3c2f40 | train_002.jsonl | 1302879600 | In one very large and very respectable company there is a cloakroom with a coat hanger. It is represented by n hooks, positioned in a row. The hooks are numbered with positive integers from 1 to n from the left to the right.The company workers have a very complicated work schedule. At the beginning of a work day all the employees are not there and the coat hanger in the cloakroom is empty. At some moments of time the employees arrive and some of them leave.When some employee arrives, he hangs his cloak on one of the available hooks. To be of as little discomfort to his colleagues as possible, the hook where the coat will hang, is chosen like this. First the employee chooses the longest segment among available hooks following in a row. If there are several of such segments, then he chooses the one closest to the right. After that the coat is hung on the hook located in the middle of this segment. If the segment has an even number of hooks, then among two central hooks we choose the one closest to the right.When an employee leaves, he takes his coat. As all the company workers deeply respect each other, no one takes somebody else's coat.From time to time the director of this respectable company gets bored and he sends his secretary to see how many coats hang on the coat hanger from the i-th to the j-th hook inclusive. And this whim is always to be fulfilled, otherwise the director gets angry and has a mental breakdown.Not to spend too much time traversing from the director's office to the cloakroom and back again, the secretary asked you to write a program, emulating the company cloakroom's work. | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Comparator;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.Random;
/**
* Generated by Contest helper plug-in
* Actual solution is at the bottom
*/
public class Main {
public static void main(String[] args) {
InputReader in = new StreamInputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
run(in, out);
}
public static void run(InputReader in, PrintWriter out) {
Solver solver = new testTreap();
solver.solve(1, in, out);
Exit.exit(in, out);
}
}
class StreamInputReader extends InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar, numChars;
public StreamInputReader(InputStream stream) {
this.stream = stream;
curChar = 0;
}
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++];
}
@Override
public void close() {
try {
stream.close();
} catch (IOException ignored) {
}
}
}
abstract class InputReader {
private boolean finished = false;
public abstract int read();
public int nextInt() {
return Integer.parseInt(nextToken());
}
public String nextToken() {
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;
}
public void setFinished(boolean finished) {
this.finished = finished;
}
public abstract void close();
}
interface Solver {
public void solve(int testNumber, InputReader in, PrintWriter out);
}
class Exit {
private Exit() {
}
public static void exit(InputReader in, PrintWriter out) {
in.setFinished(true);
in.close();
out.close();
}
}
class Structures {
public static class Mapping<K> {
public HashMap<K, Integer> map;
public Mapping() {
map = new HashMap<K, Integer> () ;
}
public void increaseValue(K key, int value) {
Integer previous = map.get(key);
if (previous == null) {
map.put(key, value);
} else map.put(key, value + previous);
}
public int getValue(K key) {
Integer get = map.get(key);
return get == null ? 0 : get;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Mapping mapping = (Mapping) o;
if (map != null ? !map.equals(mapping.map) : mapping.map != null) return false;
return true;
}
@Override
public int hashCode() {
return map != null ? map.hashCode() : 0;
}
}
public static class Tree<K> {
private class Node {
int prior;
K value;
int cnt;
Node left, right;
Node(int prior, K value, int cnt, Node left, Node right) {
this.prior = prior;
this.value = value;
this.cnt = cnt;
this.left = left;
this.right = right;
}
}
private Node Root ;
private Random random;
Comparator<K> comparator;
public Tree(Comparator<K> comparator, Random random) {
Root = null;
this.random = random;
this.comparator = comparator;
}
public Tree(Comparator<K> comparator) {
Root = null;
random = new Random(23985723857L);
this.comparator = comparator;
}
public K first() {
return first(Root);
}
public K ceiling(K value) {
return ceiling(Root, value);
}
public K floor(K value) {
return floor(Root, value) ;
}
public boolean add(K value) {
if (contains(Root, value)) {
return false;
} else {
Object[] t = split(Root, value);
Root = merge((Node)t[0], new Node(random.nextInt(), value, 1, null, null));
Root = merge(Root, (Node)t[1]);
return true;
}
}
public boolean contains(K value) {
return contains(Root, value);
}
public boolean remove(K value) {
if (contains(value)) {
Root = remove(Root, value);
return true;
} else return false;
}
public int countLower(K value) {
return countLower(Root, value);
}
private int countLower(Node root, K value) {
if (root == null) return 0;
int cmp = comparator.compare(root.value, value);
if (cmp <= 0) return countLower(root.right, value) + getCnt(root.left) + 1;
else return countLower(root.left, value);
}
private K floor(Node root, K value) {
if (root == null) return null;
int cmp = comparator.compare(root.value, value);
if (cmp == 0) return root.value;
else if (cmp < 0) {
K tmp = floor(root.right, value);
if (tmp == null) return root.value;
else {
int cmp0 = comparator.compare(tmp, root.value);
if (cmp0 > 0) return tmp;
else return root.value;
}
} else {
return floor(root.left, value);
}
}
private K ceiling(Node root, K value) {
if (root == null) return null;
int cmp = comparator.compare(root.value, value);
if (cmp == 0) return value;
else if (cmp < 0) return ceiling(root.right, value);
else {
K tmp = ceiling(root.left, value);
if (tmp == null) return root.value;
else {
int cmp0 = comparator.compare(tmp, root.value);
if (cmp0 < 0) return tmp;
else return root.value;
}
}
}
private boolean contains(Node root, K value) {
if (root == null) return false;
int cmp = comparator.compare(root.value, value);
if (cmp == 0) return true;
else if (cmp < 0) return contains(root.right, value);
else return contains(root.left, value);
}
private Node remove(Node root, K value) {
int cmp = comparator.compare(root.value, value);
if (cmp == 0) root = merge(root.left, root.right);
else if (cmp < 0) root.right = remove(root.right, value);
else root.left = remove(root.left, value);
update(root);
return root;
}
private K first(Node root) {
if (root == null) return null;
if (root.left == null) return root.value;
else return first(root.left);
}
private int getCnt(Node node) {
return node == null ? 0 : node.cnt;
}
private void update(Node node) {
if (node != null) node.cnt = getCnt(node.left) + getCnt(node.right) + 1;
}
private Node merge(Node Left, Node Right) {
if (Left == null || Right == null) {
return Left == null ? Right : Left;
} else {
if (Left.prior <= Right.prior) {
Left.right = merge(Left.right, Right);
update(Left);
return Left;
} else {
Right.left = merge(Left, Right.left);
update(Right);
return Right;
}
}
}
private Object[] split(Node Root, K key) {
if (Root == null) {
return new Object[] {null, null};
} else {
if (comparator.compare(Root.value, key) <= 0) {
Object tmp[] = split(Root.right, key);
Root.right = (Node)tmp[0];
update(Root);
return new Object[] {Root, (Node)tmp[1]};
} else {
Object tmp[] = split(Root.left, key);
Root.left = (Node)tmp[1];
update(Root);
return new Object[] {(Node)tmp[0], Root};
}
}
}
}
}
class testTreap implements Solver {
public void solve(int testNumber, InputReader in, PrintWriter out) {
Structures.Tree<Pair> set = new Structures.Tree<Pair>(new Comparator<Pair>() {
public int compare(Pair a, Pair b) {
int o1 = a.second - a.first + 1;
int o2 = b.second - b.first + 1;
if (o1 != o2) return o2 - o1;
return b.first - a.first;
}
} );
Structures.Tree<Pair> order = new Structures.Tree<Pair>(new Comparator<Pair>() {
public int compare(Pair pair, Pair pair1) {
int o = pair.first - pair1.first;
if (o != 0) return o;
return pair.second - pair1.second;
}
});
int n = in.nextInt();
int q = in.nextInt();
set.add(new Pair(1, n));
order.add(new Pair(1, n));
Structures.Tree<Integer> tree = new Structures.Tree<Integer>(new Comparator<Integer>() {
public int compare(Integer integer, Integer integer1) {
return integer - integer1;
}
});
tree.first();
Structures.Mapping<Integer> mapping = new Structures.Mapping<Integer> () ;
HashMap<Integer, Integer> Pointer = new HashMap<Integer, Integer> () ;
for (int qu = 0; qu < q; ++qu) {
int oper = in.nextInt();
if (oper == 0) {
int left = in.nextInt();
int right = in.nextInt();
out.println(tree.countLower(right) - tree.countLower(left - 1));
} else {
int c = mapping.getValue(oper);
if (c % 2 == 0) {
Pair tmp = set.first();
set.remove(tmp);
order.remove(tmp);
int mid = (tmp.first + (tmp.second - tmp.first + 1) / 2) ;
tree.add(mid);
Pointer.put(oper, mid);
if (tmp.first <= mid - 1) {
Pair ins = new Pair(tmp.first, mid - 1);
set.add(ins);
order.add(ins);
}
if (mid + 1 <= tmp.second) {
Pair ins = new Pair(mid + 1, tmp.second);
set.add(ins);
order.add(ins);
}
} else {
int m = Pointer.get(oper);
tree.remove(m);
Pair a = order.floor(new Pair(m, -1));
Pair b = order.ceiling(new Pair(m, -1));
Pair tmp = new Pair(m, m);
if (a != null) {
if (a.second + 1 == m) {
tmp.first = a.first;
order.remove(a);
set.remove(a);
}
}
if (b != null) {
if (m + 1 == b.first) {
tmp.second = b.second;
order.remove(b);
set.remove(b);
}
}
set.add(tmp);
order.add(tmp);
}
mapping.increaseValue(oper, 1);
}
}
}
class Pair {
int first, second;
Pair(int first, int second) {
this.first = first;
this.second = second;
}
}
}
| Java | ["9 11\n1\n2\n0 5 8\n1\n1\n3\n0 3 8\n9\n0 6 9\n6\n0 1 9"] | 4 seconds | ["2\n3\n2\n5"] | null | Java 6 | standard input | [
"data structures"
] | 1250f103aa5fd1ac300a8a71b816b3e4 | The first line contains two integers n, q (1 ≤ n ≤ 109, 1 ≤ q ≤ 105), which are the number of hooks on the hanger and the number of requests correspondingly. Then follow q lines with requests, sorted according to time. The request of the type "0 i j" (1 ≤ i ≤ j ≤ n) — is the director's request. The input data has at least one director's request. In all other cases the request contains a positive integer not exceeding 109 — an employee identificator. Each odd appearance of the identificator of an employee in the request list is his arrival. Each even one is his leaving. All employees have distinct identificators. When any employee arrives, there is always at least one free hook. | 2,400 | For each director's request in the input data print a single number on a single line — the number of coats hanging on the hooks from the i-th one to the j-th one inclusive. | standard output | |
PASSED | 3b708e2e9a45d62469e75202c9a1d69e | train_002.jsonl | 1302879600 | In one very large and very respectable company there is a cloakroom with a coat hanger. It is represented by n hooks, positioned in a row. The hooks are numbered with positive integers from 1 to n from the left to the right.The company workers have a very complicated work schedule. At the beginning of a work day all the employees are not there and the coat hanger in the cloakroom is empty. At some moments of time the employees arrive and some of them leave.When some employee arrives, he hangs his cloak on one of the available hooks. To be of as little discomfort to his colleagues as possible, the hook where the coat will hang, is chosen like this. First the employee chooses the longest segment among available hooks following in a row. If there are several of such segments, then he chooses the one closest to the right. After that the coat is hung on the hook located in the middle of this segment. If the segment has an even number of hooks, then among two central hooks we choose the one closest to the right.When an employee leaves, he takes his coat. As all the company workers deeply respect each other, no one takes somebody else's coat.From time to time the director of this respectable company gets bored and he sends his secretary to see how many coats hang on the coat hanger from the i-th to the j-th hook inclusive. And this whim is always to be fulfilled, otherwise the director gets angry and has a mental breakdown.Not to spend too much time traversing from the director's office to the cloakroom and back again, the secretary asked you to write a program, emulating the company cloakroom's work. | 256 megabytes | import java.util.NavigableSet;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.Random;
import java.io.*;
import java.util.Comparator;
import java.util.TreeSet;
import java.util.Arrays;
/**
* Generated by Contest helper plug-in
* Actual solution is at the bottom
*/
public class Main {
public static void main(String[] args) {
InputReader in = new StreamInputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
run(in, out);
}
public static void run(InputReader in, PrintWriter out) {
Solver solver = new Hanger();
solver.solve(1, in, out);
Exit.exit(in, out);
}
}
class StreamInputReader extends InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar, numChars;
public StreamInputReader(InputStream stream) {
this.stream = stream;
curChar = 0;
}
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++];
}
@Override
public void close() {
try {
stream.close();
} catch (IOException ignored) {
}
}
}
abstract class InputReader {
private boolean finished = false;
public abstract int read();
public int nextInt() {
return Integer.parseInt(nextToken());
}
public String nextToken() {
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;
}
public void setFinished(boolean finished) {
this.finished = finished;
}
public abstract void close();
}
interface Solver {
public void solve(int testNumber, InputReader in, PrintWriter out);
}
class Exit {
private Exit() {
}
public static void exit(InputReader in, PrintWriter out) {
in.setFinished(true);
in.close();
out.close();
}
}
class Structures {
public static class Mapping<K> {
public HashMap<K, Integer> map;
public Mapping() {
map = new HashMap<K, Integer> () ;
}
public void increaseValue(K key, int value) {
Integer previous = map.get(key);
if (previous == null) {
map.put(key, value);
} else map.put(key, value + previous);
}
public int getValue(K key) {
Integer get = map.get(key);
return get == null ? 0 : get;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Mapping mapping = (Mapping) o;
if (map != null ? !map.equals(mapping.map) : mapping.map != null) return false;
return true;
}
@Override
public int hashCode() {
return map != null ? map.hashCode() : 0;
}
}
public static class BalancedTree {
private class Node {
int prior;
int value;
int cnt;
Node left, right;
Node(int prior, int value, int cnt, Node left, Node right) {
this.prior = prior;
this.value = value;
this.cnt = cnt;
this.left = left;
this.right = right;
}
}
private Node Root ;
private Random random;
public int getCount(int left, int right) {
int a = getCount(Root, right);
int b = getCount(Root, left - 1);
return a - b;
}
public BalancedTree() {
Root = null;
random = new Random(892375325L);
}
public void erase(int value) {
Node t[] = split(Root, value);
Node q[] = split(t[0], value - 1);
Root = merge(q[0], t[1]);
}
public void insert(int value) {
Node[] t = split(Root, value);
Root = merge(t[0], new Node(random.nextInt(), value, 1, null, null));
Root = merge(Root, t[1]);
}
private int getCount(Node root, int right) {
if (root == null) return 0;
if (root.value <= right) return getCnt(root.left) + 1 + getCount(root.right, right);
else return getCount(root.left, right);
}
private int getCnt(Node node) {
return node == null ? 0 : node.cnt;
}
private void update(Node node) {
if (node != null) node.cnt = getCnt(node.left) + getCnt(node.right) + 1;
}
private Node merge(Node Left, Node Right) {
if (Left == null || Right == null) {
return Left == null ? Right : Left;
} else {
if (Left.prior <= Right.prior) {
Left.right = merge(Left.right, Right);
update(Left);
return Left;
} else {
Right.left = merge(Left, Right.left);
update(Right);
return Right;
}
}
}
private Node[] split(Node Root, int key) {
if (Root == null) {
return new Node[] {null, null};
} else {
if (Root.value <= key) {
Node tmp[] = split(Root.right, key);
Root.right = tmp[0];
update(Root);
return new Node[] {Root, tmp[1]};
} else {
Node tmp[] = split(Root.left, key);
Root.left = tmp[1];
update(Root);
return new Node[] {tmp[0], Root};
}
}
}
}
}
class Hanger implements Solver {
public void solve(int testNumber, InputReader in, PrintWriter out) {
TreeSet<Pair> set = new TreeSet<Pair>(new Comparator<Pair>() {
public int compare(Pair a, Pair b) {
int o1 = a.second - a.first + 1;
int o2 = b.second - b.first + 1;
if (o1 != o2) return o2 - o1;
return b.first - a.first;
}
} );
NavigableSet<Pair> order = new TreeSet<Pair>(new Comparator<Pair>() {
public int compare(Pair a, Pair b) {
int d = a.first - b.first;
if (d != 0) return d;
return a.second - b.second;
}
}) ;
int n = in.nextInt();
int q = in.nextInt();
set.add(new Pair(1, n));
order.add(new Pair(1, n));
Structures.BalancedTree tree = new Structures.BalancedTree();
Structures.Mapping<Integer> mapping = new Structures.Mapping<Integer> () ;
HashMap<Integer, Integer> Pointer = new HashMap<Integer, Integer> () ;
for (int qu = 0; qu < q; ++qu) {
int oper = in.nextInt();
if (oper == 0) {
int left = in.nextInt();
int right = in.nextInt();
out.println(tree.getCount(left, right));
} else {
int c = mapping.getValue(oper);
if (c % 2 == 0) {
Pair tmp = set.pollFirst();
order.remove(tmp);
int mid = (tmp.first + (tmp.second - tmp.first + 1) / 2) ;
tree.insert(mid);
Pointer.put(oper, mid);
if (tmp.first <= mid - 1) {
Pair ins = new Pair(tmp.first, mid - 1);
set.add(ins);
order.add(ins);
}
if (mid + 1 <= tmp.second) {
Pair ins = new Pair(mid + 1, tmp.second);
set.add(ins);
order.add(ins);
}
} else {
int m = Pointer.get(oper);
tree.erase(m);
Pair a = order.floor(new Pair(m, -1));
Pair b = order.ceiling(new Pair(m, -1));
Pair tmp = new Pair(m, m);
if (a != null) {
if (a.second + 1 == m) {
tmp.first = a.first;
order.remove(a);
set.remove(a);
}
}
if (b != null) {
if (m + 1 == b.first) {
tmp.second = b.second;
order.remove(b);
set.remove(b);
}
}
set.add(tmp);
order.add(tmp);
}
mapping.increaseValue(oper, 1);
}
}
}
class Pair {
int first, second;
Pair(int first, int second) {
this.first = first;
this.second = second;
}
}
}
| Java | ["9 11\n1\n2\n0 5 8\n1\n1\n3\n0 3 8\n9\n0 6 9\n6\n0 1 9"] | 4 seconds | ["2\n3\n2\n5"] | null | Java 6 | standard input | [
"data structures"
] | 1250f103aa5fd1ac300a8a71b816b3e4 | The first line contains two integers n, q (1 ≤ n ≤ 109, 1 ≤ q ≤ 105), which are the number of hooks on the hanger and the number of requests correspondingly. Then follow q lines with requests, sorted according to time. The request of the type "0 i j" (1 ≤ i ≤ j ≤ n) — is the director's request. The input data has at least one director's request. In all other cases the request contains a positive integer not exceeding 109 — an employee identificator. Each odd appearance of the identificator of an employee in the request list is his arrival. Each even one is his leaving. All employees have distinct identificators. When any employee arrives, there is always at least one free hook. | 2,400 | For each director's request in the input data print a single number on a single line — the number of coats hanging on the hooks from the i-th one to the j-th one inclusive. | standard output | |
PASSED | 9b343ccba76717484be64fee5fe38090 | train_002.jsonl | 1302879600 | In one very large and very respectable company there is a cloakroom with a coat hanger. It is represented by n hooks, positioned in a row. The hooks are numbered with positive integers from 1 to n from the left to the right.The company workers have a very complicated work schedule. At the beginning of a work day all the employees are not there and the coat hanger in the cloakroom is empty. At some moments of time the employees arrive and some of them leave.When some employee arrives, he hangs his cloak on one of the available hooks. To be of as little discomfort to his colleagues as possible, the hook where the coat will hang, is chosen like this. First the employee chooses the longest segment among available hooks following in a row. If there are several of such segments, then he chooses the one closest to the right. After that the coat is hung on the hook located in the middle of this segment. If the segment has an even number of hooks, then among two central hooks we choose the one closest to the right.When an employee leaves, he takes his coat. As all the company workers deeply respect each other, no one takes somebody else's coat.From time to time the director of this respectable company gets bored and he sends his secretary to see how many coats hang on the coat hanger from the i-th to the j-th hook inclusive. And this whim is always to be fulfilled, otherwise the director gets angry and has a mental breakdown.Not to spend too much time traversing from the director's office to the cloakroom and back again, the secretary asked you to write a program, emulating the company cloakroom's work. | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;
/**
* Generated by Contest helper plug-in
* Actual solution is at the bottom
*/
public class Main {
public static void main(String[] args) {
InputReader in = new StreamInputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
run(in, out);
}
public static void run(InputReader in, PrintWriter out) {
Solver solver = new testTreap();
solver.solve(1, in, out);
Exit.exit(in, out);
}
}
class StreamInputReader extends InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar, numChars;
public StreamInputReader(InputStream stream) {
this.stream = stream;
curChar = 0;
}
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++];
}
@Override
public void close() {
try {
stream.close();
} catch (IOException ignored) {
}
}
}
abstract class InputReader {
private boolean finished = false;
public abstract int read();
public int nextInt() {
return Integer.parseInt(nextToken());
}
public String nextToken() {
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;
}
public void setFinished(boolean finished) {
this.finished = finished;
}
public abstract void close();
}
interface Solver {
public void solve(int testNumber, InputReader in, PrintWriter out);
}
class Exit {
private Exit() {
}
public static void exit(InputReader in, PrintWriter out) {
in.setFinished(true);
in.close();
out.close();
}
}
class Structures {
public static class Mapping<K> {
public HashMap<K, Integer> map;
public Mapping() {
map = new HashMap<K, Integer> () ;
}
public void increaseValue(K key, int value) {
Integer previous = map.get(key);
if (previous == null) {
map.put(key, value);
} else map.put(key, value + previous);
}
public int getValue(K key) {
Integer get = map.get(key);
return get == null ? 0 : get;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Mapping mapping = (Mapping) o;
if (map != null ? !map.equals(mapping.map) : mapping.map != null) return false;
return true;
}
@Override
public int hashCode() {
return map != null ? map.hashCode() : 0;
}
}
public static class Tree<K extends Comparable<K>> {
private class Node {
int prior;
K value;
int cnt;
Node left, right;
Node(int prior, K value, int cnt, Node left, Node right) {
this.prior = prior;
this.value = value;
this.cnt = cnt;
this.left = left;
this.right = right;
}
}
private Node Root ;
private Random random;
public Tree() {
Root = null;
random = new Random(892375325L);
}
public K first() {
return first(Root);
}
public boolean add(K value) {
if (contains(Root, value)) {
return false;
} else {
Object[] t = split(Root, value);
Root = merge((Node)t[0], new Node(random.nextInt(), value, 1, null, null));
Root = merge(Root, (Node)t[1]);
return true;
}
}
public boolean contains(K value) {
return contains(Root, value);
}
public boolean remove(K value) {
if (contains(value)) {
Root = remove(Root, value);
return true;
} else return false;
}
public int countLower(K value) {
return countLower(Root, value);
}
private int countLower(Node root, K value) {
if (root == null) return 0;
int cmp = root.value.compareTo(value);
if (cmp <= 0) return countLower(root.right, value) + getCnt(root.left) + 1;
else return countLower(root.left, value);
}
private boolean contains(Node root, K value) {
if (root == null) return false;
int cmp = root.value.compareTo(value);
if (cmp == 0) return true;
else if (cmp < 0) return contains(root.right, value);
else return contains(root.left, value);
}
private Node remove(Node root, K value) {
int cmp = root.value.compareTo(value);
Node res = root;
if (cmp == 0) res = merge(root.left, root.right);
else if (cmp < 0) res.right = remove(root.right, value);
else res.left = remove(root.left, value);
update(res);
return res;
}
private K first(Node root) {
if (root == null) return null;
if (root.left == null) return root.value;
else return first(root.left);
}
private int getCnt(Node node) {
return node == null ? 0 : node.cnt;
}
private void update(Node node) {
if (node != null) node.cnt = getCnt(node.left) + getCnt(node.right) + 1;
}
private Node merge(Node Left, Node Right) {
if (Left == null || Right == null) {
return Left == null ? Right : Left;
} else {
if (Left.prior <= Right.prior) {
Left.right = merge(Left.right, Right);
update(Left);
return Left;
} else {
Right.left = merge(Left, Right.left);
update(Right);
return Right;
}
}
}
private Object[] split(Node Root, K key) {
if (Root == null) {
return new Object[] {null, null};
} else {
if (Root.value.compareTo(key) <= 0) {
Object tmp[] = split(Root.right, key);
Root.right = (Node)tmp[0];
update(Root);
return new Object[] {Root, (Node)tmp[1]};
} else {
Object tmp[] = split(Root.left, key);
Root.left = (Node)tmp[1];
update(Root);
return new Object[] {(Node)tmp[0], Root};
}
}
}
}
}
class testTreap implements Solver {
public void solve(int testNumber, InputReader in, PrintWriter out) {
TreeSet<Pair> set = new TreeSet<Pair>(new Comparator<Pair>() {
public int compare(Pair a, Pair b) {
int o1 = a.second - a.first + 1;
int o2 = b.second - b.first + 1;
if (o1 != o2) return o2 - o1;
return b.first - a.first;
}
} );
// Structures.Tree<Pair> order = new Structures.Tree<Pair>();
NavigableSet<Pair> order = new TreeSet<Pair>() ;
int n = in.nextInt();
int q = in.nextInt();
set.add(new Pair(1, n));
order.add(new Pair(1, n));
Structures.Tree<Integer> tree = new Structures.Tree<Integer>();
tree.first();
Structures.Mapping<Integer> mapping = new Structures.Mapping<Integer> () ;
HashMap<Integer, Integer> Pointer = new HashMap<Integer, Integer> () ;
for (int qu = 0; qu < q; ++qu) {
int oper = in.nextInt();
if (oper == 0) {
int left = in.nextInt();
int right = in.nextInt();
out.println(tree.countLower(right) - tree.countLower(left - 1));
} else {
int c = mapping.getValue(oper);
if (c % 2 == 0) {
Pair tmp = set.pollFirst();
order.remove(tmp);
int mid = (tmp.first + (tmp.second - tmp.first + 1) / 2) ;
tree.add(mid);
Pointer.put(oper, mid);
if (tmp.first <= mid - 1) {
Pair ins = new Pair(tmp.first, mid - 1);
set.add(ins);
order.add(ins);
}
if (mid + 1 <= tmp.second) {
Pair ins = new Pair(mid + 1, tmp.second);
set.add(ins);
order.add(ins);
}
} else {
int m = Pointer.get(oper);
tree.remove(m);
Pair a = order.floor(new Pair(m, -1));
Pair b = order.ceiling(new Pair(m, -1));
Pair tmp = new Pair(m, m);
if (a != null) {
if (a.second + 1 == m) {
tmp.first = a.first;
order.remove(a);
set.remove(a);
}
}
if (b != null) {
if (m + 1 == b.first) {
tmp.second = b.second;
order.remove(b);
set.remove(b);
}
}
set.add(tmp);
order.add(tmp);
}
mapping.increaseValue(oper, 1);
}
}
}
class Pair implements Comparable<Pair> {
int first, second;
Pair(int first, int second) {
this.first = first;
this.second = second;
}
public int compareTo(Pair pair) {
int d = first - pair.first;
if (d != 0) return d;
return second - pair.second;
}
}
}
| Java | ["9 11\n1\n2\n0 5 8\n1\n1\n3\n0 3 8\n9\n0 6 9\n6\n0 1 9"] | 4 seconds | ["2\n3\n2\n5"] | null | Java 6 | standard input | [
"data structures"
] | 1250f103aa5fd1ac300a8a71b816b3e4 | The first line contains two integers n, q (1 ≤ n ≤ 109, 1 ≤ q ≤ 105), which are the number of hooks on the hanger and the number of requests correspondingly. Then follow q lines with requests, sorted according to time. The request of the type "0 i j" (1 ≤ i ≤ j ≤ n) — is the director's request. The input data has at least one director's request. In all other cases the request contains a positive integer not exceeding 109 — an employee identificator. Each odd appearance of the identificator of an employee in the request list is his arrival. Each even one is his leaving. All employees have distinct identificators. When any employee arrives, there is always at least one free hook. | 2,400 | For each director's request in the input data print a single number on a single line — the number of coats hanging on the hooks from the i-th one to the j-th one inclusive. | standard output | |
PASSED | 8bbe7615562923be14138a793751c955 | train_002.jsonl | 1302879600 | In one very large and very respectable company there is a cloakroom with a coat hanger. It is represented by n hooks, positioned in a row. The hooks are numbered with positive integers from 1 to n from the left to the right.The company workers have a very complicated work schedule. At the beginning of a work day all the employees are not there and the coat hanger in the cloakroom is empty. At some moments of time the employees arrive and some of them leave.When some employee arrives, he hangs his cloak on one of the available hooks. To be of as little discomfort to his colleagues as possible, the hook where the coat will hang, is chosen like this. First the employee chooses the longest segment among available hooks following in a row. If there are several of such segments, then he chooses the one closest to the right. After that the coat is hung on the hook located in the middle of this segment. If the segment has an even number of hooks, then among two central hooks we choose the one closest to the right.When an employee leaves, he takes his coat. As all the company workers deeply respect each other, no one takes somebody else's coat.From time to time the director of this respectable company gets bored and he sends his secretary to see how many coats hang on the coat hanger from the i-th to the j-th hook inclusive. And this whim is always to be fulfilled, otherwise the director gets angry and has a mental breakdown.Not to spend too much time traversing from the director's office to the cloakroom and back again, the secretary asked you to write a program, emulating the company cloakroom's work. | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;
/**
* Generated by Contest helper plug-in
* Actual solution is at the bottom
*/
public class Main {
public static void main(String[] args) {
InputReader in = new StreamInputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
run(in, out);
}
public static void run(InputReader in, PrintWriter out) {
Solver solver = new testTreap();
solver.solve(1, in, out);
Exit.exit(in, out);
}
}
class StreamInputReader extends InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar, numChars;
public StreamInputReader(InputStream stream) {
this.stream = stream;
curChar = 0;
}
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++];
}
@Override
public void close() {
try {
stream.close();
} catch (IOException ignored) {
}
}
}
abstract class InputReader {
private boolean finished = false;
public abstract int read();
public int nextInt() {
return Integer.parseInt(nextToken());
}
public String nextToken() {
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;
}
public void setFinished(boolean finished) {
this.finished = finished;
}
public abstract void close();
}
interface Solver {
public void solve(int testNumber, InputReader in, PrintWriter out);
}
class Exit {
private Exit() {
}
public static void exit(InputReader in, PrintWriter out) {
in.setFinished(true);
in.close();
out.close();
}
}
class Structures {
public static class Mapping<K> {
public HashMap<K, Integer> map;
public Mapping() {
map = new HashMap<K, Integer> () ;
}
public void increaseValue(K key, int value) {
Integer previous = map.get(key);
if (previous == null) {
map.put(key, value);
} else map.put(key, value + previous);
}
public int getValue(K key) {
Integer get = map.get(key);
return get == null ? 0 : get;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Mapping mapping = (Mapping) o;
if (map != null ? !map.equals(mapping.map) : mapping.map != null) return false;
return true;
}
@Override
public int hashCode() {
return map != null ? map.hashCode() : 0;
}
}
public static class Tree<K extends Comparable<K>> {
private class Node {
int prior;
K value;
int cnt;
Node left, right;
Node(int prior, K value, int cnt, Node left, Node right) {
this.prior = prior;
this.value = value;
this.cnt = cnt;
this.left = left;
this.right = right;
}
}
private Node Root ;
private Random random;
public Tree() {
Root = null;
random = new Random(892375325L);
}
public K first() {
return first(Root);
}
public K ceiling(K value) {
return ceiling(Root, value);
}
public K floor(K value) {
return floor(Root, value) ;
}
public boolean add(K value) {
if (contains(Root, value)) {
return false;
} else {
Object[] t = split(Root, value);
Root = merge((Node)t[0], new Node(random.nextInt(), value, 1, null, null));
Root = merge(Root, (Node)t[1]);
return true;
}
}
public boolean contains(K value) {
return contains(Root, value);
}
public boolean remove(K value) {
if (contains(value)) {
Root = remove(Root, value);
return true;
} else return false;
}
public int countLower(K value) {
return countLower(Root, value);
}
private int countLower(Node root, K value) {
if (root == null) return 0;
int cmp = root.value.compareTo(value);
if (cmp <= 0) return countLower(root.right, value) + getCnt(root.left) + 1;
else return countLower(root.left, value);
}
private K floor(Node root, K value) {
if (root == null) return null;
int cmp = root.value.compareTo(value);
if (cmp == 0) return root.value;
else if (cmp < 0) {
K tmp = floor(root.right, value);
if (tmp == null) return root.value;
else {
int cmp0 = tmp.compareTo(root.value);
if (cmp0 > 0) return tmp;
else return root.value;
}
} else {
return floor(root.left, value);
}
}
private K ceiling(Node root, K value) {
if (root == null) return null;
int cmp = root.value.compareTo(value);
if (cmp == 0) return value;
else if (cmp < 0) return ceiling(root.right, value);
else {
K tmp = ceiling(root.left, value);
if (tmp == null) return root.value;
else {
int cmp0 = tmp.compareTo(root.value);
if (cmp0 < 0) return tmp;
else return root.value;
}
}
}
private boolean contains(Node root, K value) {
if (root == null) return false;
int cmp = root.value.compareTo(value);
if (cmp == 0) return true;
else if (cmp < 0) return contains(root.right, value);
else return contains(root.left, value);
}
private Node remove(Node root, K value) {
int cmp = root.value.compareTo(value);
Node res = root;
if (cmp == 0) res = merge(root.left, root.right);
else if (cmp < 0) res.right = remove(root.right, value);
else res.left = remove(root.left, value);
update(res);
return res;
}
private K first(Node root) {
if (root == null) return null;
if (root.left == null) return root.value;
else return first(root.left);
}
private int getCnt(Node node) {
return node == null ? 0 : node.cnt;
}
private void update(Node node) {
if (node != null) node.cnt = getCnt(node.left) + getCnt(node.right) + 1;
}
private Node merge(Node Left, Node Right) {
if (Left == null || Right == null) {
return Left == null ? Right : Left;
} else {
if (Left.prior <= Right.prior) {
Left.right = merge(Left.right, Right);
update(Left);
return Left;
} else {
Right.left = merge(Left, Right.left);
update(Right);
return Right;
}
}
}
private Object[] split(Node Root, K key) {
if (Root == null) {
return new Object[] {null, null};
} else {
if (Root.value.compareTo(key) <= 0) {
Object tmp[] = split(Root.right, key);
Root.right = (Node)tmp[0];
update(Root);
return new Object[] {Root, (Node)tmp[1]};
} else {
Object tmp[] = split(Root.left, key);
Root.left = (Node)tmp[1];
update(Root);
return new Object[] {(Node)tmp[0], Root};
}
}
}
}
}
class testTreap implements Solver {
public void solve(int testNumber, InputReader in, PrintWriter out) {
TreeSet<Pair> set = new TreeSet<Pair>(new Comparator<Pair>() {
public int compare(Pair a, Pair b) {
int o1 = a.second - a.first + 1;
int o2 = b.second - b.first + 1;
if (o1 != o2) return o2 - o1;
return b.first - a.first;
}
} );
Structures.Tree<Pair> order = new Structures.Tree<Pair>();
int n = in.nextInt();
int q = in.nextInt();
set.add(new Pair(1, n));
order.add(new Pair(1, n));
Structures.Tree<Integer> tree = new Structures.Tree<Integer>();
tree.first();
Structures.Mapping<Integer> mapping = new Structures.Mapping<Integer> () ;
HashMap<Integer, Integer> Pointer = new HashMap<Integer, Integer> () ;
for (int qu = 0; qu < q; ++qu) {
int oper = in.nextInt();
if (oper == 0) {
int left = in.nextInt();
int right = in.nextInt();
out.println(tree.countLower(right) - tree.countLower(left - 1));
} else {
int c = mapping.getValue(oper);
if (c % 2 == 0) {
Pair tmp = set.pollFirst();
order.remove(tmp);
int mid = (tmp.first + (tmp.second - tmp.first + 1) / 2) ;
tree.add(mid);
Pointer.put(oper, mid);
if (tmp.first <= mid - 1) {
Pair ins = new Pair(tmp.first, mid - 1);
set.add(ins);
order.add(ins);
}
if (mid + 1 <= tmp.second) {
Pair ins = new Pair(mid + 1, tmp.second);
set.add(ins);
order.add(ins);
}
} else {
int m = Pointer.get(oper);
tree.remove(m);
Pair a = order.floor(new Pair(m, -1));
Pair b = order.ceiling(new Pair(m, -1));
Pair tmp = new Pair(m, m);
if (a != null) {
if (a.second + 1 == m) {
tmp.first = a.first;
order.remove(a);
set.remove(a);
}
}
if (b != null) {
if (m + 1 == b.first) {
tmp.second = b.second;
order.remove(b);
set.remove(b);
}
}
set.add(tmp);
order.add(tmp);
}
mapping.increaseValue(oper, 1);
}
}
}
class Pair implements Comparable<Pair> {
int first, second;
Pair(int first, int second) {
this.first = first;
this.second = second;
}
public int compareTo(Pair pair) {
int d = first - pair.first;
if (d != 0) return d;
return second - pair.second;
}
}
}
| Java | ["9 11\n1\n2\n0 5 8\n1\n1\n3\n0 3 8\n9\n0 6 9\n6\n0 1 9"] | 4 seconds | ["2\n3\n2\n5"] | null | Java 6 | standard input | [
"data structures"
] | 1250f103aa5fd1ac300a8a71b816b3e4 | The first line contains two integers n, q (1 ≤ n ≤ 109, 1 ≤ q ≤ 105), which are the number of hooks on the hanger and the number of requests correspondingly. Then follow q lines with requests, sorted according to time. The request of the type "0 i j" (1 ≤ i ≤ j ≤ n) — is the director's request. The input data has at least one director's request. In all other cases the request contains a positive integer not exceeding 109 — an employee identificator. Each odd appearance of the identificator of an employee in the request list is his arrival. Each even one is his leaving. All employees have distinct identificators. When any employee arrives, there is always at least one free hook. | 2,400 | For each director's request in the input data print a single number on a single line — the number of coats hanging on the hooks from the i-th one to the j-th one inclusive. | standard output | |
PASSED | 8b56382098bac6aa8eb5e3f064413b3c | train_002.jsonl | 1302879600 | In one very large and very respectable company there is a cloakroom with a coat hanger. It is represented by n hooks, positioned in a row. The hooks are numbered with positive integers from 1 to n from the left to the right.The company workers have a very complicated work schedule. At the beginning of a work day all the employees are not there and the coat hanger in the cloakroom is empty. At some moments of time the employees arrive and some of them leave.When some employee arrives, he hangs his cloak on one of the available hooks. To be of as little discomfort to his colleagues as possible, the hook where the coat will hang, is chosen like this. First the employee chooses the longest segment among available hooks following in a row. If there are several of such segments, then he chooses the one closest to the right. After that the coat is hung on the hook located in the middle of this segment. If the segment has an even number of hooks, then among two central hooks we choose the one closest to the right.When an employee leaves, he takes his coat. As all the company workers deeply respect each other, no one takes somebody else's coat.From time to time the director of this respectable company gets bored and he sends his secretary to see how many coats hang on the coat hanger from the i-th to the j-th hook inclusive. And this whim is always to be fulfilled, otherwise the director gets angry and has a mental breakdown.Not to spend too much time traversing from the director's office to the cloakroom and back again, the secretary asked you to write a program, emulating the company cloakroom's work. | 256 megabytes | import java.util.NavigableSet;
import java.util.InputMismatchException;
import java.util.Random;
import java.util.TreeSet;
import java.io.*;
import java.util.Arrays;
import java.util.HashMap;
/**
* Generated by Contest helper plug-in
* Actual solution is at the bottom
*/
public class Main {
public static void main(String[] args) {
InputReader in = new StreamInputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
run(in, out);
}
public static void run(InputReader in, PrintWriter out) {
Solver solver = new Hanger();
solver.solve(1, in, out);
Exit.exit(in, out);
}
}
class StreamInputReader extends InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar, numChars;
public StreamInputReader(InputStream stream) {
this.stream = stream;
curChar = 0;
}
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++];
}
@Override
public void close() {
try {
stream.close();
} catch (IOException ignored) {
}
}
}
abstract class InputReader {
private boolean finished = false;
public abstract int read();
public int nextInt() {
return Integer.parseInt(nextToken());
}
public String nextToken() {
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;
}
public void setFinished(boolean finished) {
this.finished = finished;
}
public abstract void close();
}
interface Solver {
public void solve(int testNumber, InputReader in, PrintWriter out);
}
class Exit {
private Exit() {
}
public static void exit(InputReader in, PrintWriter out) {
in.setFinished(true);
in.close();
out.close();
}
}
class Structures {
public static class Mapping<K> {
public HashMap<K, Integer> map;
public Mapping() {
map = new HashMap<K, Integer> () ;
}
public void increaseValue(K key, int value) {
Integer previous = map.get(key);
if (previous == null) {
map.put(key, value);
} else map.put(key, value + previous);
}
public int getValue(K key) {
Integer get = map.get(key);
return get == null ? 0 : get;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Mapping mapping = (Mapping) o;
if (map != null ? !map.equals(mapping.map) : mapping.map != null) return false;
return true;
}
@Override
public int hashCode() {
return map != null ? map.hashCode() : 0;
}
}
public static class BalancedTree {
private class Node {
int prior;
int value;
int cnt;
Node left, right;
Node(int prior, int value, int cnt, Node left, Node right) {
this.prior = prior;
this.value = value;
this.cnt = cnt;
this.left = left;
this.right = right;
}
}
private Node Root ;
private Random random;
public int getCount(int left, int right) {
int a = getCount(Root, right);
int b = getCount(Root, left - 1);
return a - b;
}
private int getCount(Node root, int right) {
if (root == null) return 0;
if (root.value <= right) return getCnt(root.left) + 1 + getCount(root.right, right);
else return getCount(root.left, right);
}
public BalancedTree() {
Root = null;
random = new Random(892375325L);
}
public void erase(int value) {
Node t[] = split(Root, value);
Node q[] = split(t[0], value - 1);
Root = merge(q[0], t[1]);
}
public void insert(int value) {
Node[] t = split(Root, value);
Root = merge(t[0], new Node(random.nextInt(), value, 1, null, null));
Root = merge(Root, t[1]);
}
private int getCnt(Node node) {
return node == null ? 0 : node.cnt;
}
private void update(Node node) {
if (node != null) node.cnt = getCnt(node.left) + getCnt(node.right) + 1;
}
private Node merge(Node Left, Node Right) {
if (Left == null || Right == null) {
return Left == null ? Right : Left;
} else {
if (Left.prior <= Right.prior) {
Left.right = merge(Left.right, Right);
update(Left);
return Left;
} else {
Right.left = merge(Left, Right.left);
update(Right);
return Right;
}
}
}
private Node[] split(Node Root, int key) {
if (Root == null) {
return new Node[] {null, null};
} else {
if (Root.value <= key) {
Node tmp[] = split(Root.right, key);
Root.right = tmp[0];
update(Root);
return new Node[] {Root, tmp[1]};
} else {
Node tmp[] = split(Root.left, key);
Root.left = tmp[1];
update(Root);
return new Node[] {tmp[0], Root};
}
}
}
}
}
class Hanger implements Solver {
public void solve(int testNumber, InputReader in, PrintWriter out) {
NavigableSet<Pair> set = new TreeSet<Pair>();
NavigableSet<AnotherPair> order = new TreeSet<AnotherPair> ();
int n = in.nextInt();
int q = in.nextInt();
set.add(new Pair(1, n));
order.add(new AnotherPair(1, n));
Structures.BalancedTree tree = new Structures.BalancedTree();
Structures.Mapping<Integer> mapping = new Structures.Mapping<Integer> () ;
HashMap<Integer, Integer> Pointer = new HashMap<Integer, Integer> () ;
for (int qu = 0; qu < q; ++qu) {
int oper = in.nextInt();
if (oper == 0) {
int left = in.nextInt();
int right = in.nextInt();
out.println(tree.getCount(left, right));
} else {
int c = mapping.getValue(oper);
if (c % 2 == 0) {
Pair tmp = set.pollFirst();
order.remove(new AnotherPair(tmp.first, tmp.second));
int mid = (tmp.first + (tmp.second - tmp.first + 1) / 2) ;
tree.insert(mid);
Pointer.put(oper, mid);
if (tmp.first <= mid - 1) {
Pair ins = new Pair(tmp.first, mid - 1);
set.add(ins);
order.add(new AnotherPair(tmp.first, mid - 1));
}
if (mid + 1 <= tmp.second) {
Pair ins = new Pair(mid + 1, tmp.second);
set.add(ins);
order.add(new AnotherPair(mid + 1, tmp.second));
}
} else {
int m = Pointer.get(oper);
tree.erase(m);
AnotherPair a = order.floor(new AnotherPair(m, -1));
AnotherPair b = order.ceiling(new AnotherPair(m, -1));
Pair tmp = new Pair(m, m);
if (a != null) {
if (a.second + 1 == m) {
tmp.first = a.first;
order.remove(a);
set.remove(new Pair(a.first, a.second));
}
}
if (b != null) {
if (m + 1 == b.first) {
tmp.second = b.second;
order.remove(b);
set.remove(new Pair(b.first, b.second));
}
}
set.add(tmp);
order.add(new AnotherPair(tmp.first, tmp.second));
}
mapping.increaseValue(oper, 1);
}
}
}
class Pair implements Comparable<Pair> {
int first, second;
Pair(int first, int second) {
this.first = first;
this.second = second;
}
public int compareTo(Pair pair) {
int o1 = second - first + 1;
int o2 = pair.second - pair.first + 1;
int d = o2 - o1;
if (d != 0) return d;
return pair.first - first;
}
}
class AnotherPair implements Comparable<AnotherPair> {
int first, second;
AnotherPair(int first, int second) {
this.first = first;
this.second = second;
}
public int compareTo(AnotherPair pair) {
int d = first - pair.first;
if (d != 0) return d;
return second - pair.second;
}
}
}
| Java | ["9 11\n1\n2\n0 5 8\n1\n1\n3\n0 3 8\n9\n0 6 9\n6\n0 1 9"] | 4 seconds | ["2\n3\n2\n5"] | null | Java 6 | standard input | [
"data structures"
] | 1250f103aa5fd1ac300a8a71b816b3e4 | The first line contains two integers n, q (1 ≤ n ≤ 109, 1 ≤ q ≤ 105), which are the number of hooks on the hanger and the number of requests correspondingly. Then follow q lines with requests, sorted according to time. The request of the type "0 i j" (1 ≤ i ≤ j ≤ n) — is the director's request. The input data has at least one director's request. In all other cases the request contains a positive integer not exceeding 109 — an employee identificator. Each odd appearance of the identificator of an employee in the request list is his arrival. Each even one is his leaving. All employees have distinct identificators. When any employee arrives, there is always at least one free hook. | 2,400 | For each director's request in the input data print a single number on a single line — the number of coats hanging on the hooks from the i-th one to the j-th one inclusive. | standard output | |
PASSED | eeae67bcf7cd8cff7bfb469cac15d5fb | train_002.jsonl | 1302879600 | In one very large and very respectable company there is a cloakroom with a coat hanger. It is represented by n hooks, positioned in a row. The hooks are numbered with positive integers from 1 to n from the left to the right.The company workers have a very complicated work schedule. At the beginning of a work day all the employees are not there and the coat hanger in the cloakroom is empty. At some moments of time the employees arrive and some of them leave.When some employee arrives, he hangs his cloak on one of the available hooks. To be of as little discomfort to his colleagues as possible, the hook where the coat will hang, is chosen like this. First the employee chooses the longest segment among available hooks following in a row. If there are several of such segments, then he chooses the one closest to the right. After that the coat is hung on the hook located in the middle of this segment. If the segment has an even number of hooks, then among two central hooks we choose the one closest to the right.When an employee leaves, he takes his coat. As all the company workers deeply respect each other, no one takes somebody else's coat.From time to time the director of this respectable company gets bored and he sends his secretary to see how many coats hang on the coat hanger from the i-th to the j-th hook inclusive. And this whim is always to be fulfilled, otherwise the director gets angry and has a mental breakdown.Not to spend too much time traversing from the director's office to the cloakroom and back again, the secretary asked you to write a program, emulating the company cloakroom's work. | 256 megabytes | import java.util.Map;
import java.util.Collections;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.math.BigInteger;
import java.util.*;
import java.util.Collection;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;
import java.util.Comparator;
import java.io.*;
import java.util.Iterator;
import java.util.Arrays;
/**
* Generated by Contest helper plug-in
* Actual solution is at the bottom
*/
public class Main {
public static void main(String[] args) {
InputReader in = new StreamInputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
run(in, out);
}
public static void run(InputReader in, PrintWriter out) {
Solver solver = new TaskDTreap();
solver.solve(1, in, out);
Exit.exit(in, out);
}
}
abstract class InputReader {
private boolean finished = false;
public abstract int read();
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuffer res = new StringBuffer();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public void setFinished(boolean finished) {
this.finished = finished;
}
public abstract void close();
}
class StreamInputReader extends InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar, numChars;
public StreamInputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
@Override
public void close() {
try {
stream.close();
} catch (IOException ignored) {
}
}
}
interface Solver {
public void solve(int testNumber, InputReader in, PrintWriter out);
}
class Exit {
private Exit() {
}
public static void exit(InputReader in, PrintWriter out) {
in.setFinished(true);
in.close();
out.close();
}
}
class Pair<U, V> {
public static class Comparator<U extends Comparable<U>, V extends Comparable<V>> implements java.util.Comparator<Pair<U, V>> {
public int compare(Pair<U, V> o1, Pair<U, V> o2) {
int result = o1.first.compareTo(o2.first);
if (result != 0)
return result;
return o1.second.compareTo(o2.second);
}
}
private final U first;
private final V second;
public Pair(U first, V second) {
this.first = first;
this.second = second;
}
public U first() {
return first;
}
public V second() {
return second;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair pair = (Pair) o;
return !(first != null ? !first.equals(pair.first) : pair.first != null) && !(second != null ? !second.equals(pair.second) : pair.second != null);
}
@Override
public int hashCode() {
int result = first != null ? first.hashCode() : 0;
result = 31 * result + (second != null ? second.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "(" + first + "," + second + ")";
}
}
class TreapSet<K> implements NavigableSet<K> {
private static final Random rnd = new Random(239);
private final Node nullNode;
private final Comparator<? super K> comparator;
private Node root;
private final K from;
private final K to;
private final boolean fromInclusive;
private final boolean toInclusive;
public TreapSet() {
this((Comparator<? super K>)null);
}
public TreapSet(Comparator<? super K> comparator) {
this(null, null, false, false, comparator, null, null);
}
public TreapSet(Iterable<? extends K> collection) {
this(collection, null);
}
public TreapSet(Iterable<? extends K> collection, Comparator<? super K> comparator) {
this(comparator);
addAll(collection);
}
private TreapSet(K from, K to, boolean fromInclusive, boolean toInclusive, Comparator<? super K> comparator, Node root, Node nullNode) {
this.comparator = comparator;
this.from = from;
this.to = to;
this.fromInclusive = fromInclusive;
this.toInclusive = toInclusive;
if (nullNode == null)
nullNode = new NullNode();
if (root == null)
root = nullNode;
this.root = root;
this.nullNode = nullNode;
}
public boolean addAll(Iterable<? extends K> collection) {
boolean result = false;
for (K element : collection)
result |= add(element);
return result;
}
public K lower(K k) {
Node target = root.lower(k);
if (target == nullNode)
return null;
if (belongs(target.key))
return target.key;
return null;
}
private boolean belongs(K key) {
int valueFrom = compare(from, key);
int valueTo = compare(key, to);
return (valueFrom < 0 || valueFrom == 0 && fromInclusive) && (valueTo < 0 || valueTo == 0 && toInclusive);
}
public K floor(K k) {
Node target = root.floor(k);
if (target == nullNode)
return null;
if (belongs(target.key))
return target.key;
return null;
}
public K ceiling(K k) {
Node target = root.ceil(k);
if (target == nullNode)
return null;
if (belongs(target.key))
return target.key;
return null;
}
public K higher(K k) {
Node target = root.higher(k);
if (target == nullNode)
return null;
if (belongs(target.key))
return target.key;
return null;
}
public K pollFirst() {
K first = first();
if (first == null)
throw new NoSuchElementException();
root.erase(first);
return first;
}
public K pollLast() {
K last = last();
if (last == null)
throw new NoSuchElementException();
root.erase(last);
return last;
}
public int size() {
if (from == null && to == null)
return root.size;
if (from == null) {
Node to = toInclusive ? root.floor(this.to) : root.lower(this.to);
if (to == nullNode)
return 0;
return root.indexOf(to) + 1;
}
if (to == null) {
Node from = fromInclusive ? root.ceil(this.from) : root.higher(this.from);
if (from == nullNode)
return 0;
return root.size - root.indexOf(from);
}
Node from = fromInclusive ? root.ceil(this.from) : root.higher(this.from);
if (from == nullNode || !belongs(from.key))
return 0;
Node to = toInclusive ? root.floor(this.to) : root.lower(this.to);
return root.indexOf(to) - root.indexOf(from) + 1;
}
public boolean isEmpty() {
return size() == 0;
}
@SuppressWarnings({"unchecked"})
public boolean contains(Object o) {
return belongs((K) o) && root.search((K) o) != nullNode;
}
public Iterator<K> iterator() {
return new Iterator<K>() {
private K current = first();
public boolean hasNext() {
return current != null;
}
public K next() {
K result = current;
current = higher(current);
return result;
}
public void remove() {
TreapSet.this.remove(current);
}
};
}
public Object[] toArray() {
Object[] array = new Object[size()];
int index = 0;
for (K key : this)
array[index++] = key;
return array;
}
@SuppressWarnings({"unchecked"})
public <T> T[] toArray(T[] a) {
if (a.length < size())
throw new IllegalArgumentException();
int index = 0;
for (K key : this)
a[index++] = (T) key;
return a;
}
public boolean add(K k) {
if (k == null)
throw new NullPointerException();
if (contains(k))
return false;
root = root.insert(new Node(k, rnd.nextLong()));
return true;
}
public boolean remove(Object o) {
if (!contains(o))
return false;
//noinspection unchecked
root = root.erase((K) o);
return true;
}
public boolean containsAll(Collection<?> c) {
for (Object o : c) {
if (!contains(o))
return false;
}
return true;
}
public boolean addAll(Collection<? extends K> c) {
return addAll((Iterable<? extends K>)c);
}
public boolean retainAll(Collection<?> c) {
List<K> toRemove = new ArrayList<K>();
for (K key : this) {
if (!c.contains(key))
toRemove.add(key);
}
return removeAll(toRemove);
}
public boolean removeAll(Collection<?> c) {
boolean result = false;
for (Object o : c)
result |= remove(o);
return result;
}
public void clear() {
retainAll(Collections.<Object>emptySet());
}
public NavigableSet<K> descendingSet() {
throw new UnsupportedOperationException();
}
public Iterator<K> descendingIterator() {
return new Iterator<K>() {
private K current = last();
public boolean hasNext() {
return current != null;
}
public K next() {
K result = current;
current = lower(current);
return result;
}
public void remove() {
TreapSet.this.remove(current);
}
};
}
public NavigableSet<K> subSet(K fromElement, boolean fromInclusive, K toElement, boolean toInclusive) {
return new TreapSet<K>(fromElement, toElement, fromInclusive, toInclusive, comparator, root, nullNode);
}
public NavigableSet<K> headSet(K toElement, boolean inclusive) {
return subSet(null, false, toElement, inclusive);
}
public NavigableSet<K> tailSet(K fromElement, boolean inclusive) {
return subSet(fromElement, inclusive, null, false);
}
public Comparator<? super K> comparator() {
return comparator;
}
public SortedSet<K> subSet(K fromElement, K toElement) {
return subSet(fromElement, true, toElement, false);
}
public SortedSet<K> headSet(K toElement) {
return subSet(null, false, toElement, false);
}
public SortedSet<K> tailSet(K fromElement) {
return tailSet(fromElement, true);
}
public K first() {
if (isEmpty())
return null;
if (from == null)
return root.first().key;
if (fromInclusive)
return ceiling(from);
return higher(from);
}
public K last() {
if (isEmpty())
return null;
if (to == null)
return root.last().key;
if (toInclusive)
return floor(to);
return lower(to);
}
private int compare(K first, K second) {
if (first == null || second == null)
return -1;
if (comparator != null)
return comparator.compare(first, second);
//noinspection unchecked
return ((Comparable<? super K>)first).compareTo(second);
}
private class Node {
private final K key;
private final long priority;
protected Node left;
protected Node right;
protected int size;
protected Node(K key, long priority) {
this.key = key;
this.priority = priority;
left = nullNode;
right = nullNode;
size = 1;
}
@SuppressWarnings({"unchecked"})
protected Object[] split(K key) {
if (compare(key, this.key) < 0) {
Object[] result = left.split(key);
left = (Node) result[1];
result[1] = this;
updateSize();
return result;
}
Object[] result = right.split(key);
right = (Node) result[0];
result[0] = this;
updateSize();
return result;
}
protected void updateSize() {
size = left.size + right.size + 1;
}
@SuppressWarnings({"unchecked"})
protected Node insert(Node node) {
if (node.priority > priority) {
Object[] result = split(node.key);
node.left = (Node) result[0];
node.right = (Node) result[1];
node.updateSize();
return node;
}
if (compare(node.key, this.key) < 0) {
left = left.insert(node);
updateSize();
return this;
}
right = right.insert(node);
updateSize();
return this;
}
protected Node merge(Node left, Node right) {
if (left == nullNode)
return right;
if (right == nullNode)
return left;
if (left.priority > right.priority) {
left.right = left.right.merge(left.right, right);
left.updateSize();
return left;
}
right.left = right.left.merge(left, right.left);
right.updateSize();
return right;
}
protected Node erase(K key) {
int value = compare(key, this.key);
if (value == 0)
return merge(left, right);
if (value < 0) {
left = left.erase(key);
updateSize();
return this;
}
right = right.erase(key);
updateSize();
return this;
}
protected Node lower(K key) {
if (compare(key, this.key) <= 0)
return left.lower(key);
Node result = right.lower(key);
if (result == nullNode)
return this;
return result;
}
protected Node floor(K key) {
if (compare(key, this.key) < 0)
return left.floor(key);
Node result = right.floor(key);
if (result == nullNode)
return this;
return result;
}
protected Node higher(K key) {
if (compare(key, this.key) >= 0)
return right.higher(key);
Node result = left.higher(key);
if (result == nullNode)
return this;
return result;
}
protected Node ceil(K key) {
if (compare(key, this.key) > 0)
return right.ceil(key);
Node result = left.ceil(key);
if (result == nullNode)
return this;
return result;
}
protected Node first() {
if (left == nullNode)
return this;
return left.first();
}
protected Node last() {
if (right == nullNode)
return this;
return right.last();
}
protected Node search(K key) {
int value = compare(key, this.key);
if (value == 0)
return this;
if (value < 0)
return left.search(key);
return right.search(key);
}
public int indexOf(Node node) {
if (this == node)
return left.size;
if (compare(node.key, this.key) > 0)
return left.size + 1 + right.indexOf(node);
return left.indexOf(node);
}
}
private class NullNode extends Node {
private NullNode() {
super(null, Long.MIN_VALUE);
left = this;
right = this;
size = 0;
}
@Override
protected Object[] split(K key) {
return new Object[]{this, this};
}
@Override
protected Node insert(Node node) {
return node;
}
@Override
protected Node erase(K key) {
return this;
}
@Override
protected Node lower(K key) {
return this;
}
@Override
protected Node floor(K key) {
return this;
}
@Override
protected Node higher(K key) {
return this;
}
@Override
protected Node ceil(K key) {
return this;
}
@Override
protected Node first() {
throw new NoSuchElementException();
}
@Override
protected Node last() {
throw new NoSuchElementException();
}
@Override
protected void updateSize() {
}
@Override
protected Node search(K key) {
return this;
}
}
}
class IntegerUtils {
public static int longCompare(long a, long b) {
if (a < b)
return -1;
if (a > b)
return 1;
return 0;
}
}
class TaskDTreap implements Solver {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int count = in.readInt();
int queryCount = in.readInt();
NavigableSet<Pair<Long, Long>> byLength = new TreeSet<Pair<Long, Long>>(new Comparator<Pair<Long, Long>>() {
public int compare(Pair<Long, Long> o1, Pair<Long, Long> o2) {
long length1 = o1.second() - o1.first();
long length2 = o2.second() - o2.first();
int value = IntegerUtils.longCompare(length1, length2);
if (value != 0)
return -value;
return IntegerUtils.longCompare(o2.first(), o1.first());
}
});
NavigableSet<Pair<Long, Long>> byOrder = new TreeSet<Pair<Long, Long>>(new Pair.Comparator<Long, Long>());
Pair<Long, Long> all = new Pair<Long, Long>(1L, (long)count);
byLength.add(all);
byOrder.add(all);
Map<Integer, Integer> atWork = new HashMap<Integer, Integer>();
NavigableSet<Integer> occupied = new TreapSet<Integer>();
for (int it = 0; it < queryCount; it++) {
int employee = in.readInt();
if (employee == 0) {
int from = in.readInt();
int to = in.readInt();
out.println(occupied.subSet(from, true, to, true).size());
} else {
if (!atWork.containsKey(employee)) {
int position = add(byLength, byOrder);
atWork.put(employee, position);
occupied.add(position);
} else {
int position = atWork.get(employee);
remove(byLength, byOrder, position);
atWork.remove(employee);
occupied.remove(position);
}
}
}
}
private void remove(NavigableSet<Pair<Long, Long>> byLength, NavigableSet<Pair<Long, Long>> byOrder, long position) {
Pair<Long, Long> toTest = new Pair<Long, Long>(position, position);
Pair<Long, Long> left = null;
SortedSet<Pair<Long, Long>> headSet = byOrder.headSet(toTest);
if (!headSet.isEmpty())
left = headSet.last();
if (left != null && left.second() + 1 != position)
left = null;
Pair<Long, Long> right = null;
SortedSet<Pair<Long, Long>> tailSet = byOrder.tailSet(toTest);
if (!tailSet.isEmpty())
right = tailSet.first();
if (right != null && right.first() - 1 != position)
right = null;
if (left != null) {
byLength.remove(left);
byOrder.remove(left);
}
if (right != null) {
byLength.remove(right);
byOrder.remove(right);
}
Pair<Long, Long> toAdd = new Pair<Long, Long>(left != null ? left.first() : position, right != null ? right.second() : position);
byLength.add(toAdd);
byOrder.add(toAdd);
}
private int add(NavigableSet<Pair<Long, Long>> byLength, NavigableSet<Pair<Long, Long>> byOrder) {
Pair<Long, Long> toDivide = byLength.first();
byLength.remove(toDivide);
byOrder.remove(toDivide);
long position = (toDivide.first() + toDivide.second() + 1) / 2;
Pair<Long, Long> left = new Pair<Long, Long>(toDivide.first(), position - 1);
Pair<Long, Long> right = new Pair<Long, Long>(position + 1, toDivide.second());
if (left.first() <= left.second()) {
byLength.add(left);
byOrder.add(left);
}
if (right.first() <= right.second()) {
byLength.add(right);
byOrder.add(right);
}
return (int) position;
}
}
| Java | ["9 11\n1\n2\n0 5 8\n1\n1\n3\n0 3 8\n9\n0 6 9\n6\n0 1 9"] | 4 seconds | ["2\n3\n2\n5"] | null | Java 6 | standard input | [
"data structures"
] | 1250f103aa5fd1ac300a8a71b816b3e4 | The first line contains two integers n, q (1 ≤ n ≤ 109, 1 ≤ q ≤ 105), which are the number of hooks on the hanger and the number of requests correspondingly. Then follow q lines with requests, sorted according to time. The request of the type "0 i j" (1 ≤ i ≤ j ≤ n) — is the director's request. The input data has at least one director's request. In all other cases the request contains a positive integer not exceeding 109 — an employee identificator. Each odd appearance of the identificator of an employee in the request list is his arrival. Each even one is his leaving. All employees have distinct identificators. When any employee arrives, there is always at least one free hook. | 2,400 | For each director's request in the input data print a single number on a single line — the number of coats hanging on the hooks from the i-th one to the j-th one inclusive. | standard output | |
PASSED | 3b928170b6f969e2399158cf1dd449b8 | train_002.jsonl | 1302879600 | In one very large and very respectable company there is a cloakroom with a coat hanger. It is represented by n hooks, positioned in a row. The hooks are numbered with positive integers from 1 to n from the left to the right.The company workers have a very complicated work schedule. At the beginning of a work day all the employees are not there and the coat hanger in the cloakroom is empty. At some moments of time the employees arrive and some of them leave.When some employee arrives, he hangs his cloak on one of the available hooks. To be of as little discomfort to his colleagues as possible, the hook where the coat will hang, is chosen like this. First the employee chooses the longest segment among available hooks following in a row. If there are several of such segments, then he chooses the one closest to the right. After that the coat is hung on the hook located in the middle of this segment. If the segment has an even number of hooks, then among two central hooks we choose the one closest to the right.When an employee leaves, he takes his coat. As all the company workers deeply respect each other, no one takes somebody else's coat.From time to time the director of this respectable company gets bored and he sends his secretary to see how many coats hang on the coat hanger from the i-th to the j-th hook inclusive. And this whim is always to be fulfilled, otherwise the director gets angry and has a mental breakdown.Not to spend too much time traversing from the director's office to the cloakroom and back again, the secretary asked you to write a program, emulating the company cloakroom's work. | 256 megabytes | import java.util.Map;
import java.util.Collections;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.math.BigInteger;
import java.util.*;
import java.util.Collection;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;
import java.util.Comparator;
import java.io.*;
import java.util.Iterator;
import java.util.Arrays;
/**
* Generated by Contest helper plug-in
* Actual solution is at the bottom
*/
public class Main {
public static void main(String[] args) {
InputReader in = new StreamInputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
run(in, out);
}
public static void run(InputReader in, PrintWriter out) {
Solver solver = new TaskD();
solver.solve(1, in, out);
Exit.exit(in, out);
}
}
abstract class InputReader {
private boolean finished = false;
public abstract int read();
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuffer res = new StringBuffer();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public void setFinished(boolean finished) {
this.finished = finished;
}
public abstract void close();
}
class StreamInputReader extends InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar, numChars;
public StreamInputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
@Override
public void close() {
try {
stream.close();
} catch (IOException ignored) {
}
}
}
interface Solver {
public void solve(int testNumber, InputReader in, PrintWriter out);
}
class Exit {
private Exit() {
}
public static void exit(InputReader in, PrintWriter out) {
in.setFinished(true);
in.close();
out.close();
}
}
class Pair<U, V> {
public static class Comparator<U extends Comparable<U>, V extends Comparable<V>> implements java.util.Comparator<Pair<U, V>> {
public int compare(Pair<U, V> o1, Pair<U, V> o2) {
int result = o1.first.compareTo(o2.first);
if (result != 0)
return result;
return o1.second.compareTo(o2.second);
}
}
private final U first;
private final V second;
public Pair(U first, V second) {
this.first = first;
this.second = second;
}
public U first() {
return first;
}
public V second() {
return second;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair pair = (Pair) o;
return !(first != null ? !first.equals(pair.first) : pair.first != null) && !(second != null ? !second.equals(pair.second) : pair.second != null);
}
@Override
public int hashCode() {
int result = first != null ? first.hashCode() : 0;
result = 31 * result + (second != null ? second.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "(" + first + "," + second + ")";
}
}
class SumIntervalTree {
private int[] left;
private int[] right;
private long[] value;
private long[] delta;
public SumIntervalTree(int size) {
int arraysSize = Math.max(1, Integer.highestOneBit(size) * 4);
left = new int[arraysSize];
right = new int[arraysSize];
value = new long[arraysSize];
delta = new long[arraysSize];
initTree(0, size, 0);
}
private void initTree(int left, int right, int root) {
this.left[root] = left;
this.right[root] = right;
if (right - left > 1) {
initTree(left, (left + right + 1) / 2, 2 * root + 1);
initTree((left + right + 1) / 2, right, 2 * root + 2);
}
}
private int intersection(int left, int right, int root) {
return Math.min(right, this.right[root]) - Math.max(left, this.left[root]);
}
public void put(int position, long value) {
put(position, value, 0);
}
private void put(int position, long value, int root) {
if (left[root] > position || right[root] <= position)
return;
this.value[root] += value;
if (right[root] - left[root] > 1) {
put(position, value, 2 * root + 1);
put(position, value, 2 * root + 2);
} else
this.delta[root] += value;
}
public long getSegment(int left, int right) {
return getSegment(left, right, 0);
}
private long getSegment(int left, int right, int root) {
if (left >= this.right[root] || right <= this.left[root])
return 0;
if (left <= this.left[root] && right >= this.right[root])
return value[root];
return getSegment(left, right, 2 * root + 1) + getSegment(left, right, 2 * root + 2) + delta[root] *
intersection(left, right, root);
}
}
class IntegerUtils {
public static int longCompare(long a, long b) {
if (a < b)
return -1;
if (a > b)
return 1;
return 0;
}
}
class TaskD implements Solver {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int count = in.readInt();
int queryCount = in.readInt();
NavigableSet<Pair<Long, Long>> byLength = new TreeSet<Pair<Long, Long>>(new Comparator<Pair<Long, Long>>() {
public int compare(Pair<Long, Long> o1, Pair<Long, Long> o2) {
long length1 = o1.second() - o1.first();
long length2 = o2.second() - o2.first();
int value = IntegerUtils.longCompare(length1, length2);
if (value != 0)
return -value;
return IntegerUtils.longCompare(o2.first(), o1.first());
}
});
NavigableSet<Pair<Long, Long>> byOrder = new TreeSet<Pair<Long, Long>>(new Pair.Comparator<Long, Long>());
Pair<Long, Long> all = new Pair<Long, Long>(1L, (long)count);
byLength.add(all);
byOrder.add(all);
Map<Integer, Integer> atWork = new HashMap<Integer, Integer>();
int[] employee = new int[queryCount];
int[] from = new int[queryCount];
int[] to = new int[queryCount];
NavigableMap<Integer, Integer> possibleLocations = new TreeMap<Integer, Integer>();
for (int it = 0; it < queryCount; it++) {
employee[it] = in.readInt();
if (employee[it] == 0) {
from[it] = in.readInt();
to[it] = in.readInt();
} else {
if (!atWork.containsKey(employee[it])) {
int position = add(byLength, byOrder);
atWork.put(employee[it], position);
possibleLocations.put(position, 0);
} else {
remove(byLength, byOrder, atWork.get(employee[it]));
atWork.remove(employee[it]);
}
}
}
int index = 0;
for (Map.Entry<Integer, Integer> entry : possibleLocations.entrySet())
entry.setValue(index++);
SumIntervalTree tree = new SumIntervalTree(index);
byLength.clear();
byOrder.clear();
atWork.clear();
byLength.add(all);
byOrder.add(all);
for (int it = 0; it < queryCount; it++) {
if (employee[it] == 0) {
NavigableMap<Integer, Integer> segment = possibleLocations.tailMap(from[it], true).headMap(to[it], true);
if (segment.isEmpty())
out.println(0);
else
out.println(tree.getSegment(segment.firstEntry().getValue(), segment.lastEntry().getValue() + 1));
} else {
if (!atWork.containsKey(employee[it])) {
int position = add(byLength, byOrder);
atWork.put(employee[it], position);
tree.put(possibleLocations.get(position), 1);
} else {
int position = atWork.get(employee[it]);
remove(byLength, byOrder, position);
tree.put(possibleLocations.get(position), -1);
atWork.remove(employee[it]);
}
}
}
}
private void remove(NavigableSet<Pair<Long, Long>> byLength, NavigableSet<Pair<Long, Long>> byOrder, long position) {
Pair<Long, Long> toTest = new Pair<Long, Long>(position, position);
Pair<Long, Long> left = null;
SortedSet<Pair<Long, Long>> headSet = byOrder.headSet(toTest);
if (!headSet.isEmpty())
left = headSet.last();
if (left != null && left.second() + 1 != position)
left = null;
Pair<Long, Long> right = null;
SortedSet<Pair<Long, Long>> tailSet = byOrder.tailSet(toTest);
if (!tailSet.isEmpty())
right = tailSet.first();
if (right != null && right.first() - 1 != position)
right = null;
if (left != null) {
byLength.remove(left);
byOrder.remove(left);
}
if (right != null) {
byLength.remove(right);
byOrder.remove(right);
}
Pair<Long, Long> toAdd = new Pair<Long, Long>(left != null ? left.first() : position, right != null ? right.second() : position);
byLength.add(toAdd);
byOrder.add(toAdd);
}
private int add(NavigableSet<Pair<Long, Long>> byLength, NavigableSet<Pair<Long, Long>> byOrder) {
Pair<Long, Long> toDivide = byLength.first();
byLength.remove(toDivide);
byOrder.remove(toDivide);
long position = (toDivide.first() + toDivide.second() + 1) / 2;
Pair<Long, Long> left = new Pair<Long, Long>(toDivide.first(), position - 1);
Pair<Long, Long> right = new Pair<Long, Long>(position + 1, toDivide.second());
if (left.first() <= left.second()) {
byLength.add(left);
byOrder.add(left);
}
if (right.first() <= right.second()) {
byLength.add(right);
byOrder.add(right);
}
return (int) position;
}
}
| Java | ["9 11\n1\n2\n0 5 8\n1\n1\n3\n0 3 8\n9\n0 6 9\n6\n0 1 9"] | 4 seconds | ["2\n3\n2\n5"] | null | Java 6 | standard input | [
"data structures"
] | 1250f103aa5fd1ac300a8a71b816b3e4 | The first line contains two integers n, q (1 ≤ n ≤ 109, 1 ≤ q ≤ 105), which are the number of hooks on the hanger and the number of requests correspondingly. Then follow q lines with requests, sorted according to time. The request of the type "0 i j" (1 ≤ i ≤ j ≤ n) — is the director's request. The input data has at least one director's request. In all other cases the request contains a positive integer not exceeding 109 — an employee identificator. Each odd appearance of the identificator of an employee in the request list is his arrival. Each even one is his leaving. All employees have distinct identificators. When any employee arrives, there is always at least one free hook. | 2,400 | For each director's request in the input data print a single number on a single line — the number of coats hanging on the hooks from the i-th one to the j-th one inclusive. | standard output | |
PASSED | 188c8b12b9ad359b3836112d907f8324 | train_002.jsonl | 1302879600 | In one very large and very respectable company there is a cloakroom with a coat hanger. It is represented by n hooks, positioned in a row. The hooks are numbered with positive integers from 1 to n from the left to the right.The company workers have a very complicated work schedule. At the beginning of a work day all the employees are not there and the coat hanger in the cloakroom is empty. At some moments of time the employees arrive and some of them leave.When some employee arrives, he hangs his cloak on one of the available hooks. To be of as little discomfort to his colleagues as possible, the hook where the coat will hang, is chosen like this. First the employee chooses the longest segment among available hooks following in a row. If there are several of such segments, then he chooses the one closest to the right. After that the coat is hung on the hook located in the middle of this segment. If the segment has an even number of hooks, then among two central hooks we choose the one closest to the right.When an employee leaves, he takes his coat. As all the company workers deeply respect each other, no one takes somebody else's coat.From time to time the director of this respectable company gets bored and he sends his secretary to see how many coats hang on the coat hanger from the i-th to the j-th hook inclusive. And this whim is always to be fulfilled, otherwise the director gets angry and has a mental breakdown.Not to spend too much time traversing from the director's office to the cloakroom and back again, the secretary asked you to write a program, emulating the company cloakroom's work. | 256 megabytes |
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.util.HashMap;
import java.util.TreeMap;
import java.util.TreeSet;
public class Hanger {
class Segment implements Comparable<Segment> {
int left, right, len;
Segment(int l, int r) {
left = l;
right = r;
len = r-l+ 1;
}
public int compareTo(Segment oth) {
if (len > oth.len)
return -1;
if (len==oth.len&&right > oth.right)
return -1;
if(left==oth.left&&right==oth.right)
return 0;
return 1;
}
}
class IndexTree {
TreeMap<Integer, Integer> mp = new TreeMap<Integer, Integer>();
int N =(1<<30)- 1;
int lowbit(int k) {
return (k & -k);
}
void inc(int i, int v) {
while (i <= N) {
Integer num = mp.get(i);
if (num == null)
num = 0;
mp.put(i, num + v);
i += lowbit(i);
}
}
int get(int i) {
int res = 0;
while (i > 0) {
Integer num = mp.get(i);
if (num == null)
num = 0;
res += num;
i -= lowbit(i);
}
return res;
}
int query(int left, int right) {
return get(right) - get(left - 1);
}
}
IndexTree tree = new IndexTree();
TreeSet<Segment> segs = new TreeSet<Segment>();
HashMap<Integer, Integer> arrive = new HashMap<Integer, Integer>();
HashMap<Integer, Segment> left = new HashMap<Integer, Segment>();
HashMap<Integer, Segment> right = new HashMap<Integer, Segment>();
void run() throws IOException {
int n = nextInt();
int m = nextInt();
segs.add(new Segment(1, n));
for (int i = 0; i < m; i++) {
int x = nextInt();
if (x == 0) {
out.println(tree.query(nextInt(),nextInt()));
continue;
}
if (!arrive.containsKey(x)) {
Segment seg = segs.pollFirst();
int ans = seg.left + seg.len / 2;
arrive.put(x, ans);
tree.inc(ans, 1);
left.remove(ans);
right.remove(ans);
if (ans != seg.left) {
Segment sg = new Segment(seg.left, ans - 1);
segs.add(sg);
left.put(ans - 1,sg);
right.put(seg.left, sg);
}
if (ans != seg.right) {
Segment sg = new Segment(ans + 1, seg.right);
segs.add(sg);
left.put(seg.right, sg);
right.put(ans + 1, sg);
}
} else {
int tx =x;
x=arrive.get(x);
arrive.remove(tx);
tree.inc(x, -1);
Segment sl = left.get(x - 1), sr = right.get(x + 1);
int a = x, b = x;
if (sl != null) {
a = sl.left;
segs.remove(sl);
}
if (sr != null) {
b = sr.right;
segs.remove(sr);
}
Segment sg = new Segment(a, b);
segs.add(sg);
left.put(b,sg);
right.put(a, sg);
}
}
out.close();
}
StreamTokenizer in = new StreamTokenizer(new BufferedReader(
new InputStreamReader(System.in)));
int nextInt() throws IOException {
in.nextToken();
return (int) in.nval;
}
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
public static void main(String[] args) throws IOException {
new Hanger().run();
}
}
| Java | ["9 11\n1\n2\n0 5 8\n1\n1\n3\n0 3 8\n9\n0 6 9\n6\n0 1 9"] | 4 seconds | ["2\n3\n2\n5"] | null | Java 6 | standard input | [
"data structures"
] | 1250f103aa5fd1ac300a8a71b816b3e4 | The first line contains two integers n, q (1 ≤ n ≤ 109, 1 ≤ q ≤ 105), which are the number of hooks on the hanger and the number of requests correspondingly. Then follow q lines with requests, sorted according to time. The request of the type "0 i j" (1 ≤ i ≤ j ≤ n) — is the director's request. The input data has at least one director's request. In all other cases the request contains a positive integer not exceeding 109 — an employee identificator. Each odd appearance of the identificator of an employee in the request list is his arrival. Each even one is his leaving. All employees have distinct identificators. When any employee arrives, there is always at least one free hook. | 2,400 | For each director's request in the input data print a single number on a single line — the number of coats hanging on the hooks from the i-th one to the j-th one inclusive. | standard output | |
PASSED | 8d49d19d5c9cafc7eeff73d9ccf61c16 | train_002.jsonl | 1302879600 | In one very large and very respectable company there is a cloakroom with a coat hanger. It is represented by n hooks, positioned in a row. The hooks are numbered with positive integers from 1 to n from the left to the right.The company workers have a very complicated work schedule. At the beginning of a work day all the employees are not there and the coat hanger in the cloakroom is empty. At some moments of time the employees arrive and some of them leave.When some employee arrives, he hangs his cloak on one of the available hooks. To be of as little discomfort to his colleagues as possible, the hook where the coat will hang, is chosen like this. First the employee chooses the longest segment among available hooks following in a row. If there are several of such segments, then he chooses the one closest to the right. After that the coat is hung on the hook located in the middle of this segment. If the segment has an even number of hooks, then among two central hooks we choose the one closest to the right.When an employee leaves, he takes his coat. As all the company workers deeply respect each other, no one takes somebody else's coat.From time to time the director of this respectable company gets bored and he sends his secretary to see how many coats hang on the coat hanger from the i-th to the j-th hook inclusive. And this whim is always to be fulfilled, otherwise the director gets angry and has a mental breakdown.Not to spend too much time traversing from the director's office to the cloakroom and back again, the secretary asked you to write a program, emulating the company cloakroom's work. | 256 megabytes |
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.util.HashMap;
import java.util.TreeMap;
import java.util.TreeSet;
public class Hanger {
class Segment implements Comparable<Segment> {
int left, right, len;
Segment(int l, int r) {
left = l;
right = r;
len = r-l+ 1;
}
public int compareTo(Segment oth) {
if (len > oth.len)
return -1;
if (len==oth.len&&right > oth.right)
return -1;
if(left==oth.left&&right==oth.right)
return 0;
return 1;
}
}
class IndexTree {
TreeMap<Integer, Integer> mp = new TreeMap<Integer, Integer>();
int N =(1<<30)- 1;
int lowbit(int k) {
return (k & -k);
}
void inc(int i, int v) {
while (i <= N) {
Integer num = mp.get(i);
if (num == null)
num = 0;
mp.put(i, num + v);
i += lowbit(i);
}
}
int get(int i) {
int res = 0;
while (i > 0) {
Integer num = mp.get(i);
if (num == null)
num = 0;
res += num;
i -= lowbit(i);
}
return res;
}
int query(int left, int right) {
return get(right) - get(left - 1);
}
}
IndexTree tree = new IndexTree();
TreeSet<Segment> segs = new TreeSet<Segment>();
TreeMap<Integer, Integer> arrive = new TreeMap<Integer, Integer>();
HashMap<Integer, Integer> left = new HashMap<Integer, Integer>();
HashMap<Integer, Segment> right = new HashMap<Integer, Segment>();
void run() throws IOException {
int n = nextInt();
int m = nextInt();
segs.add(new Segment(1, n));
for (int i = 0; i < m; i++) {
int x = nextInt();
if (x == 0) {
out.println(tree.query(nextInt(),nextInt()));
continue;
}
if (!arrive.containsKey(x)) {
Segment seg = segs.pollFirst();
int ans = seg.left + seg.len / 2;
arrive.put(x, ans);
tree.inc(ans, 1);
left.put(ans, ans);
right.put(ans, null);
if (ans != seg.left) {
Segment sg = new Segment(seg.left, ans - 1);
segs.add(sg);
left.put(ans - 1, seg.left);
right.put(seg.left, sg);
}
if (ans != seg.right) {
Segment sg = new Segment(ans + 1, seg.right);
segs.add(sg);
left.put(seg.right, ans + 1);
right.put(ans + 1, sg);
}
} else {
int tx =x;
x=arrive.get(x);
arrive.remove(tx);
tree.inc(x, -1);
Segment sl = right.get(left.get(x - 1)), sr = right.get(x + 1);
int a = x, b = x;
if (sl != null) {
a = sl.left;
segs.remove(sl);
}
if (sr != null) {
b = sr.right;
segs.remove(sr);
}
Segment sg = new Segment(a, b);
segs.add(sg);
left.put(b, a);
right.put(a, sg);
}
}
out.close();
}
StreamTokenizer in = new StreamTokenizer(new BufferedReader(
new InputStreamReader(System.in)));
int nextInt() throws IOException {
in.nextToken();
return (int) in.nval;
}
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
public static void main(String[] args) throws IOException {
new Hanger().run();
}
}
| Java | ["9 11\n1\n2\n0 5 8\n1\n1\n3\n0 3 8\n9\n0 6 9\n6\n0 1 9"] | 4 seconds | ["2\n3\n2\n5"] | null | Java 6 | standard input | [
"data structures"
] | 1250f103aa5fd1ac300a8a71b816b3e4 | The first line contains two integers n, q (1 ≤ n ≤ 109, 1 ≤ q ≤ 105), which are the number of hooks on the hanger and the number of requests correspondingly. Then follow q lines with requests, sorted according to time. The request of the type "0 i j" (1 ≤ i ≤ j ≤ n) — is the director's request. The input data has at least one director's request. In all other cases the request contains a positive integer not exceeding 109 — an employee identificator. Each odd appearance of the identificator of an employee in the request list is his arrival. Each even one is his leaving. All employees have distinct identificators. When any employee arrives, there is always at least one free hook. | 2,400 | For each director's request in the input data print a single number on a single line — the number of coats hanging on the hooks from the i-th one to the j-th one inclusive. | standard output | |
PASSED | d71ba7c1c270c8c5325744ff37d83abd | train_002.jsonl | 1302879600 | In one very large and very respectable company there is a cloakroom with a coat hanger. It is represented by n hooks, positioned in a row. The hooks are numbered with positive integers from 1 to n from the left to the right.The company workers have a very complicated work schedule. At the beginning of a work day all the employees are not there and the coat hanger in the cloakroom is empty. At some moments of time the employees arrive and some of them leave.When some employee arrives, he hangs his cloak on one of the available hooks. To be of as little discomfort to his colleagues as possible, the hook where the coat will hang, is chosen like this. First the employee chooses the longest segment among available hooks following in a row. If there are several of such segments, then he chooses the one closest to the right. After that the coat is hung on the hook located in the middle of this segment. If the segment has an even number of hooks, then among two central hooks we choose the one closest to the right.When an employee leaves, he takes his coat. As all the company workers deeply respect each other, no one takes somebody else's coat.From time to time the director of this respectable company gets bored and he sends his secretary to see how many coats hang on the coat hanger from the i-th to the j-th hook inclusive. And this whim is always to be fulfilled, otherwise the director gets angry and has a mental breakdown.Not to spend too much time traversing from the director's office to the cloakroom and back again, the secretary asked you to write a program, emulating the company cloakroom's work. | 256 megabytes |
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.util.HashMap;
import java.util.TreeMap;
import java.util.TreeSet;
public class Hanger {
class Segment implements Comparable<Segment> {
int left, right, len;
Segment(int l, int r) {
left = l;
right = r;
len = r-l+ 1;
}
public int compareTo(Segment oth) {
if (len > oth.len)
return -1;
if (len==oth.len&&right > oth.right)
return -1;
if(left==oth.left&&right==oth.right)
return 0;
return 1;
}
}
class IndexTree {
HashMap<Integer, Integer> mp = new HashMap<Integer, Integer>();
int N =(1<<30)- 1;
int lowbit(int k) {
return (k & -k);
}
void inc(int i, int v) {
while (i <= N) {
Integer num = mp.get(i);
if (num == null)
num = 0;
mp.put(i, num + v);
i += lowbit(i);
}
}
int get(int i) {
int res = 0;
while (i > 0) {
Integer num = mp.get(i);
if (num == null)
num = 0;
res += num;
i -= lowbit(i);
}
return res;
}
int query(int left, int right) {
return get(right) - get(left - 1);
}
}
IndexTree tree = new IndexTree();
TreeSet<Segment> segs = new TreeSet<Segment>();
HashMap<Integer, Integer> arrive = new HashMap<Integer, Integer>();
HashMap<Integer, Segment> left = new HashMap<Integer, Segment>();
HashMap<Integer, Segment> right = new HashMap<Integer, Segment>();
void run() throws IOException {
int n = nextInt();
int m = nextInt();
segs.add(new Segment(1, n));
for (int i = 0; i < m; i++) {
int x = nextInt();
if (x == 0) {
out.println(tree.query(nextInt(),nextInt()));
continue;
}
if (!arrive.containsKey(x)) {
Segment seg = segs.pollFirst();
int ans = seg.left + seg.len / 2;
arrive.put(x, ans);
tree.inc(ans, 1);
left.remove(ans);
right.remove(ans);
if (ans != seg.left) {
Segment sg = new Segment(seg.left, ans - 1);
segs.add(sg);
left.put(ans - 1,sg);
right.put(seg.left, sg);
}
if (ans != seg.right) {
Segment sg = new Segment(ans + 1, seg.right);
segs.add(sg);
left.put(seg.right, sg);
right.put(ans + 1, sg);
}
} else {
int tx =x;
x=arrive.get(x);
arrive.remove(tx);
tree.inc(x, -1);
Segment sl = left.get(x - 1), sr = right.get(x + 1);
int a = x, b = x;
if (sl != null) {
a = sl.left;
segs.remove(sl);
}
if (sr != null) {
b = sr.right;
segs.remove(sr);
}
Segment sg = new Segment(a, b);
segs.add(sg);
left.put(b,sg);
right.put(a, sg);
}
}
out.close();
}
StreamTokenizer in = new StreamTokenizer(new BufferedReader(
new InputStreamReader(System.in)));
int nextInt() throws IOException {
in.nextToken();
return (int) in.nval;
}
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
public static void main(String[] args) throws IOException {
new Hanger().run();
}
}
| Java | ["9 11\n1\n2\n0 5 8\n1\n1\n3\n0 3 8\n9\n0 6 9\n6\n0 1 9"] | 4 seconds | ["2\n3\n2\n5"] | null | Java 6 | standard input | [
"data structures"
] | 1250f103aa5fd1ac300a8a71b816b3e4 | The first line contains two integers n, q (1 ≤ n ≤ 109, 1 ≤ q ≤ 105), which are the number of hooks on the hanger and the number of requests correspondingly. Then follow q lines with requests, sorted according to time. The request of the type "0 i j" (1 ≤ i ≤ j ≤ n) — is the director's request. The input data has at least one director's request. In all other cases the request contains a positive integer not exceeding 109 — an employee identificator. Each odd appearance of the identificator of an employee in the request list is his arrival. Each even one is his leaving. All employees have distinct identificators. When any employee arrives, there is always at least one free hook. | 2,400 | For each director's request in the input data print a single number on a single line — the number of coats hanging on the hooks from the i-th one to the j-th one inclusive. | standard output | |
PASSED | 84d0811f52a40630552e894163434e0b | train_002.jsonl | 1302879600 | In one very large and very respectable company there is a cloakroom with a coat hanger. It is represented by n hooks, positioned in a row. The hooks are numbered with positive integers from 1 to n from the left to the right.The company workers have a very complicated work schedule. At the beginning of a work day all the employees are not there and the coat hanger in the cloakroom is empty. At some moments of time the employees arrive and some of them leave.When some employee arrives, he hangs his cloak on one of the available hooks. To be of as little discomfort to his colleagues as possible, the hook where the coat will hang, is chosen like this. First the employee chooses the longest segment among available hooks following in a row. If there are several of such segments, then he chooses the one closest to the right. After that the coat is hung on the hook located in the middle of this segment. If the segment has an even number of hooks, then among two central hooks we choose the one closest to the right.When an employee leaves, he takes his coat. As all the company workers deeply respect each other, no one takes somebody else's coat.From time to time the director of this respectable company gets bored and he sends his secretary to see how many coats hang on the coat hanger from the i-th to the j-th hook inclusive. And this whim is always to be fulfilled, otherwise the director gets angry and has a mental breakdown.Not to spend too much time traversing from the director's office to the cloakroom and back again, the secretary asked you to write a program, emulating the company cloakroom's work. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.util.Arrays;
import java.util.HashMap;
import java.util.TreeSet;
public class D68 {
static StreamTokenizer in;
static PrintWriter out;
static int nextInt() throws IOException {
in.nextToken();
return (int)in.nval;
}
static String nextString() throws IOException {
in.nextToken();
return in.sval;
}
public static void main(String[] args) throws IOException {
in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(System.out);
int n = nextInt();
int q = nextInt();
TreeSet<Segment> seg = new TreeSet<Segment>();
seg.add(new Segment(1, n));
HashMap<Integer, Person> per = new HashMap<Integer, Person>();
int[] Q = new int[q];
int[] L = new int[q];
int[] R = new int[q];
TreeSet<Integer> a = new TreeSet<Integer>();
for (int cs = 0; cs < q; cs++) {
Q[cs] = nextInt();
if (Q[cs] == 0) {
a.add(L[cs] = nextInt());
a.add(R[cs] = nextInt());
}
else {
int x = Q[cs];
if (per.containsKey(x)) {
Person p = per.get(x);
Segment toLeft = p.fromLeft;
Segment toRight = p.fromRight;
Person bl = toLeft.fromLeft;
Person br = toRight.fromRight;
Segment s = new Segment(toLeft.left, toRight.right);
if (bl != null) bl.fromRight = s;
s.fromLeft = bl;
s.fromRight = br;
if (br != null) br.fromLeft = s;
per.remove(x);
seg.remove(toLeft);
seg.remove(toRight);
seg.add(s);
}
else {
Segment best = seg.pollFirst();
int mid = (best.left + best.right + 1)/2;
Person p = new Person(mid);
Person bl = best.fromLeft, br = best.fromRight;
Segment toLeft = new Segment(best.left, mid-1);
Segment toRight = new Segment(mid+1, best.right);
if (bl != null) bl.fromRight = toLeft;
toLeft.fromLeft = bl;
toLeft.fromRight = p;
p.fromLeft = toLeft;
p.fromRight = toRight;
toRight.fromLeft = p;
toRight.fromRight = br;
if (br != null) br.fromLeft = toRight;
seg.add(toLeft);
seg.add(toRight);
per.put(x, p);
a.add(mid);
}
}
}
seg.clear();
seg.add(new Segment(1, n));
per.clear();
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int e : a) {
map.put(e, map.size()+1);
}
MAX = map.size();
t = new int[MAX+1];
for (int cs = 0; cs < q; cs++) {
int x = Q[cs];
if (x == 0) {
int l = map.get(L[cs]), r = map.get(R[cs]);
out.println(get(r) - get(l-1));
}
else {
if (per.containsKey(x)) {
Person p = per.get(x);
Segment toLeft = p.fromLeft;
Segment toRight = p.fromRight;
Person bl = toLeft.fromLeft;
Person br = toRight.fromRight;
Segment s = new Segment(toLeft.left, toRight.right);
if (bl != null) bl.fromRight = s;
s.fromLeft = bl;
s.fromRight = br;
if (br != null) br.fromLeft = s;
per.remove(x);
seg.remove(toLeft);
seg.remove(toRight);
seg.add(s);
modify(map.get(p.pos), -1);
}
else {
Segment best = seg.pollFirst();
int mid = (best.left + best.right + 1)/2;
Person p = new Person(mid);
Person bl = best.fromLeft, br = best.fromRight;
Segment toLeft = new Segment(best.left, mid-1);
Segment toRight = new Segment(mid+1, best.right);
if (bl != null) bl.fromRight = toLeft;
toLeft.fromLeft = bl;
toLeft.fromRight = p;
p.fromLeft = toLeft;
p.fromRight = toRight;
toRight.fromLeft = p;
toRight.fromRight = br;
if (br != null) br.fromLeft = toRight;
seg.add(toLeft);
seg.add(toRight);
per.put(x, p);
modify(map.get(mid), 1);
}
}
}
out.flush();
}
static class Segment implements Comparable<Segment> {
int left, right, length;
Person fromLeft, fromRight;
Segment(int left, int right) {
this.left = left;
this.right = right;
this.length = right - left + 1;
}
public int compareTo(Segment o) {
if (length > o.length) return -1;
else if (length < o.length) return 1;
else if (right > o.right) return -1;
else if (right < o.right) return 1;
else return 0;
}
}
static class Person {
Segment fromLeft, fromRight;
int pos;
Person(int pos) {
this.pos = pos;
}
}
static int MAX = 1000000;
static int[] t;
static void modify(int x, int v) {
t[x] += v;
while ((x += x&(-x)) <= MAX) t[x] += v;
}
static int get(int x) {
int res = t[x];
while ((x -= x&(-x)) >= 1) res += t[x];
return res;
}
}
| Java | ["9 11\n1\n2\n0 5 8\n1\n1\n3\n0 3 8\n9\n0 6 9\n6\n0 1 9"] | 4 seconds | ["2\n3\n2\n5"] | null | Java 6 | standard input | [
"data structures"
] | 1250f103aa5fd1ac300a8a71b816b3e4 | The first line contains two integers n, q (1 ≤ n ≤ 109, 1 ≤ q ≤ 105), which are the number of hooks on the hanger and the number of requests correspondingly. Then follow q lines with requests, sorted according to time. The request of the type "0 i j" (1 ≤ i ≤ j ≤ n) — is the director's request. The input data has at least one director's request. In all other cases the request contains a positive integer not exceeding 109 — an employee identificator. Each odd appearance of the identificator of an employee in the request list is his arrival. Each even one is his leaving. All employees have distinct identificators. When any employee arrives, there is always at least one free hook. | 2,400 | For each director's request in the input data print a single number on a single line — the number of coats hanging on the hooks from the i-th one to the j-th one inclusive. | standard output | |
PASSED | 03220614114d1e4ecc145b8a47826d9e | train_002.jsonl | 1302879600 | In one very large and very respectable company there is a cloakroom with a coat hanger. It is represented by n hooks, positioned in a row. The hooks are numbered with positive integers from 1 to n from the left to the right.The company workers have a very complicated work schedule. At the beginning of a work day all the employees are not there and the coat hanger in the cloakroom is empty. At some moments of time the employees arrive and some of them leave.When some employee arrives, he hangs his cloak on one of the available hooks. To be of as little discomfort to his colleagues as possible, the hook where the coat will hang, is chosen like this. First the employee chooses the longest segment among available hooks following in a row. If there are several of such segments, then he chooses the one closest to the right. After that the coat is hung on the hook located in the middle of this segment. If the segment has an even number of hooks, then among two central hooks we choose the one closest to the right.When an employee leaves, he takes his coat. As all the company workers deeply respect each other, no one takes somebody else's coat.From time to time the director of this respectable company gets bored and he sends his secretary to see how many coats hang on the coat hanger from the i-th to the j-th hook inclusive. And this whim is always to be fulfilled, otherwise the director gets angry and has a mental breakdown.Not to spend too much time traversing from the director's office to the cloakroom and back again, the secretary asked you to write a program, emulating the company cloakroom's work. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class D implements Runnable {
static class Segment {
int l;
int r;
public Segment(int l, int r) {
super();
this.l = l;
this.r = r;
}
@Override
public String toString() {
return "Segment [l=" + l + ", r=" + r + "]";
}
}
static class SegmentTree {
static class Node {
Node l;
Node r;
int sum;
}
Node root;
int n;
public SegmentTree(int n) {
this.n = n;
root = new Node();
}
int getSum(Node v, int l, int r, int left, int right) {
if (v == null) {
return 0;
}
if (l <= left && right <= r) {
return v.sum;
}
if (r <= left || right <= l) {
return 0;
}
int m = (left + right) >> 1;
return getSum(v.l, l, r, left, m) + getSum(v.r, l, r, m, right);
}
int getSum(int l, int r) {
return getSum(root, l, r, 0, n);
}
void add(int x, int y) {
Node v = root;
int l = 0;
int r = n;
while (l < r - 1) {
v.sum += y;
int m = (l + r) >> 1;
if (x < m) {
if (v.l == null) {
v.l = new Node();
}
v = v.l;
r = m;
} else {
if (v.r == null) {
v.r = new Node();
}
v = v.r;
l = m;
}
}
v.sum += y;
}
}
void solve() {
TreeSet<Segment> ts1 = new TreeSet<Segment>(new Comparator<Segment>() {
@Override
public int compare(Segment o1, Segment o2) {
int e1 = o1.r - o1.l;
int e2 = o2.r - o2.l;
if (e1 == e2) {
return o1.l < o2.l ? 1 : o1.l > o2.l ? -1 : 0;
}
return e1 < e2 ? 1 : -1;
}
});
TreeSet<Segment> ts2 = new TreeSet<Segment>(new Comparator<Segment>() {
@Override
public int compare(Segment o1, Segment o2) {
return o1.l > o2.l ? 1 : o1.l < o2.l ? -1 : 0;
}
});
HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
int n = nextInt();
int m = nextInt();
Segment all = new Segment(0, n);
SegmentTree stree = new SegmentTree(n);
ts1.add(all);
ts2.add(all);
Segment test = new Segment(0, 0);
for (int i = 0; i < m; i++) {
int x = nextInt();
if (x == 0) {
int l = nextInt();
int r = nextInt();
out.println(stree.getSum(l - 1, r));
} else {
if (hm.containsKey(x)) {
int w = hm.get(x);
hm.remove(x);
stree.add(w, -1);
test.l = test.r = w;
Segment left = ts2.floor(test);
Segment right = ts2.ceiling(test);
Segment newSegment = new Segment(w, w + 1);
if (left != null && left.r == w) {
newSegment.l = left.l;
ts1.remove(left);
ts2.remove(left);
}
if (right != null && right.l == w + 1) {
newSegment.r = right.r;
ts1.remove(right);
ts2.remove(right);
}
ts1.add(newSegment);
ts2.add(newSegment);
} else {
Segment most = ts1.pollFirst();
ts2.remove(most);
int w = (most.l + most.r) >> 1;
hm.put(x, w);
stree.add(w, 1);
Segment left = new Segment(most.l, w);
Segment right = new Segment(w + 1, most.r);
if (left.l < left.r) {
ts1.add(left);
ts2.add(left);
}
if (right.l < right.r) {
ts1.add(right);
ts2.add(right);
}
}
}
}
}
FastScanner sc;
PrintWriter out;
public void run() {
Locale.setDefault(Locale.US);
try {
sc = new FastScanner(System.in);
out = new PrintWriter(System.out);
solve();
sc.close();
out.close();
} catch (Throwable e) {
e.printStackTrace();
System.exit(1);
}
}
int nextInt() {
return sc.nextInt();
}
String nextToken() {
return sc.nextToken();
}
long nextLong() {
return sc.nextLong();
}
double nextDouble() {
return sc.nextDouble();
}
BigInteger nextBigInteger() {
return sc.nextBigInteger();
}
class FastScanner extends BufferedReader {
StringTokenizer st;
boolean eof;
String buf;
String curLine;
boolean createST;
public FastScanner(String fileName) throws FileNotFoundException {
this(fileName, true);
}
public FastScanner(String fileName, boolean createST)
throws FileNotFoundException {
super(new FileReader(fileName));
this.createST = createST;
nextToken();
}
public FastScanner(InputStream stream) {
this(stream, true);
}
public FastScanner(InputStream stream, boolean createST) {
super(new InputStreamReader(stream));
this.createST = createST;
nextToken();
}
String nextLine() {
String ret = curLine;
if (createST) {
st = null;
}
nextToken();
return ret;
}
String nextToken() {
if (!createST) {
try {
curLine = readLine();
} catch (Exception e) {
eof = true;
}
return null;
}
while (st == null || !st.hasMoreTokens()) {
try {
curLine = readLine();
st = new StringTokenizer(curLine);
} catch (Exception e) {
eof = true;
break;
}
}
String ret = buf;
buf = eof ? "-1" : st.nextToken();
return ret;
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
BigInteger nextBigInteger() {
return new BigInteger(nextToken());
}
public void close() {
try {
buf = null;
st = null;
curLine = null;
super.close();
} catch (Exception e) {
}
}
boolean isEOF() {
return eof;
}
}
public static void main(String[] args) {
new D().run();
}
} | Java | ["9 11\n1\n2\n0 5 8\n1\n1\n3\n0 3 8\n9\n0 6 9\n6\n0 1 9"] | 4 seconds | ["2\n3\n2\n5"] | null | Java 6 | standard input | [
"data structures"
] | 1250f103aa5fd1ac300a8a71b816b3e4 | The first line contains two integers n, q (1 ≤ n ≤ 109, 1 ≤ q ≤ 105), which are the number of hooks on the hanger and the number of requests correspondingly. Then follow q lines with requests, sorted according to time. The request of the type "0 i j" (1 ≤ i ≤ j ≤ n) — is the director's request. The input data has at least one director's request. In all other cases the request contains a positive integer not exceeding 109 — an employee identificator. Each odd appearance of the identificator of an employee in the request list is his arrival. Each even one is his leaving. All employees have distinct identificators. When any employee arrives, there is always at least one free hook. | 2,400 | For each director's request in the input data print a single number on a single line — the number of coats hanging on the hooks from the i-th one to the j-th one inclusive. | standard output | |
PASSED | f494bb5394e7a4511549a8df67216463 | train_002.jsonl | 1302879600 | In one very large and very respectable company there is a cloakroom with a coat hanger. It is represented by n hooks, positioned in a row. The hooks are numbered with positive integers from 1 to n from the left to the right.The company workers have a very complicated work schedule. At the beginning of a work day all the employees are not there and the coat hanger in the cloakroom is empty. At some moments of time the employees arrive and some of them leave.When some employee arrives, he hangs his cloak on one of the available hooks. To be of as little discomfort to his colleagues as possible, the hook where the coat will hang, is chosen like this. First the employee chooses the longest segment among available hooks following in a row. If there are several of such segments, then he chooses the one closest to the right. After that the coat is hung on the hook located in the middle of this segment. If the segment has an even number of hooks, then among two central hooks we choose the one closest to the right.When an employee leaves, he takes his coat. As all the company workers deeply respect each other, no one takes somebody else's coat.From time to time the director of this respectable company gets bored and he sends his secretary to see how many coats hang on the coat hanger from the i-th to the j-th hook inclusive. And this whim is always to be fulfilled, otherwise the director gets angry and has a mental breakdown.Not to spend too much time traversing from the director's office to the cloakroom and back again, the secretary asked you to write a program, emulating the company cloakroom's work. | 256 megabytes | import java.io.*;
import java.util.*;
public class D {
int n;
int[] qMan, qLeft, qRight;
int[] x;
int queries;
int getIndex(int i) {
int l = 0, r = x.length;
while (r - l > 1) {
int m = (r + l) / 2;
if (x[m] > i) {
r = m;
} else {
l = m;
}
}
return l;
}
private void solve() throws IOException {
n = nextInt();
queries = nextInt();
qMan = new int[queries];
qLeft = new int[queries];
qRight = new int[queries];
HashSet<Integer> interesting = new HashSet<Integer>();
interesting.add(0);
interesting.add(n);
for (int i = 0; i < queries; i++) {
qMan[i] = nextInt();
if (qMan[i] == 0) {
qLeft[i] = nextInt() - 1;
qRight[i] = nextInt();
interesting.add(qLeft[i]);
interesting.add(qRight[i]);
}
}
x = new int[interesting.size()];
int cnt = 0;
for (int i : interesting) {
x[cnt++] = i;
}
Arrays.sort(x);
Fenwick f = new Fenwick(x.length);
TreeSet<Segment> segments = new TreeSet<D.Segment>();
TreeSet<Segment> segmentsByX = new TreeSet<D.Segment>(new ByStart());
Segment s = new Segment(0, n);
segments.add(s);
segmentsByX.add(s);
HashMap<Integer, Integer> taken = new HashMap<Integer, Integer>();
for (int i = 0; i < queries; i++) {
// System.err.println(segmentsByX);
if (qMan[i] == 0) {
// System.err.println("QUERY " + qLeft[i] + " " + qRight[i]);
int l = getIndex(qLeft[i]);
int r = getIndex(qRight[i]);
out.println(f.getSum(l, r));
} else {
Integer pos = taken.get(qMan[i]);
if (pos == null) {
Segment t = segments.pollLast();
segmentsByX.remove(t);
pos = t.start + t.len / 2;
// System.err.println("PUTTING " + qMan[i] + " TO " + pos);
taken.put(qMan[i], pos);
int ind = getIndex(pos);
f.add(ind, 1);
if (t.len % 2 == 1) {
if (t.len > 1) {
Segment s1 = new Segment(t.start, t.len / 2);
Segment s2 = new Segment(pos + 1, t.len / 2);
segments.add(s1);
segments.add(s2);
segmentsByX.add(s1);
segmentsByX.add(s2);
}
} else {
Segment s1 = new Segment(t.start, t.len / 2);
segments.add(s1);
segmentsByX.add(s1);
if (t.len > 2) {
Segment s2 = new Segment(pos + 1, t.len / 2 - 1);
segments.add(s2);
segmentsByX.add(s2);
}
}
} else {
// System.err.println("FREEING " + pos);
int ind = getIndex(pos);
taken.remove(qMan[i]);
f.add(ind, -1);
Segment ok = new Segment(pos, -1);
Segment left = segmentsByX.lower(ok);
if (left != null && left.start + left.len != pos) {
left = null;
}
Segment right = segmentsByX.higher(ok);
if (right != null && right.start != pos + 1) {
right = null;
}
if (left != null) {
segments.remove(left);
segmentsByX.remove(left);
}
if (right != null) {
segments.remove(right);
segmentsByX.remove(right);
}
int newStart = left == null ? pos : left.start;
int newLen = 1 + (left == null ? 0 : left.len)
+ (right == null ? 0 : right.len);
Segment add = new Segment(newStart, newLen);
segments.add(add);
segmentsByX.add(add);
}
}
}
}
static class ByStart implements Comparator<Segment> {
@Override
public int compare(Segment o1, Segment o2) {
return o1.start - o2.start;
}
}
static class Segment implements Comparable<Segment> {
@Override
public String toString() {
return "Segment [start=" + start + ", len=" + len + "]";
}
int start, len;
public Segment(int start, int len) {
this.start = start;
this.len = len;
}
@Override
public int compareTo(Segment o) {
if (len != o.len)
return len - o.len;
return start - o.start;
}
}
static class Fenwick {
private final int[] s;
public Fenwick(int n) {
s = new int[n];
}
public int getSum(int i) {
int res = 0;
for (; i >= 0; i = (i & i + 1) - 1) {
res += s[i];
}
return res;
}
public void add(int i, int val) {
for (; i < s.length; i |= i + 1) {
s[i] += val;
}
}
public int getSum(int l, int r) {
int res = 0;
for (--r; r >= l; r = (r & r + 1) - 1) {
res += s[r];
}
for (--l; l != r; l = (l & l + 1) - 1) {
res -= s[l];
}
return res;
}
}
public static void main(String[] args) {
new D().run();
}
BufferedReader br;
StringTokenizer st;
PrintWriter out;
boolean eof = false;
public void run() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
st = new StringTokenizer("");
solve();
out.close();
} catch (Throwable e) {
e.printStackTrace();
System.exit(239);
}
}
String nextToken() throws IOException {
while (!st.hasMoreTokens()) {
String line = br.readLine();
if (line == null) {
eof = true;
line = "0";
}
st = new StringTokenizer(line);
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
} | Java | ["9 11\n1\n2\n0 5 8\n1\n1\n3\n0 3 8\n9\n0 6 9\n6\n0 1 9"] | 4 seconds | ["2\n3\n2\n5"] | null | Java 6 | standard input | [
"data structures"
] | 1250f103aa5fd1ac300a8a71b816b3e4 | The first line contains two integers n, q (1 ≤ n ≤ 109, 1 ≤ q ≤ 105), which are the number of hooks on the hanger and the number of requests correspondingly. Then follow q lines with requests, sorted according to time. The request of the type "0 i j" (1 ≤ i ≤ j ≤ n) — is the director's request. The input data has at least one director's request. In all other cases the request contains a positive integer not exceeding 109 — an employee identificator. Each odd appearance of the identificator of an employee in the request list is his arrival. Each even one is his leaving. All employees have distinct identificators. When any employee arrives, there is always at least one free hook. | 2,400 | For each director's request in the input data print a single number on a single line — the number of coats hanging on the hooks from the i-th one to the j-th one inclusive. | standard output | |
PASSED | d276693f39e0587759807faa3d2a4789 | train_002.jsonl | 1302879600 | In one very large and very respectable company there is a cloakroom with a coat hanger. It is represented by n hooks, positioned in a row. The hooks are numbered with positive integers from 1 to n from the left to the right.The company workers have a very complicated work schedule. At the beginning of a work day all the employees are not there and the coat hanger in the cloakroom is empty. At some moments of time the employees arrive and some of them leave.When some employee arrives, he hangs his cloak on one of the available hooks. To be of as little discomfort to his colleagues as possible, the hook where the coat will hang, is chosen like this. First the employee chooses the longest segment among available hooks following in a row. If there are several of such segments, then he chooses the one closest to the right. After that the coat is hung on the hook located in the middle of this segment. If the segment has an even number of hooks, then among two central hooks we choose the one closest to the right.When an employee leaves, he takes his coat. As all the company workers deeply respect each other, no one takes somebody else's coat.From time to time the director of this respectable company gets bored and he sends his secretary to see how many coats hang on the coat hanger from the i-th to the j-th hook inclusive. And this whim is always to be fulfilled, otherwise the director gets angry and has a mental breakdown.Not to spend too much time traversing from the director's office to the cloakroom and back again, the secretary asked you to write a program, emulating the company cloakroom's work. | 256 megabytes | //package round68;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.TreeSet;
public class D2 {
IntReader in;
PrintWriter out;
// String INPUT = "9 11\r\n" +
// "1\r\n" +
// "2\r\n" +
// "0 5 8\r\n" +
// "1\r\n" +
// "1\r\n" +
// "3\r\n" +
// "0 3 8\r\n" +
// "9\r\n" +
// "0 6 9\r\n" +
// "6\r\n" +
// "0 1 9";
// String INPUT = "8 9 1 2 1 2 1 2 1 2 0 1 8";
// String INPUT = "3 3 10 10 0 1 3";
// String INPUT = "9 9 1 2 3 4 5 6 7 8 0 1 8";
String INPUT = "";
static class Interval implements Comparable<Interval>
{
public int ind, len;
public Interval(int ind, int len) {
this.ind = ind;
this.len = len;
}
public int compareTo(Interval b)
{
if(len != b.len)return b.len - this.len; // longer
return b.ind - this.ind; // right
}
}
void solve()
{
int n = ni();
int q = ni();
int[][] com = new int[q][];
Map<Integer, Integer> arranged = new HashMap<Integer, Integer>();
TreeSet<Interval> ints = new TreeSet<Interval>(); // 優先度順にIntervalを並べたもの
ints.add(new Interval(1, n));
TreeMap<Integer, Interval> indint = new TreeMap<Integer, Interval>(); // 左から右にIntervalを並べた物
HashSet<Integer> aped = new HashSet<Integer>(); // ハンガーとして採用されたindex
for(int i = 0;i < q;i++){
int c = ni();
if(c == 0){
com[i] = new int[]{ni(), ni()};
}else{
if(arranged.containsKey(c)){
int ind = arranged.remove(c);
Map.Entry<Integer, Interval> left = indint.floorEntry(ind);
Map.Entry<Integer, Interval> right = indint.ceilingEntry(ind+1);
ints.remove(right.getValue());
ints.remove(left.getValue());
Interval merged = new Interval(left.getKey(), left.getValue().len + 1 + right.getValue().len);
ints.add(merged);
indint.remove(left.getKey());
indint.remove(right.getKey());
indint.put(left.getKey(), merged);
com[i] = new int[]{ind};
}else{
Interval v = ints.pollFirst();
int ind = v.ind + v.len / 2;
Interval left = new Interval(v.ind, v.len/2);
Interval right = new Interval(ind+1, v.ind+v.len-ind-1);
ints.add(left);
ints.add(right);
indint.put(v.ind, left);
indint.put(ind+1, right);
arranged.put(c, ind);
aped.add(ind);
com[i] = new int[]{ind};
}
}
}
List<Integer> l = new ArrayList<Integer>(aped); // hanger_indexes
Collections.sort(l);
HashMap<Integer, Integer> apmap = new HashMap<Integer, Integer>(); // <hanger_index after_index>
for(int i = 0;i < l.size();i++){
apmap.put(l.get(i), i+1);
}
// tr(arranged);
int u = l.size();
int[] f = new int[u+1];
int[] a = new int[u+1];
for(int i = 0;i < q;i++){
if(com[i].length == 2){
int low = Collections.binarySearch(l, com[i][0]);
if(low < 0)low = -low - 1;
int high = Collections.binarySearch(l, com[i][1]);
if(high < 0)high = -high - 2;
// tr(l, com[i], low, high);
if(high+1 < low){
out.println(0);
}else{
out.println(sumFenwick(f, high+1) - sumFenwick(f, low));
}
}else{
int ind = apmap.get(com[i][0]);
if(a[ind] == 1){
a[ind]--;
addFenwick(f, ind, -1);
}else{
a[ind]++;
addFenwick(f, ind, 1);
}
}
}
}
public static int sumFenwick(int[] ft, int i)
{
int sum = 0;
for(;i > 0;i -= i&-i)sum += ft[i];
return sum;
}
public static void addFenwick(int[] ft, int i, int v)
{
int n = ft.length;
for(;i < n;i += i&-i)ft[i] += v;
}
void run() throws Exception
{
in = INPUT.isEmpty() ? new IntReader(System.in) : new IntReader(new ByteArrayInputStream(INPUT.getBytes()));
out = new PrintWriter(System.out);
solve();
out.flush();
}
public static void main(String[] args) throws Exception
{
new D2().run();
}
public class IntReader {
private InputStream is;
public IntReader(InputStream is)
{
this.is = is;
}
public int nui()
{
try {
int num = 0;
while((num = is.read()) != -1 && (num < '0' || num > '9'));
num -= '0';
while(true){
int b = is.read();
if(b == -1)return num;
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return num;
}
}
} catch (IOException e) {
}
return -1;
}
public int ni()
{
try {
int num = 0;
boolean minus = false;
while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-'));
if(num == '-'){
num = 0;
minus = true;
}else{
num -= '0';
}
while(true){
int b = is.read();
if(b == -1)return minus ? -num : num;
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
}
} catch (IOException e) {
}
return -1;
}
public String nl()
{
try{
int b = 0;
StringBuilder sb = new StringBuilder();
while((b = is.read()) != -1 && (b == '\r' || b == '\n'));
if(b == -1)return "";
sb.append((char)b);
while(true){
b = is.read();
if(b == -1)return sb.toString();
if(b == '\r' || b == '\n')return sb.toString();
sb.append((char)b);
}
} catch (IOException e) {
}
return "";
}
}
int ni() { return in.ni(); }
int nui() { return in.nui(); }
String nl() { return in.nl(); }
void tr(Object... o) { if(INPUT.length() != 0)System.out.println(Arrays.deepToString(o)); }
}
| Java | ["9 11\n1\n2\n0 5 8\n1\n1\n3\n0 3 8\n9\n0 6 9\n6\n0 1 9"] | 4 seconds | ["2\n3\n2\n5"] | null | Java 6 | standard input | [
"data structures"
] | 1250f103aa5fd1ac300a8a71b816b3e4 | The first line contains two integers n, q (1 ≤ n ≤ 109, 1 ≤ q ≤ 105), which are the number of hooks on the hanger and the number of requests correspondingly. Then follow q lines with requests, sorted according to time. The request of the type "0 i j" (1 ≤ i ≤ j ≤ n) — is the director's request. The input data has at least one director's request. In all other cases the request contains a positive integer not exceeding 109 — an employee identificator. Each odd appearance of the identificator of an employee in the request list is his arrival. Each even one is his leaving. All employees have distinct identificators. When any employee arrives, there is always at least one free hook. | 2,400 | For each director's request in the input data print a single number on a single line — the number of coats hanging on the hooks from the i-th one to the j-th one inclusive. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.