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 | d91c431631d85443f426719bd4799645 | train_003.jsonl | 1496837700 | The crowdedness of the discotheque would never stop our friends from having fun, but a bit more spaciousness won't hurt, will it?The discotheque can be seen as an infinite xy-plane, in which there are a total of n dancers. Once someone starts moving around, they will move only inside their own movement range, which is a circular area Ci described by a center (xi,βyi) and a radius ri. No two ranges' borders have more than one common point, that is for every pair (i,βj) (1ββ€βiβ<βjββ€βn) either ranges Ci and Cj are disjoint, or one of them is a subset of the other. Note that it's possible that two ranges' borders share a single common point, but no two dancers have exactly the same ranges.Tsukihi, being one of them, defines the spaciousness to be the area covered by an odd number of movement ranges of dancers who are moving. An example is shown below, with shaded regions representing the spaciousness if everyone moves at the same time. But no one keeps moving for the whole night after all, so the whole night's time is divided into two halves β before midnight and after midnight. Every dancer moves around in one half, while sitting down with friends in the other. The spaciousness of two halves are calculated separately and their sum should, of course, be as large as possible. The following figure shows an optimal solution to the example above. By different plans of who dances in the first half and who does in the other, different sums of spaciousness over two halves are achieved. You are to find the largest achievable value of this sum. | 256 megabytes | import java.util.*;
import java.math.*;
import java.io.*;
import java.text.*;
public class A{
//public static PrintWriter pw;
public static PrintWriter pw=new PrintWriter(System.out);
public static void solve() throws IOException{
// pw=new PrintWriter(new FileWriter("C:\\Users\\shree\\Downloads\\small_output_in"));
FastReader sc=new FastReader();
int n=sc.I();
long x[]=new long[n+1];
long y[]=new long[n+1];
long r[]=new long[n+1];
area=new double[n+1];
for(int i=1;i<=n;i++) {
x[i]=sc.L(); y[i]=sc.L(); r[i]=sc.L();
area[i]=(r[i]*r[i]);
}
graph=new Vector[n+1];
parent=new int[n+1];
Arrays.fill(parent,Integer.MAX_VALUE);
for(int i=1;i<=n;i++)graph[i]=new Vector<>();
for(int i=1;i<=n;i++) { long mn=Long.MAX_VALUE;
for(int j=1;j<=n;j++) {
if(i!=j && r[j]>r[i] && getD(x[i],y[i],x[j],y[j])<=(r[j]-r[i])*(r[j]-r[i]) && r[j]<mn) {
parent[i]=j;
mn=r[j];
}
}
if(parent[i]!=Integer.MAX_VALUE)
graph[parent[i]].add(i);
}
vis=new boolean[n+1];
double ans=0;
for(int i=1;i<=n;i++) if(parent[i]==Integer.MAX_VALUE) ans+=dfs(i,0);
pw.printf("%.14f\n", ans*Math.PI);
pw.close();
}
static Vector<Integer> graph[];
static boolean vis[];
static double area[];
static int parent[];
static double dfs(int v,int level) {
vis[v]=true;
double ans=0;
if(level%2==0 && parent[v]!=Integer.MAX_VALUE) ans-=area[v];
else ans+=area[v];
for(int u : graph[v]) {
if(!vis[u]) ans+=dfs(u,level+1);
}
return ans;
}
static double getD(long x1,long y1,long x2,long y2) {
return ((x1-x2)*(x1-x2) +(y1-y2)*(y1-y2));
}
public static void main(String[] args) {
new Thread(null ,new Runnable(){
public void run(){
try{
solve();
} catch(Exception e){
e.printStackTrace();
}
}
},"1",1<<26).start();
}
static long modPow(long x,long y,long M){
if(y==0) return 1;
if(y%2==0) return modPow((x*x)%M,y/2,M)%M;
else return (x*modPow((x*x)%M,(y-1)/2,M))%M;
}
static long M=(long)1e9+7;
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() throws FileNotFoundException{
//br=new BufferedReader(new FileReader("C:\\Users\\shree\\Downloads\\B-small-practice.in"));
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 I(){ return Integer.parseInt(next()); }
long L(){ return Long.parseLong(next()); }
double D() { return Double.parseDouble(next()); }
String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["5\n2 1 6\n0 4 1\n2 -1 3\n1 -2 1\n4 -1 1", "8\n0 0 1\n0 0 2\n0 0 3\n0 0 4\n0 0 5\n0 0 6\n0 0 7\n0 0 8"] | 2 seconds | ["138.23007676", "289.02652413"] | NoteThe first sample corresponds to the illustrations in the legend. | Java 8 | standard input | [
"dp",
"geometry",
"greedy",
"dfs and similar",
"trees"
] | 56a13208f0a9b2fad23756f39acd64af | The first line of input contains a positive integer n (1ββ€βnββ€β1β000) β the number of dancers. The following n lines each describes a dancer: the i-th line among them contains three space-separated integers xi, yi and ri (β-β106ββ€βxi,βyiββ€β106, 1ββ€βriββ€β106), describing a circular movement range centered at (xi,βyi) with radius ri. | 2,000 | Output one decimal number β the largest achievable sum of spaciousness over two halves of the night. The output is considered correct if it has a relative or absolute error of at most 10β-β9. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if . | standard output | |
PASSED | b19a6ce4f0d3e9f67a6d70899e16046f | train_003.jsonl | 1487930700 | Vasya is an administrator of a public page of organization "Mouse and keyboard" and his everyday duty is to publish news from the world of competitive programming. For each news he also creates a list of hashtags to make searching for a particular topic more comfortable. For the purpose of this problem we define hashtag as a string consisting of lowercase English letters and exactly one symbol '#' located at the beginning of the string. The length of the hashtag is defined as the number of symbols in it without the symbol '#'.The head administrator of the page told Vasya that hashtags should go in lexicographical order (take a look at the notes section for the definition).Vasya is lazy so he doesn't want to actually change the order of hashtags in already published news. Instead, he decided to delete some suffixes (consecutive characters at the end of the string) of some of the hashtags. He is allowed to delete any number of characters, even the whole string except for the symbol '#'. Vasya wants to pick such a way to delete suffixes that the total number of deleted symbols is minimum possible. If there are several optimal solutions, he is fine with any of them. | 256 megabytes |
//.....your program....
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class Main {
//////
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
//////
public static void main(String[] args) {
FastReader scan=new FastReader();
//Scanner scan = new Scanner(System.in);
//String ans1="abc";
//char ab='i';
//String abc="kk";
//ans1.concat(abc);
//System.out.println(ans1);
int N=scan.nextInt();
String[] s=new String[N];
String[] ans=new String[N];
for(int i=0;i<N;i++){
s[i]=scan.next();
}
// long startTime = System.currentTimeMillis();
//Arrays.fill(ans,"");
ans[N-1]=s[N-1];
for(int i=N-2;i>=0;i--){
ans[i]="";
if(ans[i+1].compareTo(s[i])>=0){
ans[i]=s[i];
continue;
}
int a=ans[i+1].length();
int b=s[i].length();
int len=Math.min(a,b);
int j=0;
for(j=0;j<len;j++){
if(ans[i+1].charAt(j)<s[i].charAt(j)){
break;
}
}
//ans[i]=ans[i].concat(String.valueOf(s[i].charAt(j)));
ans[i]=s[i].substring(0,j);
// for(int k=0;k<j;k++){
// }
}
PrintWriter pw = new PrintWriter(System.out);
//for (int i = 0; i < n; i++) {
//pw.println(s[i].toString());
//}
//pw.close();
for(int i=0;i<N;i++){
// System.out.println(ans[i]);
pw.println(ans[i]);
}
pw.close();
//long endTime = System.currentTimeMillis();
//long totalTime = endTime - startTime;
//scan.close();
//System.out.println(totalTime);
}
}
| Java | ["3\n#book\n#bigtown\n#big", "3\n#book\n#cool\n#cold", "4\n#car\n#cart\n#art\n#at", "3\n#apple\n#apple\n#fruit"] | 2 seconds | ["#b\n#big\n#big", "#book\n#co\n#cold", "#\n#\n#art\n#at", "#apple\n#apple\n#fruit"] | NoteWord a1,βa2,β...,βam of length m is lexicographically not greater than word b1,βb2,β...,βbk of length k, if one of two conditions hold: at first position i, such that aiββ βbi, the character ai goes earlier in the alphabet than character bi, i.e. a has smaller character than b in the first position where they differ; if there is no such position i and mββ€βk, i.e. the first word is a prefix of the second or two words are equal. The sequence of words is said to be sorted in lexicographical order if each word (except the last one) is lexicographically not greater than the next word.For the words consisting of lowercase English letters the lexicographical order coincides with the alphabet word order in the dictionary.According to the above definition, if a hashtag consisting of one character '#' it is lexicographically not greater than any other valid hashtag. That's why in the third sample we can't keep first two hashtags unchanged and shorten the other two. | Java 8 | standard input | [
"binary search",
"implementation",
"greedy",
"strings"
] | 27baf9b1241c0f8e3a2037b18f39fe34 | The first line of the input contains a single integer n (1ββ€βnββ€β500β000)Β β the number of hashtags being edited now. Each of the next n lines contains exactly one hashtag of positive length. It is guaranteed that the total length of all hashtags (i.e. the total length of the string except for characters '#') won't exceed 500β000. | 1,800 | Print the resulting hashtags in any of the optimal solutions. | standard output | |
PASSED | 8941f7b8f5fe4144f4f2367752f2b5b2 | train_003.jsonl | 1487930700 | Vasya is an administrator of a public page of organization "Mouse and keyboard" and his everyday duty is to publish news from the world of competitive programming. For each news he also creates a list of hashtags to make searching for a particular topic more comfortable. For the purpose of this problem we define hashtag as a string consisting of lowercase English letters and exactly one symbol '#' located at the beginning of the string. The length of the hashtag is defined as the number of symbols in it without the symbol '#'.The head administrator of the page told Vasya that hashtags should go in lexicographical order (take a look at the notes section for the definition).Vasya is lazy so he doesn't want to actually change the order of hashtags in already published news. Instead, he decided to delete some suffixes (consecutive characters at the end of the string) of some of the hashtags. He is allowed to delete any number of characters, even the whole string except for the symbol '#'. Vasya wants to pick such a way to delete suffixes that the total number of deleted symbols is minimum possible. If there are several optimal solutions, he is fine with any of them. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class D401 {
public static void main(String args[]) throws FileNotFoundException {
InputReader in = new InputReader(System.in);
OutputStream outputStream = System.out;
PrintWriter out = new PrintWriter(outputStream);
StringBuilder sb = new StringBuilder();
// ----------My Code----------
int n = in.nextInt();
String str[] = new String[n];
for (int i = 0; i < n; i++)
str[i] = in.nextLine();
for (int i = n - 2; i >= 0; i--) {
int min = Math.min(str[i].length(), str[i + 1].length());
if (min == str[i].length()) {
for (int j = 0; j < min; j++) {
if (str[i].charAt(j) > str[i + 1].charAt(j)) {
str[i] = str[i].substring(0, j);
break;
}else if(str[i].charAt(j) < str[i + 1].charAt(j)){
break;
}
}
} else {
boolean f = true;
for (int j = 0; j < min; j++) {
if (str[i].charAt(j) > str[i + 1].charAt(j)) {
f = false;
str[i] = str[i].substring(0, j);
break;
}else if(str[i].charAt(j) < str[i + 1].charAt(j)){
f=false;
break;
}
}
if (f == true)
str[i] = str[i].substring(0, min);
}
}
for(int i=0;i<n;i++)
sb.append(str[i]).append("\n");
out.println(sb);
// ---------------The End------------------
out.close();
}
// ---------------Extra Methods------------------
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;
}
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;
}
// ---------------Extra Methods------------------
public static void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream inputstream) {
reader = new BufferedReader(new InputStreamReader(inputstream));
tokenizer = null;
}
public String nextLine() {
String fullLine = null;
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
fullLine = reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return fullLine;
}
return fullLine;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public char nextChar() {
return next().charAt(0);
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public int[] nextIntArray(int n, int f) {
if (f == 0) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
} else {
int[] arr = new int[n + 1];
for (int i = 1; i < n + 1; i++) {
arr[i] = nextInt();
}
return arr;
}
}
public long[] nextLongArray(int n, int f) {
if (f == 0) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
} else {
long[] arr = new long[n + 1];
for (int i = 1; i < n + 1; i++) {
arr[i] = nextLong();
}
return arr;
}
}
public double[] nextDoubleArray(int n, int f) {
if (f == 0) {
double[] arr = new double[n];
for (int i = 0; i < n; i++) {
arr[i] = nextDouble();
}
return arr;
} else {
double[] arr = new double[n + 1];
for (int i = 1; i < n + 1; i++) {
arr[i] = nextDouble();
}
return arr;
}
}
}
static class Pair implements Comparable<Pair> {
int a, b;
Pair(int a, int b) {
this.a = a;
this.b = b;
}
public int compareTo(Pair o) {
// TODO Auto-generated method stub
if (this.a != o.a)
return Integer.compare(this.a, o.a);
else
return Integer.compare(this.b, o.b);
}
public boolean equals(Object o) {
if (o instanceof Pair) {
Pair p = (Pair) o;
return p.a == a && p.b == b;
}
return false;
}
public int hashCode() {
return new Integer(a).hashCode() * 31 + new Integer(b).hashCode();
}
}
}
| Java | ["3\n#book\n#bigtown\n#big", "3\n#book\n#cool\n#cold", "4\n#car\n#cart\n#art\n#at", "3\n#apple\n#apple\n#fruit"] | 2 seconds | ["#b\n#big\n#big", "#book\n#co\n#cold", "#\n#\n#art\n#at", "#apple\n#apple\n#fruit"] | NoteWord a1,βa2,β...,βam of length m is lexicographically not greater than word b1,βb2,β...,βbk of length k, if one of two conditions hold: at first position i, such that aiββ βbi, the character ai goes earlier in the alphabet than character bi, i.e. a has smaller character than b in the first position where they differ; if there is no such position i and mββ€βk, i.e. the first word is a prefix of the second or two words are equal. The sequence of words is said to be sorted in lexicographical order if each word (except the last one) is lexicographically not greater than the next word.For the words consisting of lowercase English letters the lexicographical order coincides with the alphabet word order in the dictionary.According to the above definition, if a hashtag consisting of one character '#' it is lexicographically not greater than any other valid hashtag. That's why in the third sample we can't keep first two hashtags unchanged and shorten the other two. | Java 8 | standard input | [
"binary search",
"implementation",
"greedy",
"strings"
] | 27baf9b1241c0f8e3a2037b18f39fe34 | The first line of the input contains a single integer n (1ββ€βnββ€β500β000)Β β the number of hashtags being edited now. Each of the next n lines contains exactly one hashtag of positive length. It is guaranteed that the total length of all hashtags (i.e. the total length of the string except for characters '#') won't exceed 500β000. | 1,800 | Print the resulting hashtags in any of the optimal solutions. | standard output | |
PASSED | 1e206284ccc7e74b6fdcfb077ec1a7ab | train_003.jsonl | 1487930700 | Vasya is an administrator of a public page of organization "Mouse and keyboard" and his everyday duty is to publish news from the world of competitive programming. For each news he also creates a list of hashtags to make searching for a particular topic more comfortable. For the purpose of this problem we define hashtag as a string consisting of lowercase English letters and exactly one symbol '#' located at the beginning of the string. The length of the hashtag is defined as the number of symbols in it without the symbol '#'.The head administrator of the page told Vasya that hashtags should go in lexicographical order (take a look at the notes section for the definition).Vasya is lazy so he doesn't want to actually change the order of hashtags in already published news. Instead, he decided to delete some suffixes (consecutive characters at the end of the string) of some of the hashtags. He is allowed to delete any number of characters, even the whole string except for the symbol '#'. Vasya wants to pick such a way to delete suffixes that the total number of deleted symbols is minimum possible. If there are several optimal solutions, he is fine with any of them. | 256 megabytes | import java.io.*;
import java.util.Arrays;
public class D401 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
int n = Integer.parseInt(br.readLine());
char[][] hashtags = new char[n][];
for (int i = 0; i < n; i++) {
hashtags[i] = br.readLine().toCharArray();
}
for (int i = n - 2; i >= 0; i--) {
int jL = hashtags[i].length;
int kL = hashtags[i + 1].length;
boolean flag = false;
for (int j = 0, k = 0; j < jL && k < kL; j++, k++) {
if (hashtags[i][j] < hashtags[i + 1][k]) {
flag = true;
break;
}
if (hashtags[i][j] > hashtags[i + 1][k]) {
hashtags[i] = Arrays.copyOf(hashtags[i], j);
flag = true;
break;
}
}
if (!flag && jL > kL) {
hashtags[i] = Arrays.copyOf(hashtags[i], kL);
}
}
for (int i = 0; i < n; i++) {
out.println(hashtags[i]);
}
out.close();
}
} | Java | ["3\n#book\n#bigtown\n#big", "3\n#book\n#cool\n#cold", "4\n#car\n#cart\n#art\n#at", "3\n#apple\n#apple\n#fruit"] | 2 seconds | ["#b\n#big\n#big", "#book\n#co\n#cold", "#\n#\n#art\n#at", "#apple\n#apple\n#fruit"] | NoteWord a1,βa2,β...,βam of length m is lexicographically not greater than word b1,βb2,β...,βbk of length k, if one of two conditions hold: at first position i, such that aiββ βbi, the character ai goes earlier in the alphabet than character bi, i.e. a has smaller character than b in the first position where they differ; if there is no such position i and mββ€βk, i.e. the first word is a prefix of the second or two words are equal. The sequence of words is said to be sorted in lexicographical order if each word (except the last one) is lexicographically not greater than the next word.For the words consisting of lowercase English letters the lexicographical order coincides with the alphabet word order in the dictionary.According to the above definition, if a hashtag consisting of one character '#' it is lexicographically not greater than any other valid hashtag. That's why in the third sample we can't keep first two hashtags unchanged and shorten the other two. | Java 8 | standard input | [
"binary search",
"implementation",
"greedy",
"strings"
] | 27baf9b1241c0f8e3a2037b18f39fe34 | The first line of the input contains a single integer n (1ββ€βnββ€β500β000)Β β the number of hashtags being edited now. Each of the next n lines contains exactly one hashtag of positive length. It is guaranteed that the total length of all hashtags (i.e. the total length of the string except for characters '#') won't exceed 500β000. | 1,800 | Print the resulting hashtags in any of the optimal solutions. | standard output | |
PASSED | 46f4f49dd556e022c633ef8240208325 | train_003.jsonl | 1487930700 | Vasya is an administrator of a public page of organization "Mouse and keyboard" and his everyday duty is to publish news from the world of competitive programming. For each news he also creates a list of hashtags to make searching for a particular topic more comfortable. For the purpose of this problem we define hashtag as a string consisting of lowercase English letters and exactly one symbol '#' located at the beginning of the string. The length of the hashtag is defined as the number of symbols in it without the symbol '#'.The head administrator of the page told Vasya that hashtags should go in lexicographical order (take a look at the notes section for the definition).Vasya is lazy so he doesn't want to actually change the order of hashtags in already published news. Instead, he decided to delete some suffixes (consecutive characters at the end of the string) of some of the hashtags. He is allowed to delete any number of characters, even the whole string except for the symbol '#'. Vasya wants to pick such a way to delete suffixes that the total number of deleted symbols is minimum possible. If there are several optimal solutions, he is fine with any of them. | 256 megabytes | /* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class codeforces implements Runnable
{
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 String nextLine()
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
public int nextInt()
{
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.')
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.')
{
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next()
{
return readString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
public static void main(String args[]) throws Exception
{
new Thread(null, new codeforces(),"codeforces",1<<26).start();
}
public void run() {
InputReader s = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int n = Integer.parseInt(s.next());
String str[] = new String[n];
for(int i = 0; i < n; i++)
str[i] = s.next();
outerloop:
for(int i = n - 2; i >= 0; i--) {
if(str[i].compareTo(str[i + 1]) <= 0) {
continue;
}
else {
int max = Math.min(str[i].length(), str[i + 1].length());
for(int j = 1; j < max; j++) {
if(str[i].charAt(j) > str[i + 1].charAt(j)) {
String temp = str[i].substring(0, j);
str[i] = temp;
continue outerloop;
}
}
String temp = str[i].substring(0, max);
str[i] = temp;
}
}
for(int i = 0; i < n; i++)
w.println(str[i]);
w.close();
}
}
| Java | ["3\n#book\n#bigtown\n#big", "3\n#book\n#cool\n#cold", "4\n#car\n#cart\n#art\n#at", "3\n#apple\n#apple\n#fruit"] | 2 seconds | ["#b\n#big\n#big", "#book\n#co\n#cold", "#\n#\n#art\n#at", "#apple\n#apple\n#fruit"] | NoteWord a1,βa2,β...,βam of length m is lexicographically not greater than word b1,βb2,β...,βbk of length k, if one of two conditions hold: at first position i, such that aiββ βbi, the character ai goes earlier in the alphabet than character bi, i.e. a has smaller character than b in the first position where they differ; if there is no such position i and mββ€βk, i.e. the first word is a prefix of the second or two words are equal. The sequence of words is said to be sorted in lexicographical order if each word (except the last one) is lexicographically not greater than the next word.For the words consisting of lowercase English letters the lexicographical order coincides with the alphabet word order in the dictionary.According to the above definition, if a hashtag consisting of one character '#' it is lexicographically not greater than any other valid hashtag. That's why in the third sample we can't keep first two hashtags unchanged and shorten the other two. | Java 8 | standard input | [
"binary search",
"implementation",
"greedy",
"strings"
] | 27baf9b1241c0f8e3a2037b18f39fe34 | The first line of the input contains a single integer n (1ββ€βnββ€β500β000)Β β the number of hashtags being edited now. Each of the next n lines contains exactly one hashtag of positive length. It is guaranteed that the total length of all hashtags (i.e. the total length of the string except for characters '#') won't exceed 500β000. | 1,800 | Print the resulting hashtags in any of the optimal solutions. | standard output | |
PASSED | b32eaa9cb598d98c15dfed7b481e8d6e | train_003.jsonl | 1487930700 | Vasya is an administrator of a public page of organization "Mouse and keyboard" and his everyday duty is to publish news from the world of competitive programming. For each news he also creates a list of hashtags to make searching for a particular topic more comfortable. For the purpose of this problem we define hashtag as a string consisting of lowercase English letters and exactly one symbol '#' located at the beginning of the string. The length of the hashtag is defined as the number of symbols in it without the symbol '#'.The head administrator of the page told Vasya that hashtags should go in lexicographical order (take a look at the notes section for the definition).Vasya is lazy so he doesn't want to actually change the order of hashtags in already published news. Instead, he decided to delete some suffixes (consecutive characters at the end of the string) of some of the hashtags. He is allowed to delete any number of characters, even the whole string except for the symbol '#'. Vasya wants to pick such a way to delete suffixes that the total number of deleted symbols is minimum possible. If there are several optimal solutions, he is fine with any of them. | 256 megabytes | import java.util.*;
import java.io.*;
public class A{
static boolean visited[];
public static void main(String[] args) {
MyScanner scan = new MyScanner();
int n = scan.nextInt();
String arr[] = new String[n];
for(int i = 0;i < n;i++)
arr[i] = scan.next();
String ot[] = new String[n];
for(int i = n-2;i >= 0;i--)
{
String g = arr[i+1];
String l = arr[i];
if(g.compareTo(l) >= 0)
continue;
int l1 = g.length();
int l2 = l.length();
String x = l.substring(0,Math.min(l1,l2));
if(g.compareTo(x) >=0)
{
arr[i] = x;
continue;
}
int j;
for( j = 0;j< Math.min(l1,l2);j++)
if(l.charAt(j) > g.charAt(j))
break;
arr[i] = l.substring(0,j);
}
PrintWriter pw = new PrintWriter(System.out);
for(int i = 0;i < n;i++)
pw.print(arr[i]+"\n");
pw.close();
}
}
class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public int mod(long x) {
// TODO Auto-generated method stub
return (int) x % 1000000007;
}
public int mod(int x) {
return x % 1000000007;
}
boolean hasNext() {
if (st.hasMoreElements())
return true;
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.hasMoreTokens();
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public long nextLong() {
return Long.parseLong(next());
}
} | Java | ["3\n#book\n#bigtown\n#big", "3\n#book\n#cool\n#cold", "4\n#car\n#cart\n#art\n#at", "3\n#apple\n#apple\n#fruit"] | 2 seconds | ["#b\n#big\n#big", "#book\n#co\n#cold", "#\n#\n#art\n#at", "#apple\n#apple\n#fruit"] | NoteWord a1,βa2,β...,βam of length m is lexicographically not greater than word b1,βb2,β...,βbk of length k, if one of two conditions hold: at first position i, such that aiββ βbi, the character ai goes earlier in the alphabet than character bi, i.e. a has smaller character than b in the first position where they differ; if there is no such position i and mββ€βk, i.e. the first word is a prefix of the second or two words are equal. The sequence of words is said to be sorted in lexicographical order if each word (except the last one) is lexicographically not greater than the next word.For the words consisting of lowercase English letters the lexicographical order coincides with the alphabet word order in the dictionary.According to the above definition, if a hashtag consisting of one character '#' it is lexicographically not greater than any other valid hashtag. That's why in the third sample we can't keep first two hashtags unchanged and shorten the other two. | Java 8 | standard input | [
"binary search",
"implementation",
"greedy",
"strings"
] | 27baf9b1241c0f8e3a2037b18f39fe34 | The first line of the input contains a single integer n (1ββ€βnββ€β500β000)Β β the number of hashtags being edited now. Each of the next n lines contains exactly one hashtag of positive length. It is guaranteed that the total length of all hashtags (i.e. the total length of the string except for characters '#') won't exceed 500β000. | 1,800 | Print the resulting hashtags in any of the optimal solutions. | standard output | |
PASSED | 24e2762c4f53e3377154598c07258abf | train_003.jsonl | 1487930700 | Vasya is an administrator of a public page of organization "Mouse and keyboard" and his everyday duty is to publish news from the world of competitive programming. For each news he also creates a list of hashtags to make searching for a particular topic more comfortable. For the purpose of this problem we define hashtag as a string consisting of lowercase English letters and exactly one symbol '#' located at the beginning of the string. The length of the hashtag is defined as the number of symbols in it without the symbol '#'.The head administrator of the page told Vasya that hashtags should go in lexicographical order (take a look at the notes section for the definition).Vasya is lazy so he doesn't want to actually change the order of hashtags in already published news. Instead, he decided to delete some suffixes (consecutive characters at the end of the string) of some of the hashtags. He is allowed to delete any number of characters, even the whole string except for the symbol '#'. Vasya wants to pick such a way to delete suffixes that the total number of deleted symbols is minimum possible. If there are several optimal solutions, he is fine with any of them. | 256 megabytes | import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Cf401D {
static MyScanner in = new MyScanner();
static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
public static void main(String[] args) {
int n = in.nextInt();
// int k = in.nextInt();
// long n = in.nextLong();
// long k = in.nextLong();
// String s = in.next();
String[] arr = new String[n];
for (int i = 0; i < n; i++) {
arr[i] = in.next();
}
for (int i = n - 2; i >= 0; i--) {
for (int j = 0; j < arr[i].length() && j < arr[i + 1].length(); j++) {
if (arr[i].charAt(j) > arr[i + 1].charAt(j)) {
arr[i] = arr[i].substring(0, j);
break;
} else if (arr[i].charAt(j) < arr[i + 1].charAt(j)) {
break;
}
if (j == arr[i + 1].length() - 1) {
arr[i] = arr[i].substring(0, j + 1);
}
}
}
for (String s : arr) {
out.println(s);
}
/*
* Dont delete
*/
out.close();
/*
*
*/
}
public static long GCD(long a, long b) {
return b == 0 ? a : GCD(b, a % b);
}
public static long LCM(long a, long b) {
return a * b / GCD(a, b);
}
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| Java | ["3\n#book\n#bigtown\n#big", "3\n#book\n#cool\n#cold", "4\n#car\n#cart\n#art\n#at", "3\n#apple\n#apple\n#fruit"] | 2 seconds | ["#b\n#big\n#big", "#book\n#co\n#cold", "#\n#\n#art\n#at", "#apple\n#apple\n#fruit"] | NoteWord a1,βa2,β...,βam of length m is lexicographically not greater than word b1,βb2,β...,βbk of length k, if one of two conditions hold: at first position i, such that aiββ βbi, the character ai goes earlier in the alphabet than character bi, i.e. a has smaller character than b in the first position where they differ; if there is no such position i and mββ€βk, i.e. the first word is a prefix of the second or two words are equal. The sequence of words is said to be sorted in lexicographical order if each word (except the last one) is lexicographically not greater than the next word.For the words consisting of lowercase English letters the lexicographical order coincides with the alphabet word order in the dictionary.According to the above definition, if a hashtag consisting of one character '#' it is lexicographically not greater than any other valid hashtag. That's why in the third sample we can't keep first two hashtags unchanged and shorten the other two. | Java 8 | standard input | [
"binary search",
"implementation",
"greedy",
"strings"
] | 27baf9b1241c0f8e3a2037b18f39fe34 | The first line of the input contains a single integer n (1ββ€βnββ€β500β000)Β β the number of hashtags being edited now. Each of the next n lines contains exactly one hashtag of positive length. It is guaranteed that the total length of all hashtags (i.e. the total length of the string except for characters '#') won't exceed 500β000. | 1,800 | Print the resulting hashtags in any of the optimal solutions. | standard output | |
PASSED | fe088a81a630046d4c8adac799ac79bb | train_003.jsonl | 1487930700 | Vasya is an administrator of a public page of organization "Mouse and keyboard" and his everyday duty is to publish news from the world of competitive programming. For each news he also creates a list of hashtags to make searching for a particular topic more comfortable. For the purpose of this problem we define hashtag as a string consisting of lowercase English letters and exactly one symbol '#' located at the beginning of the string. The length of the hashtag is defined as the number of symbols in it without the symbol '#'.The head administrator of the page told Vasya that hashtags should go in lexicographical order (take a look at the notes section for the definition).Vasya is lazy so he doesn't want to actually change the order of hashtags in already published news. Instead, he decided to delete some suffixes (consecutive characters at the end of the string) of some of the hashtags. He is allowed to delete any number of characters, even the whole string except for the symbol '#'. Vasya wants to pick such a way to delete suffixes that the total number of deleted symbols is minimum possible. If there are several optimal solutions, he is fine with any of them. | 256 megabytes | import java.io.*;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
public class D
{
String line;
StringTokenizer inputParser;
BufferedReader is;
FileInputStream fstream;
DataInputStream in;
void openInput(String file)
{
if(file==null)is = new BufferedReader(new InputStreamReader(System.in));//stdin
else
{
try{
fstream = new FileInputStream(file);
in = new DataInputStream(fstream);
is = new BufferedReader(new InputStreamReader(in));
}catch(Exception e)
{
System.err.println(e);
}
}
}
void readNextLine()
{
try {
line = is.readLine();
if(line!=null)inputParser = new StringTokenizer(line, " ");
//System.err.println("Input: " + line);
} catch (IOException e) {
System.err.println("Unexpected IO ERROR: " + e);
}
}
int NextInt()
{
String n = inputParser.nextToken();
int val = Integer.parseInt(n);
//System.out.println("I read this number: " + val);
return val;
}
double NextDouble()
{
String n = inputParser.nextToken();
double val = Double.parseDouble(n);
//System.out.println("I read this number: " + val);
return val;
}
long NextLong()
{
String n = inputParser.nextToken();
long val = Long.parseLong(n);
return val;
}
String NextString()
{
String n = inputParser.nextToken();
return n;
}
void closeInput()
{
try {
is.close();
} catch (IOException e) {
System.err.println("Unexpected IO ERROR: " + e);
}
}
public static void main(String [] argv)
{
String filePath=null;
if(argv.length>0)filePath=argv[0];
new D(filePath);
}
public D(String inputFile)
{
openInput(inputFile);
//readNextLine();
int T=1;//NextInt();
StringBuilder sb = new StringBuilder();
for(int t=1; t<=T; t++)
{
readNextLine();
int N=NextInt();
String [] a = new String[N];
for(int i=0; i<N; i++)
{
readNextLine();
a[i] = line;
}
for(int i=N-2; i>=0; i--)
{
for(int j=0; j<a[i].length(); j++)
{
if(a[i+1].length()<=j||a[i].charAt(j)>a[i+1].charAt(j))
{
a[i] = a[i].substring(0, j);
break;
}
else if(a[i+1].charAt(j)>a[i].charAt(j))break;
}
}
for(int i=0; i<N; i++)
sb.append(a[i]+"\n");
}
System.out.print(sb);
closeInput();
}
} | Java | ["3\n#book\n#bigtown\n#big", "3\n#book\n#cool\n#cold", "4\n#car\n#cart\n#art\n#at", "3\n#apple\n#apple\n#fruit"] | 2 seconds | ["#b\n#big\n#big", "#book\n#co\n#cold", "#\n#\n#art\n#at", "#apple\n#apple\n#fruit"] | NoteWord a1,βa2,β...,βam of length m is lexicographically not greater than word b1,βb2,β...,βbk of length k, if one of two conditions hold: at first position i, such that aiββ βbi, the character ai goes earlier in the alphabet than character bi, i.e. a has smaller character than b in the first position where they differ; if there is no such position i and mββ€βk, i.e. the first word is a prefix of the second or two words are equal. The sequence of words is said to be sorted in lexicographical order if each word (except the last one) is lexicographically not greater than the next word.For the words consisting of lowercase English letters the lexicographical order coincides with the alphabet word order in the dictionary.According to the above definition, if a hashtag consisting of one character '#' it is lexicographically not greater than any other valid hashtag. That's why in the third sample we can't keep first two hashtags unchanged and shorten the other two. | Java 8 | standard input | [
"binary search",
"implementation",
"greedy",
"strings"
] | 27baf9b1241c0f8e3a2037b18f39fe34 | The first line of the input contains a single integer n (1ββ€βnββ€β500β000)Β β the number of hashtags being edited now. Each of the next n lines contains exactly one hashtag of positive length. It is guaranteed that the total length of all hashtags (i.e. the total length of the string except for characters '#') won't exceed 500β000. | 1,800 | Print the resulting hashtags in any of the optimal solutions. | standard output | |
PASSED | 0a324ded1fbcf7ea21bba7a09880e796 | train_003.jsonl | 1487930700 | Vasya is an administrator of a public page of organization "Mouse and keyboard" and his everyday duty is to publish news from the world of competitive programming. For each news he also creates a list of hashtags to make searching for a particular topic more comfortable. For the purpose of this problem we define hashtag as a string consisting of lowercase English letters and exactly one symbol '#' located at the beginning of the string. The length of the hashtag is defined as the number of symbols in it without the symbol '#'.The head administrator of the page told Vasya that hashtags should go in lexicographical order (take a look at the notes section for the definition).Vasya is lazy so he doesn't want to actually change the order of hashtags in already published news. Instead, he decided to delete some suffixes (consecutive characters at the end of the string) of some of the hashtags. He is allowed to delete any number of characters, even the whole string except for the symbol '#'. Vasya wants to pick such a way to delete suffixes that the total number of deleted symbols is minimum possible. If there are several optimal solutions, he is fine with any of them. | 256 megabytes | import java.util.*;
import java.io.*;
public class d{
static InputReader in = new InputReader(System.in);
static PrintWriter out = new PrintWriter(System.out);
String str(char[] s){
return new String(s);
}
char[] ta(String s){
return s.toCharArray();
}
void solve(){
int n = in.nextInt();
char[][] a = new char[n][0];
for(int i=0; i<n; i++){
a[i] = ta(in.next());
}
for(int i=n-2; i>=0; i--){
if(str(a[i]).compareTo(str(a[i+1])) < 0) continue;
int m = Math.min(a[i].length, a[i+1].length);
int l = m;
for(int j=0; j < m; j++){
if(a[i][j] != a[i+1][j]){
l = j;
break;
}
}
a[i] = ta(str(a[i]).substring(0,l));
}
for(int i=0; i<n; i++) out.println(str(a[i]));
}
public static void main(String[] args){
d m = new d();
m.solve();
out.flush();
out.close();
}
static class InputReader{
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream instream){
reader = new BufferedReader(new InputStreamReader(instream), 1<<15);
tokenizer = null;
}
public String next(){
while(tokenizer == null || !tokenizer.hasMoreTokens()){
try{
tokenizer = new StringTokenizer(reader.readLine());
}catch(Exception e){
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public String nextLine(){
try{
return reader.readLine();
}catch(Exception e){
throw new RuntimeException(e);
}
}
public int nextInt(){
return Integer.parseInt(next());
}
public long nextLong(){
return Long.parseLong(next());
}
public double nextDouble(){
return Double.parseDouble(next());
}
}
}
| Java | ["3\n#book\n#bigtown\n#big", "3\n#book\n#cool\n#cold", "4\n#car\n#cart\n#art\n#at", "3\n#apple\n#apple\n#fruit"] | 2 seconds | ["#b\n#big\n#big", "#book\n#co\n#cold", "#\n#\n#art\n#at", "#apple\n#apple\n#fruit"] | NoteWord a1,βa2,β...,βam of length m is lexicographically not greater than word b1,βb2,β...,βbk of length k, if one of two conditions hold: at first position i, such that aiββ βbi, the character ai goes earlier in the alphabet than character bi, i.e. a has smaller character than b in the first position where they differ; if there is no such position i and mββ€βk, i.e. the first word is a prefix of the second or two words are equal. The sequence of words is said to be sorted in lexicographical order if each word (except the last one) is lexicographically not greater than the next word.For the words consisting of lowercase English letters the lexicographical order coincides with the alphabet word order in the dictionary.According to the above definition, if a hashtag consisting of one character '#' it is lexicographically not greater than any other valid hashtag. That's why in the third sample we can't keep first two hashtags unchanged and shorten the other two. | Java 8 | standard input | [
"binary search",
"implementation",
"greedy",
"strings"
] | 27baf9b1241c0f8e3a2037b18f39fe34 | The first line of the input contains a single integer n (1ββ€βnββ€β500β000)Β β the number of hashtags being edited now. Each of the next n lines contains exactly one hashtag of positive length. It is guaranteed that the total length of all hashtags (i.e. the total length of the string except for characters '#') won't exceed 500β000. | 1,800 | Print the resulting hashtags in any of the optimal solutions. | standard output | |
PASSED | 61ac9d5335fa19dbb43837dfa1403cd4 | train_003.jsonl | 1487930700 | Vasya is an administrator of a public page of organization "Mouse and keyboard" and his everyday duty is to publish news from the world of competitive programming. For each news he also creates a list of hashtags to make searching for a particular topic more comfortable. For the purpose of this problem we define hashtag as a string consisting of lowercase English letters and exactly one symbol '#' located at the beginning of the string. The length of the hashtag is defined as the number of symbols in it without the symbol '#'.The head administrator of the page told Vasya that hashtags should go in lexicographical order (take a look at the notes section for the definition).Vasya is lazy so he doesn't want to actually change the order of hashtags in already published news. Instead, he decided to delete some suffixes (consecutive characters at the end of the string) of some of the hashtags. He is allowed to delete any number of characters, even the whole string except for the symbol '#'. Vasya wants to pick such a way to delete suffixes that the total number of deleted symbols is minimum possible. If there are several optimal solutions, he is fine with any of them. | 256 megabytes | import java.util.*;
import java.io.*;
public class d{
static InputReader in = new InputReader(System.in);
static PrintWriter out = new PrintWriter(System.out);
char[] ta(String s){
return s.toCharArray();
}
void solve(){
int n = in.nextInt();;
String[] s = new String[n];
for(int i=0; i<n; i++) s[i] = in.next();
for(int i=n-2; i>=0; i--){
if(s[i].compareTo(s[i+1]) < 0) continue;
int m = Math.min(s[i].length(), s[i+1].length());
int l = m;
char[] a = ta(s[i]);
char[] b = ta(s[i+1]);
for(int j=0; j<m; j++){
if(a[j] != b[j]){
l = j;
break;
}
}
s[i] = s[i].substring(0,l);
}
for(int i=0; i<n; i++) out.println(s[i]);
}
public static void main(String[] args){
d m = new d();
m.solve();
out.flush();
out.close();
}
static class InputReader{
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream instream){
reader = new BufferedReader(new InputStreamReader(instream), 1<<15);
tokenizer = null;
}
public String next(){
while(tokenizer == null || !tokenizer.hasMoreTokens()){
try{
tokenizer = new StringTokenizer(reader.readLine());
}catch(Exception e){
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public String nextLine(){
try{
return reader.readLine();
}catch(Exception e){
throw new RuntimeException(e);
}
}
public int nextInt(){
return Integer.parseInt(next());
}
public long nextLong(){
return Long.parseLong(next());
}
public double nextDouble(){
return Double.parseDouble(next());
}
}
}
| Java | ["3\n#book\n#bigtown\n#big", "3\n#book\n#cool\n#cold", "4\n#car\n#cart\n#art\n#at", "3\n#apple\n#apple\n#fruit"] | 2 seconds | ["#b\n#big\n#big", "#book\n#co\n#cold", "#\n#\n#art\n#at", "#apple\n#apple\n#fruit"] | NoteWord a1,βa2,β...,βam of length m is lexicographically not greater than word b1,βb2,β...,βbk of length k, if one of two conditions hold: at first position i, such that aiββ βbi, the character ai goes earlier in the alphabet than character bi, i.e. a has smaller character than b in the first position where they differ; if there is no such position i and mββ€βk, i.e. the first word is a prefix of the second or two words are equal. The sequence of words is said to be sorted in lexicographical order if each word (except the last one) is lexicographically not greater than the next word.For the words consisting of lowercase English letters the lexicographical order coincides with the alphabet word order in the dictionary.According to the above definition, if a hashtag consisting of one character '#' it is lexicographically not greater than any other valid hashtag. That's why in the third sample we can't keep first two hashtags unchanged and shorten the other two. | Java 8 | standard input | [
"binary search",
"implementation",
"greedy",
"strings"
] | 27baf9b1241c0f8e3a2037b18f39fe34 | The first line of the input contains a single integer n (1ββ€βnββ€β500β000)Β β the number of hashtags being edited now. Each of the next n lines contains exactly one hashtag of positive length. It is guaranteed that the total length of all hashtags (i.e. the total length of the string except for characters '#') won't exceed 500β000. | 1,800 | Print the resulting hashtags in any of the optimal solutions. | standard output | |
PASSED | f29b657de18eda0b5dc4c1e2f9430d62 | train_003.jsonl | 1487930700 | Vasya is an administrator of a public page of organization "Mouse and keyboard" and his everyday duty is to publish news from the world of competitive programming. For each news he also creates a list of hashtags to make searching for a particular topic more comfortable. For the purpose of this problem we define hashtag as a string consisting of lowercase English letters and exactly one symbol '#' located at the beginning of the string. The length of the hashtag is defined as the number of symbols in it without the symbol '#'.The head administrator of the page told Vasya that hashtags should go in lexicographical order (take a look at the notes section for the definition).Vasya is lazy so he doesn't want to actually change the order of hashtags in already published news. Instead, he decided to delete some suffixes (consecutive characters at the end of the string) of some of the hashtags. He is allowed to delete any number of characters, even the whole string except for the symbol '#'. Vasya wants to pick such a way to delete suffixes that the total number of deleted symbols is minimum possible. If there are several optimal solutions, he is fine with any of them. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
PrintWriter pw=new PrintWriter(System.out);
while(sc.hasNext()){
int n=sc.nextInt();
String[]s=new String [n];
for(int i=0;i<n;i++){
s[i]=sc.next();
}
for(int i=n-1;i>=1;i--){
int flag=0;
int temp=Math.min(s[i].length(), s[i-1].length());
for(int j=1;j<temp;j++){
if(s[i-1].charAt(j)<s[i].charAt(j)){
flag=2;
break;
}
if(s[i-1].charAt(j)>s[i].charAt(j)){
s[i-1]=s[i-1].substring(0, j);
flag=1;
break;
}
}
if(flag==0){
if(s[i-1].length()>s[i].length())
if(s[i-1].charAt(s[i].length()-1)==s[i].charAt(s[i].length()-1))
s[i-1]=s[i-1].substring(0, s[i].length());
}
}
for(int i=0;i<n;i++){
pw.println(s[i]);
}
pw.flush();
}
}
} | Java | ["3\n#book\n#bigtown\n#big", "3\n#book\n#cool\n#cold", "4\n#car\n#cart\n#art\n#at", "3\n#apple\n#apple\n#fruit"] | 2 seconds | ["#b\n#big\n#big", "#book\n#co\n#cold", "#\n#\n#art\n#at", "#apple\n#apple\n#fruit"] | NoteWord a1,βa2,β...,βam of length m is lexicographically not greater than word b1,βb2,β...,βbk of length k, if one of two conditions hold: at first position i, such that aiββ βbi, the character ai goes earlier in the alphabet than character bi, i.e. a has smaller character than b in the first position where they differ; if there is no such position i and mββ€βk, i.e. the first word is a prefix of the second or two words are equal. The sequence of words is said to be sorted in lexicographical order if each word (except the last one) is lexicographically not greater than the next word.For the words consisting of lowercase English letters the lexicographical order coincides with the alphabet word order in the dictionary.According to the above definition, if a hashtag consisting of one character '#' it is lexicographically not greater than any other valid hashtag. That's why in the third sample we can't keep first two hashtags unchanged and shorten the other two. | Java 8 | standard input | [
"binary search",
"implementation",
"greedy",
"strings"
] | 27baf9b1241c0f8e3a2037b18f39fe34 | The first line of the input contains a single integer n (1ββ€βnββ€β500β000)Β β the number of hashtags being edited now. Each of the next n lines contains exactly one hashtag of positive length. It is guaranteed that the total length of all hashtags (i.e. the total length of the string except for characters '#') won't exceed 500β000. | 1,800 | Print the resulting hashtags in any of the optimal solutions. | standard output | |
PASSED | 1302a2535dc6877d6f90c2393d505651 | train_003.jsonl | 1487930700 | Vasya is an administrator of a public page of organization "Mouse and keyboard" and his everyday duty is to publish news from the world of competitive programming. For each news he also creates a list of hashtags to make searching for a particular topic more comfortable. For the purpose of this problem we define hashtag as a string consisting of lowercase English letters and exactly one symbol '#' located at the beginning of the string. The length of the hashtag is defined as the number of symbols in it without the symbol '#'.The head administrator of the page told Vasya that hashtags should go in lexicographical order (take a look at the notes section for the definition).Vasya is lazy so he doesn't want to actually change the order of hashtags in already published news. Instead, he decided to delete some suffixes (consecutive characters at the end of the string) of some of the hashtags. He is allowed to delete any number of characters, even the whole string except for the symbol '#'. Vasya wants to pick such a way to delete suffixes that the total number of deleted symbols is minimum possible. If there are several optimal solutions, he is fine with any of them. | 256 megabytes | import java.util.*;
import java.io.*;
public class main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
while(sc.hasNext()){
int n = sc.nextInt();
String[] s = new String [n];
for(int i = 0; i < n; i++){
s[i] = sc.next();
}
for(int i = n - 1; i > 0; i--){
int ok = 0;
int si = s[i].length();
int sj = s[i-1].length();
int size = Math.min(si, sj);
for(int j = 1; j < size; j++){
if(s[i].charAt(j) > s[i-1].charAt(j)){
ok = 1;
break;
}
if(s[i].charAt(j) < s[i-1].charAt(j)){
s[i-1] = s[i-1].substring(0, j);
ok = 1;
break;
}
}
if(ok == 0){
if(si < sj){
if(s[i].charAt(si-1) == s[i-1].charAt(si-1)){
s[i-1] = s[i-1].substring(0, si);
}
}
}
}
for(int i = 0; i < n; i++){
pw.println(s[i]);
}
pw.flush();
}
sc.close();
}
} | Java | ["3\n#book\n#bigtown\n#big", "3\n#book\n#cool\n#cold", "4\n#car\n#cart\n#art\n#at", "3\n#apple\n#apple\n#fruit"] | 2 seconds | ["#b\n#big\n#big", "#book\n#co\n#cold", "#\n#\n#art\n#at", "#apple\n#apple\n#fruit"] | NoteWord a1,βa2,β...,βam of length m is lexicographically not greater than word b1,βb2,β...,βbk of length k, if one of two conditions hold: at first position i, such that aiββ βbi, the character ai goes earlier in the alphabet than character bi, i.e. a has smaller character than b in the first position where they differ; if there is no such position i and mββ€βk, i.e. the first word is a prefix of the second or two words are equal. The sequence of words is said to be sorted in lexicographical order if each word (except the last one) is lexicographically not greater than the next word.For the words consisting of lowercase English letters the lexicographical order coincides with the alphabet word order in the dictionary.According to the above definition, if a hashtag consisting of one character '#' it is lexicographically not greater than any other valid hashtag. That's why in the third sample we can't keep first two hashtags unchanged and shorten the other two. | Java 8 | standard input | [
"binary search",
"implementation",
"greedy",
"strings"
] | 27baf9b1241c0f8e3a2037b18f39fe34 | The first line of the input contains a single integer n (1ββ€βnββ€β500β000)Β β the number of hashtags being edited now. Each of the next n lines contains exactly one hashtag of positive length. It is guaranteed that the total length of all hashtags (i.e. the total length of the string except for characters '#') won't exceed 500β000. | 1,800 | Print the resulting hashtags in any of the optimal solutions. | standard output | |
PASSED | 5bb0b95c87ee301b58aec55a26bb22e2 | train_003.jsonl | 1487930700 | Vasya is an administrator of a public page of organization "Mouse and keyboard" and his everyday duty is to publish news from the world of competitive programming. For each news he also creates a list of hashtags to make searching for a particular topic more comfortable. For the purpose of this problem we define hashtag as a string consisting of lowercase English letters and exactly one symbol '#' located at the beginning of the string. The length of the hashtag is defined as the number of symbols in it without the symbol '#'.The head administrator of the page told Vasya that hashtags should go in lexicographical order (take a look at the notes section for the definition).Vasya is lazy so he doesn't want to actually change the order of hashtags in already published news. Instead, he decided to delete some suffixes (consecutive characters at the end of the string) of some of the hashtags. He is allowed to delete any number of characters, even the whole string except for the symbol '#'. Vasya wants to pick such a way to delete suffixes that the total number of deleted symbols is minimum possible. If there are several optimal solutions, he is fine with any of them. | 256 megabytes | //package codeforces.round401;
import java.io.*;
import java.util.StringTokenizer;
/**
* Created by shirsh.bansal on 24/02/17.
*/
public class Main {
public static void main(String[] args) throws IOException {
FastScanner scanner = new FastScanner();
OutputWriter outputWriter = new OutputWriter(System.out);
int n = scanner.nextInt();
String s[] = new String[n];
for (int i = 0; i < n; i++) {
s[i] = scanner.next();
}
String ans[] = new String[n];
ans[n-1] = new String(s[n-1]);
// StringBuilder finalAns = new StringBuilder(ans[n-1]);
for (int i = n-1; i >= 1; i--) {
StringBuilder builder = new StringBuilder();
int l = Math.min(ans[i].length(), s[i-1].length());
int j = 1;
while (j < l && ans[i].charAt(j) == s[i-1].charAt(j)){
j++;
}
if((j < l && ans[i].charAt(j) < s[i-1].charAt(j)) || (j == l && ans[i].length() < s[i-1].length())) {
ans[i-1] = builder.append(s[i-1], 0, j).toString();
} else {
ans[i-1] = builder.append(s[i-1]).toString();
}
// finalAns.append("\n");
// finalAns.append(ans[i-1]);
}
for (int i = 0; i < n; i++) {
outputWriter.printLine(ans[i]);
// System.out.println(ans[i]);
}
outputWriter.flush();
outputWriter.close();
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object...objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object...objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
}
}
| Java | ["3\n#book\n#bigtown\n#big", "3\n#book\n#cool\n#cold", "4\n#car\n#cart\n#art\n#at", "3\n#apple\n#apple\n#fruit"] | 2 seconds | ["#b\n#big\n#big", "#book\n#co\n#cold", "#\n#\n#art\n#at", "#apple\n#apple\n#fruit"] | NoteWord a1,βa2,β...,βam of length m is lexicographically not greater than word b1,βb2,β...,βbk of length k, if one of two conditions hold: at first position i, such that aiββ βbi, the character ai goes earlier in the alphabet than character bi, i.e. a has smaller character than b in the first position where they differ; if there is no such position i and mββ€βk, i.e. the first word is a prefix of the second or two words are equal. The sequence of words is said to be sorted in lexicographical order if each word (except the last one) is lexicographically not greater than the next word.For the words consisting of lowercase English letters the lexicographical order coincides with the alphabet word order in the dictionary.According to the above definition, if a hashtag consisting of one character '#' it is lexicographically not greater than any other valid hashtag. That's why in the third sample we can't keep first two hashtags unchanged and shorten the other two. | Java 8 | standard input | [
"binary search",
"implementation",
"greedy",
"strings"
] | 27baf9b1241c0f8e3a2037b18f39fe34 | The first line of the input contains a single integer n (1ββ€βnββ€β500β000)Β β the number of hashtags being edited now. Each of the next n lines contains exactly one hashtag of positive length. It is guaranteed that the total length of all hashtags (i.e. the total length of the string except for characters '#') won't exceed 500β000. | 1,800 | Print the resulting hashtags in any of the optimal solutions. | standard output | |
PASSED | b6464ba8e2887756d95f5717a3e42d30 | train_003.jsonl | 1487930700 | Vasya is an administrator of a public page of organization "Mouse and keyboard" and his everyday duty is to publish news from the world of competitive programming. For each news he also creates a list of hashtags to make searching for a particular topic more comfortable. For the purpose of this problem we define hashtag as a string consisting of lowercase English letters and exactly one symbol '#' located at the beginning of the string. The length of the hashtag is defined as the number of symbols in it without the symbol '#'.The head administrator of the page told Vasya that hashtags should go in lexicographical order (take a look at the notes section for the definition).Vasya is lazy so he doesn't want to actually change the order of hashtags in already published news. Instead, he decided to delete some suffixes (consecutive characters at the end of the string) of some of the hashtags. He is allowed to delete any number of characters, even the whole string except for the symbol '#'. Vasya wants to pick such a way to delete suffixes that the total number of deleted symbols is minimum possible. If there are several optimal solutions, he is fine with any of them. | 256 megabytes | // nice question I Like it
import java.util.*;
import java.io.*;
public class lp1{
static int count(String s1,String s2,int l2) // s2>=s1 // it will give length of string s1 which needs to be removed
{
int i1=0,i2=0;
while(i1<s1.length()&&i2<l2)
{
if(s1.charAt(i1)<s2.charAt(i2))
return 0;
if(s1.charAt(i1)>s2.charAt(i2))
break;
i1++;i2++;
}
if(i1<s1.length())
return s1.length()-i1;
return 0;
}
static boolean ok(int mid,String str[],int n,int a[])
{
int p=str[n-1].length(),ans=0; a[n-1]=p;
for(int i=n-2;i>=0;i--){
int at= count(str[i],str[i+1],p);
ans = ans + at;
p = str[i].length()-at;
a[i]=p;
}
if(ans<=mid)
return true;
return false;
}
public static void main(String[] args){
int n = ni();
String str[] = new String[n];
int a[] = new int[n];
int sum=0;
for(int i=0;i<n;i++)
{
str[i] = n();
sum = sum + str[i].length();
}
int l=-1,r=sum;
while((r-l)>1)
{
int mid = (l+r)/2;
if(ok(mid,str,n,a))
r=mid ;
else
l=mid;
}
ok(r,str,n,a);
for(int i=0;i<n;i++)
{
for(int j=0;j<a[i];j++)
p(str[i].charAt(j));
pn("");
}
out.flush();
}
static class pair
{
int a,b;
pair(){}
pair(int c,int d){a=c;b=d;}
@Override
public int hashCode(){return (a+" "+b).hashCode();}
@Override public boolean equals(Object c){if(a==((pair)c).a&&b==((pair)c).b)return true;return false;}
}
static int get(int index)
{
return (index&(-index));
}
static void add(int bit[],int index,int val)
{
while(index<bit.length)
{
bit[index] = bit[index]+val;
index = index + get(index);
}
}
static int get(int bit[],int index)
{
int sum=0;
while(index>0)
{
sum = sum+bit[index];
index = index-get(index);
}
return sum;
}
static void add(long bit[],int index,long val)
{
while(index<bit.length)
{
bit[index] = bit[index]+val;
index = index + get(index);
}
}
static long get(long bit[],int index)
{
long sum=0;
while(index>0)
{
sum = sum+bit[index];
index = index-get(index);
}
return sum;
}
static void compress(int a[])
{
int n = a.length;
Integer ar[] = new Integer[n];
for(int i=0;i<n;i++)
ar[i] = a[i];
Arrays.sort(ar);
HashMap<Integer,Integer> hm = new HashMap();
int st=1;
for(int i=0;i<n;i++)
if(!hm.containsKey(ar[i]))
hm.put(ar[i],st++);
for(int i=0;i<n;i++)
a[i] = hm.get(a[i]);
}
static int find(int x,int p[]){ if(x==p[x]) return x; return p[x]=find(p[x],p) ;}
static void union(int x,int y,int p[]){ int xr=find(x,p),yr=find(y,p); if(xr!=yr){ p[xr]=yr;} }
static int abs(int x){ return x>0 ? x : -x; }
static long abs(long x){ return x>0 ? x : -x; }
static long gcd(long a,long b){ if(a==0)return b; if(b==0) return a;if(b%a==0) return a;return gcd(b%a,a); }
static int gcd(int a,int b){ if(a==0)return b; if(b==0) return a; if(b%a==0) return a;return gcd(b%a,a); }
static long min(long a,long b){ return a<b ? a : b; }
static int min(int a,int b){ return a<b ? a : b; }
static long max(long a,long b){ return a>b ? a : b; }
static int max(int a,int b){ return a>b ? a : b; }
static long pow(long a,long b,long md){ long ans=1; while(b>0){if(b%2==1) ans = (ans*a)%md; a = (a*a)%md; b = b/2;} return ans; }
static int log2n(long a){ int te=0; while(a>0) {a>>=1; ++te; } return te; }
static void subtract_1(char s[]){if(s[0]=='0') return;int n = s.length,i=n-1;while(s[i]=='0')i--;s[i] =(char)((int)(s[i]-'0') + 47);for(int j=i+1;j<n;j++)s[j]='9';}
static void reverse(char s[]){int i1=0,i2=s.length-1; while(i1<i2){char t=s[i1];s[i1]=s[i2];s[i2]=t; i1++;i2--;} }
static String reverse(String r){String s = "";int i= r.length()-1; while(i>=0){ s=s+r.charAt(i);i--;}return s;}
static boolean pal(char s[]){ int i1=0,i2=s.length-1; while(i1<i2){ if(s[i1]!=s[i2]) return false; i1++;i2--;} return true;}
static boolean pal(String s){int n = s.length(),i1=0,i2=n-1;while(i1<i2){if(s.charAt(i1)!=s.charAt(i2))return false;i1++; i2--;}return true;}
// Input OutPut Functions
static PrintWriter out = new PrintWriter(System.out);
static FastReader sc=new FastReader();
static int ni(){ int x = sc.nextInt();return(x); }
static long nl(){ long x = sc.nextLong(); return(x); }
static String n(){ String str = sc.next(); return(str); }
static String ns(){ String str = sc.nextLine(); return(str);}
static double nd(){double d = sc.nextDouble(); return(d); }
static int[] ai(int n){ int a[] = new int[n]; for(int i=0;i<n;i++) a[i] = ni(); return a; }
static long[] al(int n) {long a[] = new long[n]; for(int i=0;i<n;i++) a[i] = nl(); return a; }
static double[] ad(int n) { double a[]= new double[n]; for(int i=0;i<n;i++) a[i]=nd(); return a;}
static String[] as(int n){ String a[] = new String[n]; for(int i=0;i<n;i++) a[i] = n(); return a; }
static void p(Object o){ out.print(o); }
static void pn(Object o){ out.println(o); }
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\n#book\n#bigtown\n#big", "3\n#book\n#cool\n#cold", "4\n#car\n#cart\n#art\n#at", "3\n#apple\n#apple\n#fruit"] | 2 seconds | ["#b\n#big\n#big", "#book\n#co\n#cold", "#\n#\n#art\n#at", "#apple\n#apple\n#fruit"] | NoteWord a1,βa2,β...,βam of length m is lexicographically not greater than word b1,βb2,β...,βbk of length k, if one of two conditions hold: at first position i, such that aiββ βbi, the character ai goes earlier in the alphabet than character bi, i.e. a has smaller character than b in the first position where they differ; if there is no such position i and mββ€βk, i.e. the first word is a prefix of the second or two words are equal. The sequence of words is said to be sorted in lexicographical order if each word (except the last one) is lexicographically not greater than the next word.For the words consisting of lowercase English letters the lexicographical order coincides with the alphabet word order in the dictionary.According to the above definition, if a hashtag consisting of one character '#' it is lexicographically not greater than any other valid hashtag. That's why in the third sample we can't keep first two hashtags unchanged and shorten the other two. | Java 8 | standard input | [
"binary search",
"implementation",
"greedy",
"strings"
] | 27baf9b1241c0f8e3a2037b18f39fe34 | The first line of the input contains a single integer n (1ββ€βnββ€β500β000)Β β the number of hashtags being edited now. Each of the next n lines contains exactly one hashtag of positive length. It is guaranteed that the total length of all hashtags (i.e. the total length of the string except for characters '#') won't exceed 500β000. | 1,800 | Print the resulting hashtags in any of the optimal solutions. | standard output | |
PASSED | 2938e102a25b16eb2263dbde235ef27f | train_003.jsonl | 1487930700 | Vasya is an administrator of a public page of organization "Mouse and keyboard" and his everyday duty is to publish news from the world of competitive programming. For each news he also creates a list of hashtags to make searching for a particular topic more comfortable. For the purpose of this problem we define hashtag as a string consisting of lowercase English letters and exactly one symbol '#' located at the beginning of the string. The length of the hashtag is defined as the number of symbols in it without the symbol '#'.The head administrator of the page told Vasya that hashtags should go in lexicographical order (take a look at the notes section for the definition).Vasya is lazy so he doesn't want to actually change the order of hashtags in already published news. Instead, he decided to delete some suffixes (consecutive characters at the end of the string) of some of the hashtags. He is allowed to delete any number of characters, even the whole string except for the symbol '#'. Vasya wants to pick such a way to delete suffixes that the total number of deleted symbols is minimum possible. If there are several optimal solutions, he is fine with any of them. | 256 megabytes | import java.util.*;
import java.io.*;
public class lp1{
static int count(String s1,String s2,int l2) // s2>=s1
{
int i1=0,i2=0;
while(i1<s1.length()&&i2<l2)
{
if(s1.charAt(i1)<s2.charAt(i2))
return 0;
if(s1.charAt(i1)>s2.charAt(i2))
break;
i1++;i2++;
}
if(i1<s1.length())
return s1.length()-i1;
return 0;
}
static boolean ok(int mid,String str[],int n,int a[])
{
int p=str[n-1].length(),ans=0; a[n-1]=p;
for(int i=n-2;i>=0;i--){
int at= count(str[i],str[i+1],p);
ans = ans + at;
p = str[i].length()-at;
a[i]=p;
}
if(ans<=mid)
return true;
return false;
}
public static void main(String[] args){
int n = ni();
String str[] = new String[n];
int a[] = new int[n];
int sum=0;
for(int i=0;i<n;i++)
{
str[i] = n();
sum = sum + str[i].length();
}
int l=-1,r=sum;
while((r-l)>1)
{
int mid = (l+r)/2;
if(ok(mid,str,n,a))
r=mid ;
else
l=mid;
}
ok(r,str,n,a);
for(int i=0;i<n;i++)
{
for(int j=0;j<a[i];j++)
p(str[i].charAt(j));
pn("");
}
out.flush();
}
static class pair
{
int a,b;
pair(){}
pair(int c,int d){a=c;b=d;}
@Override
public int hashCode(){return (a+" "+b).hashCode();}
@Override public boolean equals(Object c){if(a==((pair)c).a&&b==((pair)c).b)return true;return false;}
}
static int get(int index)
{
return (index&(-index));
}
static void add(int bit[],int index,int val)
{
while(index<bit.length)
{
bit[index] = bit[index]+val;
index = index + get(index);
}
}
static int get(int bit[],int index)
{
int sum=0;
while(index>0)
{
sum = sum+bit[index];
index = index-get(index);
}
return sum;
}
static void add(long bit[],int index,long val)
{
while(index<bit.length)
{
bit[index] = bit[index]+val;
index = index + get(index);
}
}
static long get(long bit[],int index)
{
long sum=0;
while(index>0)
{
sum = sum+bit[index];
index = index-get(index);
}
return sum;
}
static void compress(int a[])
{
int n = a.length;
Integer ar[] = new Integer[n];
for(int i=0;i<n;i++)
ar[i] = a[i];
Arrays.sort(ar);
HashMap<Integer,Integer> hm = new HashMap();
int st=1;
for(int i=0;i<n;i++)
if(!hm.containsKey(ar[i]))
hm.put(ar[i],st++);
for(int i=0;i<n;i++)
a[i] = hm.get(a[i]);
}
static int find(int x,int p[]){ if(x==p[x]) return x; return p[x]=find(p[x],p) ;}
static void union(int x,int y,int p[]){ int xr=find(x,p),yr=find(y,p); if(xr!=yr){ p[xr]=yr;} }
static int abs(int x){ return x>0 ? x : -x; }
static long abs(long x){ return x>0 ? x : -x; }
static long gcd(long a,long b){ if(a==0)return b; if(b==0) return a;if(b%a==0) return a;return gcd(b%a,a); }
static int gcd(int a,int b){ if(a==0)return b; if(b==0) return a; if(b%a==0) return a;return gcd(b%a,a); }
static long min(long a,long b){ return a<b ? a : b; }
static int min(int a,int b){ return a<b ? a : b; }
static long max(long a,long b){ return a>b ? a : b; }
static int max(int a,int b){ return a>b ? a : b; }
static long pow(long a,long b,long md){ long ans=1; while(b>0){if(b%2==1) ans = (ans*a)%md; a = (a*a)%md; b = b/2;} return ans; }
static int log2n(long a){ int te=0; while(a>0) {a>>=1; ++te; } return te; }
static void subtract_1(char s[]){if(s[0]=='0') return;int n = s.length,i=n-1;while(s[i]=='0')i--;s[i] =(char)((int)(s[i]-'0') + 47);for(int j=i+1;j<n;j++)s[j]='9';}
static void reverse(char s[]){int i1=0,i2=s.length-1; while(i1<i2){char t=s[i1];s[i1]=s[i2];s[i2]=t; i1++;i2--;} }
static String reverse(String r){String s = "";int i= r.length()-1; while(i>=0){ s=s+r.charAt(i);i--;}return s;}
static boolean pal(char s[]){ int i1=0,i2=s.length-1; while(i1<i2){ if(s[i1]!=s[i2]) return false; i1++;i2--;} return true;}
static boolean pal(String s){int n = s.length(),i1=0,i2=n-1;while(i1<i2){if(s.charAt(i1)!=s.charAt(i2))return false;i1++; i2--;}return true;}
// Input OutPut Functions
static PrintWriter out = new PrintWriter(System.out);
static FastReader sc=new FastReader();
static int ni(){ int x = sc.nextInt();return(x); }
static long nl(){ long x = sc.nextLong(); return(x); }
static String n(){ String str = sc.next(); return(str); }
static String ns(){ String str = sc.nextLine(); return(str);}
static double nd(){double d = sc.nextDouble(); return(d); }
static int[] ai(int n){ int a[] = new int[n]; for(int i=0;i<n;i++) a[i] = ni(); return a; }
static long[] al(int n) {long a[] = new long[n]; for(int i=0;i<n;i++) a[i] = nl(); return a; }
static double[] ad(int n) { double a[]= new double[n]; for(int i=0;i<n;i++) a[i]=nd(); return a;}
static String[] as(int n){ String a[] = new String[n]; for(int i=0;i<n;i++) a[i] = n(); return a; }
static void p(Object o){ out.print(o); }
static void pn(Object o){ out.println(o); }
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\n#book\n#bigtown\n#big", "3\n#book\n#cool\n#cold", "4\n#car\n#cart\n#art\n#at", "3\n#apple\n#apple\n#fruit"] | 2 seconds | ["#b\n#big\n#big", "#book\n#co\n#cold", "#\n#\n#art\n#at", "#apple\n#apple\n#fruit"] | NoteWord a1,βa2,β...,βam of length m is lexicographically not greater than word b1,βb2,β...,βbk of length k, if one of two conditions hold: at first position i, such that aiββ βbi, the character ai goes earlier in the alphabet than character bi, i.e. a has smaller character than b in the first position where they differ; if there is no such position i and mββ€βk, i.e. the first word is a prefix of the second or two words are equal. The sequence of words is said to be sorted in lexicographical order if each word (except the last one) is lexicographically not greater than the next word.For the words consisting of lowercase English letters the lexicographical order coincides with the alphabet word order in the dictionary.According to the above definition, if a hashtag consisting of one character '#' it is lexicographically not greater than any other valid hashtag. That's why in the third sample we can't keep first two hashtags unchanged and shorten the other two. | Java 8 | standard input | [
"binary search",
"implementation",
"greedy",
"strings"
] | 27baf9b1241c0f8e3a2037b18f39fe34 | The first line of the input contains a single integer n (1ββ€βnββ€β500β000)Β β the number of hashtags being edited now. Each of the next n lines contains exactly one hashtag of positive length. It is guaranteed that the total length of all hashtags (i.e. the total length of the string except for characters '#') won't exceed 500β000. | 1,800 | Print the resulting hashtags in any of the optimal solutions. | standard output | |
PASSED | 52e7b1876f69f4daa0b09041fba7d80a | train_003.jsonl | 1487930700 | Vasya is an administrator of a public page of organization "Mouse and keyboard" and his everyday duty is to publish news from the world of competitive programming. For each news he also creates a list of hashtags to make searching for a particular topic more comfortable. For the purpose of this problem we define hashtag as a string consisting of lowercase English letters and exactly one symbol '#' located at the beginning of the string. The length of the hashtag is defined as the number of symbols in it without the symbol '#'.The head administrator of the page told Vasya that hashtags should go in lexicographical order (take a look at the notes section for the definition).Vasya is lazy so he doesn't want to actually change the order of hashtags in already published news. Instead, he decided to delete some suffixes (consecutive characters at the end of the string) of some of the hashtags. He is allowed to delete any number of characters, even the whole string except for the symbol '#'. Vasya wants to pick such a way to delete suffixes that the total number of deleted symbols is minimum possible. If there are several optimal solutions, he is fine with any of them. | 256 megabytes |
import java.io.*;
import java.util.*;
public class SolveD {
public static Reader in;
public static PrintWriter out;
public static long mod = 1000000007;
public static long inf = 100000000000000000l;
public static long fac[],inv[];
public static int union[];
public static void solve(){
int n = in.nextInt();
String str[] = new String[n];
for(int i=0; i<n; i++)
str[i] = in.next();
String res[] = new String[n];
res[n-1] = str[n-1];
for(int i=n-2; i>=0; i--)
{
//System.out.println(str[i].length()+" "+res[i+1].length());
if((str[i].length() >= res[i+1].length()) && (str[i]).substring(0, res[i+1].length()).equals(res[i+1]))
{
res[i] = res[i+1];
}
else
{
int k =0;
boolean flag = true;
while(k<Math.min(str[i].length(), res[i+1].length()))
{
if(str[i].charAt(k) == res[i+1].charAt(k))
k++;
else if(str[i].charAt(k) < res[i+1].charAt(k))
break;
else
{
flag = false;
break;
}
}
if(flag)
res[i] = str[i];
else
{
res[i] = str[i].substring(0,k);
}
}
}
for(int i=0; i<n; i++)
out.println(res[i]);
}
/**
* ############################### Template ################################
*/
public static class Pair implements Comparable{
int x,y;
Pair(int x, int y)
{
this.x = x;
this.y = y;
}
@Override
public int compareTo(Object o)
{
Pair pp = (Pair)o;
if(pp.x == x)
return 0;
else if (x>pp.x)
return 1;
else
return -1;
}
}
public static void init()
{
for(int i=0; i<union.length; i++)
union[i] = i;
}
public static int find(int n)
{
return (union[n]==n)?n:(union[n]=find(union[n]));
}
public static void unionSet(int i ,int j)
{
union[find(i)]=find(j);
}
public static boolean connected(int i,int j)
{
return union[i]==union[j];
}
public static long gcd(long a, long b) {
long x = Math.min(a,b);
long y = Math.max(a,b);
while(x!=0)
{
long temp = x;
x = y%x;
y = temp;
}
return y;
}
public static long modPow(long base, long exp, long mod) {
base = base % mod;
long result =1;
while(exp > 0)
{
if(exp % 2== 1)
{
result = (result * base) % mod;
exp --;
}
else
{
base = (base * base) % mod;
exp = exp >> 1;
}
}
return result;
}
public static void cal()
{
fac = new long[1000005];
inv = new long[1000005];
fac[0]=1;
inv[0]=1;
for(int i=1; i<=1000000; i++)
{
fac[i]=(fac[i-1]*i)%mod;
inv[i]=(inv[i-1]*modPow(i,mod-2,mod))%mod;
}
}
public static long ncr(int n, int r)
{
return (((fac[n]*inv[r])%mod)*inv[n-r])%mod;
}
SolveD() throws IOException {
in = new Reader(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
solve();
out.flush();
out.close();
}
public static void main(String args[]) {
new Thread(null, new Runnable() {
public void run() {
try {
new SolveD();
} catch (Exception e) {
e.printStackTrace();
}
}
}, "1", 1 << 26).start();
}
public static class Reader {
public BufferedReader reader;
public StringTokenizer st;
public Reader(InputStreamReader stream) {
reader = new BufferedReader(stream);
st = null;
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public String nextLine() throws IOException{
return reader.readLine();
}
public long nextLong(){
return Long.parseLong(next());
}
public double nextDouble(){
return Double.parseDouble(next());
}
}
} | Java | ["3\n#book\n#bigtown\n#big", "3\n#book\n#cool\n#cold", "4\n#car\n#cart\n#art\n#at", "3\n#apple\n#apple\n#fruit"] | 2 seconds | ["#b\n#big\n#big", "#book\n#co\n#cold", "#\n#\n#art\n#at", "#apple\n#apple\n#fruit"] | NoteWord a1,βa2,β...,βam of length m is lexicographically not greater than word b1,βb2,β...,βbk of length k, if one of two conditions hold: at first position i, such that aiββ βbi, the character ai goes earlier in the alphabet than character bi, i.e. a has smaller character than b in the first position where they differ; if there is no such position i and mββ€βk, i.e. the first word is a prefix of the second or two words are equal. The sequence of words is said to be sorted in lexicographical order if each word (except the last one) is lexicographically not greater than the next word.For the words consisting of lowercase English letters the lexicographical order coincides with the alphabet word order in the dictionary.According to the above definition, if a hashtag consisting of one character '#' it is lexicographically not greater than any other valid hashtag. That's why in the third sample we can't keep first two hashtags unchanged and shorten the other two. | Java 8 | standard input | [
"binary search",
"implementation",
"greedy",
"strings"
] | 27baf9b1241c0f8e3a2037b18f39fe34 | The first line of the input contains a single integer n (1ββ€βnββ€β500β000)Β β the number of hashtags being edited now. Each of the next n lines contains exactly one hashtag of positive length. It is guaranteed that the total length of all hashtags (i.e. the total length of the string except for characters '#') won't exceed 500β000. | 1,800 | Print the resulting hashtags in any of the optimal solutions. | standard output | |
PASSED | 96ca6ad8f79fea21cafb8342cfe27383 | train_003.jsonl | 1487930700 | Vasya is an administrator of a public page of organization "Mouse and keyboard" and his everyday duty is to publish news from the world of competitive programming. For each news he also creates a list of hashtags to make searching for a particular topic more comfortable. For the purpose of this problem we define hashtag as a string consisting of lowercase English letters and exactly one symbol '#' located at the beginning of the string. The length of the hashtag is defined as the number of symbols in it without the symbol '#'.The head administrator of the page told Vasya that hashtags should go in lexicographical order (take a look at the notes section for the definition).Vasya is lazy so he doesn't want to actually change the order of hashtags in already published news. Instead, he decided to delete some suffixes (consecutive characters at the end of the string) of some of the hashtags. He is allowed to delete any number of characters, even the whole string except for the symbol '#'. Vasya wants to pick such a way to delete suffixes that the total number of deleted symbols is minimum possible. If there are several optimal solutions, he is fine with any of them. | 256 megabytes | import java.io.*;
import java.util.*;
public class CFB {
BufferedReader br;
PrintWriter out;
StringTokenizer st;
boolean eof;
private static final long MOD = 1000L * 1000L * 1000L + 7;
private static final int[] dx = {0, -1, 0, 1};
private static final int[] dy = {1, 0, -1, 0};
private static final String yes = "Yes";
private static final String no = "No";
void solve() throws IOException {
int n = nextInt();
String[] arr = new String[n];
for (int i = 0; i < n; i++) {
arr[i] = nextString();
}
String[] res = new String[n];
res[n - 1] = arr[n - 1];
for (int i = n - 2; i >= 0; i--) {
String pre = res[i + 1];
String cur = helper(arr[i], pre);
res[i] = cur;
}
for (int i = 0; i < n; i++) {
outln(res[i]);
}
}
String helper(String s1, String s2) {
if (s1.compareTo(s2) <= 0) {
return new String(s1);
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s1.length(); i++) {
if (i >= s2.length() || s1.charAt(i) > s2.charAt(i)) {
return sb.toString();
}
sb.append(s1.charAt(i));
}
return null;
}
void shuffle(long[] a) {
int n = a.length;
for(int i = 0; i < n; i++) {
int r = i + (int) (Math.random() * (n - i));
long tmp = a[i];
a[i] = a[r];
a[r] = tmp;
}
}
private void outln(Object o) {
out.println(o);
}
private void out(Object o) {
out.print(o);
}
private void formatPrint(double val) {
System.out.format("%.9f%n", val);
}
public CFB() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
}
public static void main(String[] args) throws IOException {
new CFB();
}
public long[] nextLongArr(int n) throws IOException{
long[] res = new long[n];
for(int i = 0; i < n; i++)
res[i] = nextLong();
return res;
}
public int[] nextIntArr(int n) throws IOException {
int[] res = new int[n];
for(int i = 0; i < n; i++)
res[i] = nextInt();
return res;
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
eof = true;
return null;
}
}
return st.nextToken();
}
public String nextString() {
try {
return br.readLine();
} catch (IOException e) {
eof = true;
return null;
}
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
}
| Java | ["3\n#book\n#bigtown\n#big", "3\n#book\n#cool\n#cold", "4\n#car\n#cart\n#art\n#at", "3\n#apple\n#apple\n#fruit"] | 2 seconds | ["#b\n#big\n#big", "#book\n#co\n#cold", "#\n#\n#art\n#at", "#apple\n#apple\n#fruit"] | NoteWord a1,βa2,β...,βam of length m is lexicographically not greater than word b1,βb2,β...,βbk of length k, if one of two conditions hold: at first position i, such that aiββ βbi, the character ai goes earlier in the alphabet than character bi, i.e. a has smaller character than b in the first position where they differ; if there is no such position i and mββ€βk, i.e. the first word is a prefix of the second or two words are equal. The sequence of words is said to be sorted in lexicographical order if each word (except the last one) is lexicographically not greater than the next word.For the words consisting of lowercase English letters the lexicographical order coincides with the alphabet word order in the dictionary.According to the above definition, if a hashtag consisting of one character '#' it is lexicographically not greater than any other valid hashtag. That's why in the third sample we can't keep first two hashtags unchanged and shorten the other two. | Java 8 | standard input | [
"binary search",
"implementation",
"greedy",
"strings"
] | 27baf9b1241c0f8e3a2037b18f39fe34 | The first line of the input contains a single integer n (1ββ€βnββ€β500β000)Β β the number of hashtags being edited now. Each of the next n lines contains exactly one hashtag of positive length. It is guaranteed that the total length of all hashtags (i.e. the total length of the string except for characters '#') won't exceed 500β000. | 1,800 | Print the resulting hashtags in any of the optimal solutions. | standard output | |
PASSED | 395efba2d7a3b86ad71cf3e0f1bcee48 | train_003.jsonl | 1487930700 | Vasya is an administrator of a public page of organization "Mouse and keyboard" and his everyday duty is to publish news from the world of competitive programming. For each news he also creates a list of hashtags to make searching for a particular topic more comfortable. For the purpose of this problem we define hashtag as a string consisting of lowercase English letters and exactly one symbol '#' located at the beginning of the string. The length of the hashtag is defined as the number of symbols in it without the symbol '#'.The head administrator of the page told Vasya that hashtags should go in lexicographical order (take a look at the notes section for the definition).Vasya is lazy so he doesn't want to actually change the order of hashtags in already published news. Instead, he decided to delete some suffixes (consecutive characters at the end of the string) of some of the hashtags. He is allowed to delete any number of characters, even the whole string except for the symbol '#'. Vasya wants to pick such a way to delete suffixes that the total number of deleted symbols is minimum possible. If there are several optimal solutions, he is fine with any of them. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Task777D {
public static void main(String[] args) throws IOException {
InputScanner is = new InputScanner();
int n = is.nextInt();
char[][] tags = new char[n][];
for (int i = 0; i < n; i++) tags[i] = is.next().toCharArray();
int[] size = new int[n];
size[n - 1] = tags[n - 1].length;
for (int i = n - 1; i > 0; i--) {
if (compareTo(tags[i], size[i], tags[i - 1]) < 0) {
size[i - 1] = greatestCommonPrefix(tags[i], size[i], tags[i - 1]);
} else size[i - 1] = tags[i - 1].length;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
for (int j = 0; j < size[i]; j++) {
sb.append(tags[i][j]);
}
sb.append("\n");
}
System.out.print(sb);
}
public static int greatestCommonPrefix(char[] a, int a_len, char[] b) {
int minLength = Math.min(a_len, b.length);
for (int i = 0; i < minLength; i++) {
if (a[i] != b[i]) return i;
}
return minLength;
}
public static int compareTo(char[] a, int a_len, char[] b) {
int minLength = Math.min(a_len, b.length);
for (int i = 0; i < minLength; i++) {
if (a[i] > b[i]) return 1;
else if (a[i] < b[i]) return -1;
}
return -1;
}
static class InputScanner {
BufferedReader br;
StringTokenizer st;
public InputScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public String next() throws IOException {
if (st == null || !st.hasMoreTokens()) {
String line = br.readLine();
st = new StringTokenizer(line);
}
return st.nextToken();
}
public int nextInt() throws IOException {
String next = next();
return Integer.parseInt(next);
}
public long nextLong() throws IOException {
String next = next();
return Long.parseLong(next);
}
}
}
| Java | ["3\n#book\n#bigtown\n#big", "3\n#book\n#cool\n#cold", "4\n#car\n#cart\n#art\n#at", "3\n#apple\n#apple\n#fruit"] | 2 seconds | ["#b\n#big\n#big", "#book\n#co\n#cold", "#\n#\n#art\n#at", "#apple\n#apple\n#fruit"] | NoteWord a1,βa2,β...,βam of length m is lexicographically not greater than word b1,βb2,β...,βbk of length k, if one of two conditions hold: at first position i, such that aiββ βbi, the character ai goes earlier in the alphabet than character bi, i.e. a has smaller character than b in the first position where they differ; if there is no such position i and mββ€βk, i.e. the first word is a prefix of the second or two words are equal. The sequence of words is said to be sorted in lexicographical order if each word (except the last one) is lexicographically not greater than the next word.For the words consisting of lowercase English letters the lexicographical order coincides with the alphabet word order in the dictionary.According to the above definition, if a hashtag consisting of one character '#' it is lexicographically not greater than any other valid hashtag. That's why in the third sample we can't keep first two hashtags unchanged and shorten the other two. | Java 8 | standard input | [
"binary search",
"implementation",
"greedy",
"strings"
] | 27baf9b1241c0f8e3a2037b18f39fe34 | The first line of the input contains a single integer n (1ββ€βnββ€β500β000)Β β the number of hashtags being edited now. Each of the next n lines contains exactly one hashtag of positive length. It is guaranteed that the total length of all hashtags (i.e. the total length of the string except for characters '#') won't exceed 500β000. | 1,800 | Print the resulting hashtags in any of the optimal solutions. | standard output | |
PASSED | 7bc7053f24a616a3cfc12b7233f9c068 | train_003.jsonl | 1487930700 | Vasya is an administrator of a public page of organization "Mouse and keyboard" and his everyday duty is to publish news from the world of competitive programming. For each news he also creates a list of hashtags to make searching for a particular topic more comfortable. For the purpose of this problem we define hashtag as a string consisting of lowercase English letters and exactly one symbol '#' located at the beginning of the string. The length of the hashtag is defined as the number of symbols in it without the symbol '#'.The head administrator of the page told Vasya that hashtags should go in lexicographical order (take a look at the notes section for the definition).Vasya is lazy so he doesn't want to actually change the order of hashtags in already published news. Instead, he decided to delete some suffixes (consecutive characters at the end of the string) of some of the hashtags. He is allowed to delete any number of characters, even the whole string except for the symbol '#'. Vasya wants to pick such a way to delete suffixes that the total number of deleted symbols is minimum possible. If there are several optimal solutions, he is fine with any of them. | 256 megabytes | import java.io.*;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
String[] strings = new String[n];
for (int i = 0; i < n; i++) {
strings[i] = in.next();
}
for (int i = n-1; i >= 1; i--) {
int len = 0;
if(strings[i].length() > strings[i-1].length()) {
len = strings[i-1].length();
} else {
len = strings[i].length();
}
String biggerString = strings[i];
String smallString = strings[i-1];
boolean isShortened = false;
for (int j = 1; j < len; j++) {
if(biggerString.charAt(j) < smallString.charAt(j)) {
strings[i-1] = strings[i-1].substring(0,j);
isShortened = true;
break;
} else if(biggerString.charAt(j) > smallString.charAt(j)){
break;
}
}
if(!isShortened && strings[i-1].length() > strings[i].length()
&& strings[i].equals(strings[i-1].substring(0,strings[i].length()))) {
strings[i-1] = strings[i-1].substring(0, strings[i].length());
}
}
for (int i = 0; i < n; i++) {
out.println(strings[i]);
}
out.close();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
} | Java | ["3\n#book\n#bigtown\n#big", "3\n#book\n#cool\n#cold", "4\n#car\n#cart\n#art\n#at", "3\n#apple\n#apple\n#fruit"] | 2 seconds | ["#b\n#big\n#big", "#book\n#co\n#cold", "#\n#\n#art\n#at", "#apple\n#apple\n#fruit"] | NoteWord a1,βa2,β...,βam of length m is lexicographically not greater than word b1,βb2,β...,βbk of length k, if one of two conditions hold: at first position i, such that aiββ βbi, the character ai goes earlier in the alphabet than character bi, i.e. a has smaller character than b in the first position where they differ; if there is no such position i and mββ€βk, i.e. the first word is a prefix of the second or two words are equal. The sequence of words is said to be sorted in lexicographical order if each word (except the last one) is lexicographically not greater than the next word.For the words consisting of lowercase English letters the lexicographical order coincides with the alphabet word order in the dictionary.According to the above definition, if a hashtag consisting of one character '#' it is lexicographically not greater than any other valid hashtag. That's why in the third sample we can't keep first two hashtags unchanged and shorten the other two. | Java 8 | standard input | [
"binary search",
"implementation",
"greedy",
"strings"
] | 27baf9b1241c0f8e3a2037b18f39fe34 | The first line of the input contains a single integer n (1ββ€βnββ€β500β000)Β β the number of hashtags being edited now. Each of the next n lines contains exactly one hashtag of positive length. It is guaranteed that the total length of all hashtags (i.e. the total length of the string except for characters '#') won't exceed 500β000. | 1,800 | Print the resulting hashtags in any of the optimal solutions. | standard output | |
PASSED | bfdb54c1b4997934fa7ec7501b9c35bf | train_003.jsonl | 1487930700 | Vasya is an administrator of a public page of organization "Mouse and keyboard" and his everyday duty is to publish news from the world of competitive programming. For each news he also creates a list of hashtags to make searching for a particular topic more comfortable. For the purpose of this problem we define hashtag as a string consisting of lowercase English letters and exactly one symbol '#' located at the beginning of the string. The length of the hashtag is defined as the number of symbols in it without the symbol '#'.The head administrator of the page told Vasya that hashtags should go in lexicographical order (take a look at the notes section for the definition).Vasya is lazy so he doesn't want to actually change the order of hashtags in already published news. Instead, he decided to delete some suffixes (consecutive characters at the end of the string) of some of the hashtags. He is allowed to delete any number of characters, even the whole string except for the symbol '#'. Vasya wants to pick such a way to delete suffixes that the total number of deleted symbols is minimum possible. If there are several optimal solutions, he is fine with any of them. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
/**
* 777D
* <p>
* A greedy solution.
* ΞΈ(Ξ£(|s_i|)) time
* ΞΈ(Ξ£(|s_i|)) space
*
* @author artyom
*/
public class _777D implements Runnable {
private BufferedReader in;
private Object solve() throws IOException {
int n = nextInt();
List<CharSequence> ls = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
ls.add(nextToken());
}
for (int i = n - 1; i > 0; i--) {
StringBuilder sb = new StringBuilder("#");
CharSequence prev = ls.get(i - 1), next = ls.get(i);
for (int j = 1, m = Math.min(next.length(), prev.length()); j < m; j++) {
if (prev.charAt(j) < next.charAt(j)) {
sb.append(prev.subSequence(j, prev.length()));
break;
}
if (prev.charAt(j) > next.charAt(j)) {
break;
}
sb.append(prev.charAt(j));
}
ls.set(i - 1, sb);
}
return String.join("\n", ls);
}
//--------------------------------------------------------------
public static void main(String[] args) {
new _777D().run();
}
@Override
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
System.out.print(solve());
in.close();
} catch (IOException e) {
System.exit(0);
}
}
private String nextToken() throws IOException {
return in.readLine();
}
private int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
} | Java | ["3\n#book\n#bigtown\n#big", "3\n#book\n#cool\n#cold", "4\n#car\n#cart\n#art\n#at", "3\n#apple\n#apple\n#fruit"] | 2 seconds | ["#b\n#big\n#big", "#book\n#co\n#cold", "#\n#\n#art\n#at", "#apple\n#apple\n#fruit"] | NoteWord a1,βa2,β...,βam of length m is lexicographically not greater than word b1,βb2,β...,βbk of length k, if one of two conditions hold: at first position i, such that aiββ βbi, the character ai goes earlier in the alphabet than character bi, i.e. a has smaller character than b in the first position where they differ; if there is no such position i and mββ€βk, i.e. the first word is a prefix of the second or two words are equal. The sequence of words is said to be sorted in lexicographical order if each word (except the last one) is lexicographically not greater than the next word.For the words consisting of lowercase English letters the lexicographical order coincides with the alphabet word order in the dictionary.According to the above definition, if a hashtag consisting of one character '#' it is lexicographically not greater than any other valid hashtag. That's why in the third sample we can't keep first two hashtags unchanged and shorten the other two. | Java 8 | standard input | [
"binary search",
"implementation",
"greedy",
"strings"
] | 27baf9b1241c0f8e3a2037b18f39fe34 | The first line of the input contains a single integer n (1ββ€βnββ€β500β000)Β β the number of hashtags being edited now. Each of the next n lines contains exactly one hashtag of positive length. It is guaranteed that the total length of all hashtags (i.e. the total length of the string except for characters '#') won't exceed 500β000. | 1,800 | Print the resulting hashtags in any of the optimal solutions. | standard output | |
PASSED | 1f1b0ae072a9216d9a94dfc3e948c406 | train_003.jsonl | 1487930700 | Vasya is an administrator of a public page of organization "Mouse and keyboard" and his everyday duty is to publish news from the world of competitive programming. For each news he also creates a list of hashtags to make searching for a particular topic more comfortable. For the purpose of this problem we define hashtag as a string consisting of lowercase English letters and exactly one symbol '#' located at the beginning of the string. The length of the hashtag is defined as the number of symbols in it without the symbol '#'.The head administrator of the page told Vasya that hashtags should go in lexicographical order (take a look at the notes section for the definition).Vasya is lazy so he doesn't want to actually change the order of hashtags in already published news. Instead, he decided to delete some suffixes (consecutive characters at the end of the string) of some of the hashtags. He is allowed to delete any number of characters, even the whole string except for the symbol '#'. Vasya wants to pick such a way to delete suffixes that the total number of deleted symbols is minimum possible. If there are several optimal solutions, he is fine with any of them. | 256 megabytes | import java.util.*;
import java.io.*;
public class cf
{
static String arr[];
static int n;
public static void main(String[] args)throws IOException
{
PrintWriter out= new PrintWriter(System.out);
Scanner sc = new Scanner(System.in);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
n=Integer.parseInt(br.readLine());
arr=new String[n];
for(int i = 0 ;i<n;i++)
{
arr[i]=br.readLine();
}
for(int i=n-2;i>=0;i--)
{
int j=0;
int flag=0;
for(j=0;j<Math.min(arr[i].length(),arr[i+1].length());j++)
{
if(arr[i].charAt(j)<arr[i+1].charAt(j))
{
flag=1;
break;
}
else if(arr[i].charAt(j)>arr[i+1].charAt(j))
{
break;
}
}
if(flag==0)
{
arr[i]=arr[i].substring(0,j);
}
}
for(int i = 0 ;i<n;i++)
out.println(arr[i]);
out.close();
}
}
| Java | ["3\n#book\n#bigtown\n#big", "3\n#book\n#cool\n#cold", "4\n#car\n#cart\n#art\n#at", "3\n#apple\n#apple\n#fruit"] | 2 seconds | ["#b\n#big\n#big", "#book\n#co\n#cold", "#\n#\n#art\n#at", "#apple\n#apple\n#fruit"] | NoteWord a1,βa2,β...,βam of length m is lexicographically not greater than word b1,βb2,β...,βbk of length k, if one of two conditions hold: at first position i, such that aiββ βbi, the character ai goes earlier in the alphabet than character bi, i.e. a has smaller character than b in the first position where they differ; if there is no such position i and mββ€βk, i.e. the first word is a prefix of the second or two words are equal. The sequence of words is said to be sorted in lexicographical order if each word (except the last one) is lexicographically not greater than the next word.For the words consisting of lowercase English letters the lexicographical order coincides with the alphabet word order in the dictionary.According to the above definition, if a hashtag consisting of one character '#' it is lexicographically not greater than any other valid hashtag. That's why in the third sample we can't keep first two hashtags unchanged and shorten the other two. | Java 8 | standard input | [
"binary search",
"implementation",
"greedy",
"strings"
] | 27baf9b1241c0f8e3a2037b18f39fe34 | The first line of the input contains a single integer n (1ββ€βnββ€β500β000)Β β the number of hashtags being edited now. Each of the next n lines contains exactly one hashtag of positive length. It is guaranteed that the total length of all hashtags (i.e. the total length of the string except for characters '#') won't exceed 500β000. | 1,800 | Print the resulting hashtags in any of the optimal solutions. | standard output | |
PASSED | 5805e3ee09a76f05325760f373447da0 | train_003.jsonl | 1487930700 | Vasya is an administrator of a public page of organization "Mouse and keyboard" and his everyday duty is to publish news from the world of competitive programming. For each news he also creates a list of hashtags to make searching for a particular topic more comfortable. For the purpose of this problem we define hashtag as a string consisting of lowercase English letters and exactly one symbol '#' located at the beginning of the string. The length of the hashtag is defined as the number of symbols in it without the symbol '#'.The head administrator of the page told Vasya that hashtags should go in lexicographical order (take a look at the notes section for the definition).Vasya is lazy so he doesn't want to actually change the order of hashtags in already published news. Instead, he decided to delete some suffixes (consecutive characters at the end of the string) of some of the hashtags. He is allowed to delete any number of characters, even the whole string except for the symbol '#'. Vasya wants to pick such a way to delete suffixes that the total number of deleted symbols is minimum possible. If there are several optimal solutions, he is fine with any of them. | 256 megabytes | import java.util.*;
public class Task777D {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
StringBuffer sb[] = new StringBuffer[n], ans = new StringBuffer();
for (int i = 0; i < n; i++) {
sb[i] = new StringBuffer(sc.next());
}
for (int i = n - 2; i >= 0; i--) {
if (sb[i].toString().compareTo(sb[i + 1].toString()) > 0) {
int j;
for (j = 1; j < sb[i].length() && j < sb[i + 1].length(); j++) {
if (sb[i].charAt(j) - sb[i + 1].charAt(j) > 0) {
break;
}
}
sb[i].delete(j, sb[i].length());
}
}
for (int i = 0; i < n; i++) {
ans.append(sb[i] + "\r\n");
}
System.out.print(ans);
}
} | Java | ["3\n#book\n#bigtown\n#big", "3\n#book\n#cool\n#cold", "4\n#car\n#cart\n#art\n#at", "3\n#apple\n#apple\n#fruit"] | 2 seconds | ["#b\n#big\n#big", "#book\n#co\n#cold", "#\n#\n#art\n#at", "#apple\n#apple\n#fruit"] | NoteWord a1,βa2,β...,βam of length m is lexicographically not greater than word b1,βb2,β...,βbk of length k, if one of two conditions hold: at first position i, such that aiββ βbi, the character ai goes earlier in the alphabet than character bi, i.e. a has smaller character than b in the first position where they differ; if there is no such position i and mββ€βk, i.e. the first word is a prefix of the second or two words are equal. The sequence of words is said to be sorted in lexicographical order if each word (except the last one) is lexicographically not greater than the next word.For the words consisting of lowercase English letters the lexicographical order coincides with the alphabet word order in the dictionary.According to the above definition, if a hashtag consisting of one character '#' it is lexicographically not greater than any other valid hashtag. That's why in the third sample we can't keep first two hashtags unchanged and shorten the other two. | Java 8 | standard input | [
"binary search",
"implementation",
"greedy",
"strings"
] | 27baf9b1241c0f8e3a2037b18f39fe34 | The first line of the input contains a single integer n (1ββ€βnββ€β500β000)Β β the number of hashtags being edited now. Each of the next n lines contains exactly one hashtag of positive length. It is guaranteed that the total length of all hashtags (i.e. the total length of the string except for characters '#') won't exceed 500β000. | 1,800 | Print the resulting hashtags in any of the optimal solutions. | standard output | |
PASSED | a68e36ef9e37ac550744248f38c1d4dd | train_003.jsonl | 1487930700 | Vasya is an administrator of a public page of organization "Mouse and keyboard" and his everyday duty is to publish news from the world of competitive programming. For each news he also creates a list of hashtags to make searching for a particular topic more comfortable. For the purpose of this problem we define hashtag as a string consisting of lowercase English letters and exactly one symbol '#' located at the beginning of the string. The length of the hashtag is defined as the number of symbols in it without the symbol '#'.The head administrator of the page told Vasya that hashtags should go in lexicographical order (take a look at the notes section for the definition).Vasya is lazy so he doesn't want to actually change the order of hashtags in already published news. Instead, he decided to delete some suffixes (consecutive characters at the end of the string) of some of the hashtags. He is allowed to delete any number of characters, even the whole string except for the symbol '#'. Vasya wants to pick such a way to delete suffixes that the total number of deleted symbols is minimum possible. If there are several optimal solutions, he is fine with any of them. | 256 megabytes | import java.io.*;
import java.util.*;
public class D777
{
public static void main(String args[])throws IOException
{
Scanner sc=new Scanner(System.in);
PrintWriter pw=new PrintWriter(System.out);
int n=sc.nextInt();
String s[]=new String[n];
for(int i=0;i<n;i++)
{
s[i]=sc.next();
}
for(int i=n-2;i>=0;i--)
{
int min=Math.min(s[i].length(),s[i+1].length()),f=0;
for(int j=1;j<min;j++)
{
if(s[i].charAt(j)<s[i+1].charAt(j))
{
f=1;break;
}
else if(s[i].charAt(j)>s[i+1].charAt(j))
{
s[i]=s[i].substring(0,j);
f=1;break;
}
}
if(f==0 && s[i].length()>s[i+1].length())
{
s[i]=s[i].substring(0,min);
}
}
for(int i=0;i<n;i++)
{
pw.println(s[i]);
}
pw.flush();
}
} | Java | ["3\n#book\n#bigtown\n#big", "3\n#book\n#cool\n#cold", "4\n#car\n#cart\n#art\n#at", "3\n#apple\n#apple\n#fruit"] | 2 seconds | ["#b\n#big\n#big", "#book\n#co\n#cold", "#\n#\n#art\n#at", "#apple\n#apple\n#fruit"] | NoteWord a1,βa2,β...,βam of length m is lexicographically not greater than word b1,βb2,β...,βbk of length k, if one of two conditions hold: at first position i, such that aiββ βbi, the character ai goes earlier in the alphabet than character bi, i.e. a has smaller character than b in the first position where they differ; if there is no such position i and mββ€βk, i.e. the first word is a prefix of the second or two words are equal. The sequence of words is said to be sorted in lexicographical order if each word (except the last one) is lexicographically not greater than the next word.For the words consisting of lowercase English letters the lexicographical order coincides with the alphabet word order in the dictionary.According to the above definition, if a hashtag consisting of one character '#' it is lexicographically not greater than any other valid hashtag. That's why in the third sample we can't keep first two hashtags unchanged and shorten the other two. | Java 8 | standard input | [
"binary search",
"implementation",
"greedy",
"strings"
] | 27baf9b1241c0f8e3a2037b18f39fe34 | The first line of the input contains a single integer n (1ββ€βnββ€β500β000)Β β the number of hashtags being edited now. Each of the next n lines contains exactly one hashtag of positive length. It is guaranteed that the total length of all hashtags (i.e. the total length of the string except for characters '#') won't exceed 500β000. | 1,800 | Print the resulting hashtags in any of the optimal solutions. | standard output | |
PASSED | 29bca5e513f01db63a42ca6cd9256e92 | train_003.jsonl | 1487930700 | Vasya is an administrator of a public page of organization "Mouse and keyboard" and his everyday duty is to publish news from the world of competitive programming. For each news he also creates a list of hashtags to make searching for a particular topic more comfortable. For the purpose of this problem we define hashtag as a string consisting of lowercase English letters and exactly one symbol '#' located at the beginning of the string. The length of the hashtag is defined as the number of symbols in it without the symbol '#'.The head administrator of the page told Vasya that hashtags should go in lexicographical order (take a look at the notes section for the definition).Vasya is lazy so he doesn't want to actually change the order of hashtags in already published news. Instead, he decided to delete some suffixes (consecutive characters at the end of the string) of some of the hashtags. He is allowed to delete any number of characters, even the whole string except for the symbol '#'. Vasya wants to pick such a way to delete suffixes that the total number of deleted symbols is minimum possible. If there are several optimal solutions, he is fine with any of them. | 256 megabytes | import java.util.*;
public class D {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int n= sc.nextInt();
StringBuffer sb[] = new StringBuffer[n],ans = new StringBuffer();
for(int i=0 ; i<n ;i++){
sb[i] = new StringBuffer(sc.next());
}
for(int i=n-2; i>=0 ;i--){
if(sb[i].toString().compareTo(sb[i+1].toString())>0){
int j;
for(j=1 ;j<sb[i].length() && j<sb[i+1].length();j++){
if(sb[i].charAt(j)-sb[i+1].charAt(j)>0){
break;
}
}
sb[i].delete(j, sb[i].length());
}
}
for(int i=0 ; i<n ;i++){
ans.append(sb[i]+"\r\n");
}
System.out.print(ans);
}
}
| Java | ["3\n#book\n#bigtown\n#big", "3\n#book\n#cool\n#cold", "4\n#car\n#cart\n#art\n#at", "3\n#apple\n#apple\n#fruit"] | 2 seconds | ["#b\n#big\n#big", "#book\n#co\n#cold", "#\n#\n#art\n#at", "#apple\n#apple\n#fruit"] | NoteWord a1,βa2,β...,βam of length m is lexicographically not greater than word b1,βb2,β...,βbk of length k, if one of two conditions hold: at first position i, such that aiββ βbi, the character ai goes earlier in the alphabet than character bi, i.e. a has smaller character than b in the first position where they differ; if there is no such position i and mββ€βk, i.e. the first word is a prefix of the second or two words are equal. The sequence of words is said to be sorted in lexicographical order if each word (except the last one) is lexicographically not greater than the next word.For the words consisting of lowercase English letters the lexicographical order coincides with the alphabet word order in the dictionary.According to the above definition, if a hashtag consisting of one character '#' it is lexicographically not greater than any other valid hashtag. That's why in the third sample we can't keep first two hashtags unchanged and shorten the other two. | Java 8 | standard input | [
"binary search",
"implementation",
"greedy",
"strings"
] | 27baf9b1241c0f8e3a2037b18f39fe34 | The first line of the input contains a single integer n (1ββ€βnββ€β500β000)Β β the number of hashtags being edited now. Each of the next n lines contains exactly one hashtag of positive length. It is guaranteed that the total length of all hashtags (i.e. the total length of the string except for characters '#') won't exceed 500β000. | 1,800 | Print the resulting hashtags in any of the optimal solutions. | standard output | |
PASSED | dae2dc6cf6320c614cbf59a412dc10c5 | train_003.jsonl | 1487930700 | Vasya is an administrator of a public page of organization "Mouse and keyboard" and his everyday duty is to publish news from the world of competitive programming. For each news he also creates a list of hashtags to make searching for a particular topic more comfortable. For the purpose of this problem we define hashtag as a string consisting of lowercase English letters and exactly one symbol '#' located at the beginning of the string. The length of the hashtag is defined as the number of symbols in it without the symbol '#'.The head administrator of the page told Vasya that hashtags should go in lexicographical order (take a look at the notes section for the definition).Vasya is lazy so he doesn't want to actually change the order of hashtags in already published news. Instead, he decided to delete some suffixes (consecutive characters at the end of the string) of some of the hashtags. He is allowed to delete any number of characters, even the whole string except for the symbol '#'. Vasya wants to pick such a way to delete suffixes that the total number of deleted symbols is minimum possible. If there are several optimal solutions, he is fine with any of them. | 256 megabytes | import java.util.Scanner;
import java.io.*;
import java.util.*;
import java.math.*;
import java.lang.*;
import static java.lang.Math.*;
public class TestClass implements Runnable
{
public static void main(String args[])
{
new Thread(null, new TestClass(),"TESTCLASS",1<<26).start();
}
public void run()
{
//Scanner scan=new Scanner(System.in);
InputReader hb=new InputReader(System.in);
PrintWriter w=new PrintWriter(System.out);
int n=hb.nextInt();
String s[]=new String[n];
for(int i=0;i<n;i++)
s[i]=hb.next();
for(int i=n-2;i>=0;i--)
{
if(s[i+1].compareTo(s[i]) < 0)
{
int index=Math.min(s[i].length(),s[i+1].length());
for(int j=1;j<s[i].length() && j<s[i+1].length();j++)
{
if(s[i+1].charAt(j)<s[i].charAt(j))
{
index=j;
break;
}
}
s[i]=s[i].substring(0,index);
}
}
for(int i=0;i<n;i++)
w.println(s[i]);
//w.println(s1.compareTo(s2));
w.close();
}
private void shuffle(char[] arr)
{
Random ran = new Random();
for (int i = 0; i < arr.length; i++) {
int i1 = ran.nextInt(arr.length);
int i2 = ran.nextInt(arr.length);
char temp = arr[i1];
arr[i1] = arr[i2];
arr[i2] = temp;
}
}
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 String nextLine()
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
public int nextInt()
{
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.')
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.')
{
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next()
{
return readString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
static class Pair implements Comparable<Pair>
{
int a;
int b;
String str;
public Pair(int a,int b)
{
this.a=a;
this.b=b;
str=min(a,b)+" "+max(a,b);
}
public int compareTo(Pair pair)
{
if(Integer.compare(a,pair.a)==0)
return Integer.compare(b,pair.b);
return Integer.compare(a,pair.a);
}
}
} | Java | ["3\n#book\n#bigtown\n#big", "3\n#book\n#cool\n#cold", "4\n#car\n#cart\n#art\n#at", "3\n#apple\n#apple\n#fruit"] | 2 seconds | ["#b\n#big\n#big", "#book\n#co\n#cold", "#\n#\n#art\n#at", "#apple\n#apple\n#fruit"] | NoteWord a1,βa2,β...,βam of length m is lexicographically not greater than word b1,βb2,β...,βbk of length k, if one of two conditions hold: at first position i, such that aiββ βbi, the character ai goes earlier in the alphabet than character bi, i.e. a has smaller character than b in the first position where they differ; if there is no such position i and mββ€βk, i.e. the first word is a prefix of the second or two words are equal. The sequence of words is said to be sorted in lexicographical order if each word (except the last one) is lexicographically not greater than the next word.For the words consisting of lowercase English letters the lexicographical order coincides with the alphabet word order in the dictionary.According to the above definition, if a hashtag consisting of one character '#' it is lexicographically not greater than any other valid hashtag. That's why in the third sample we can't keep first two hashtags unchanged and shorten the other two. | Java 8 | standard input | [
"binary search",
"implementation",
"greedy",
"strings"
] | 27baf9b1241c0f8e3a2037b18f39fe34 | The first line of the input contains a single integer n (1ββ€βnββ€β500β000)Β β the number of hashtags being edited now. Each of the next n lines contains exactly one hashtag of positive length. It is guaranteed that the total length of all hashtags (i.e. the total length of the string except for characters '#') won't exceed 500β000. | 1,800 | Print the resulting hashtags in any of the optimal solutions. | standard output | |
PASSED | 1b6f09a4b1b19f3194e1a29bd849ec61 | train_003.jsonl | 1487930700 | Vasya is an administrator of a public page of organization "Mouse and keyboard" and his everyday duty is to publish news from the world of competitive programming. For each news he also creates a list of hashtags to make searching for a particular topic more comfortable. For the purpose of this problem we define hashtag as a string consisting of lowercase English letters and exactly one symbol '#' located at the beginning of the string. The length of the hashtag is defined as the number of symbols in it without the symbol '#'.The head administrator of the page told Vasya that hashtags should go in lexicographical order (take a look at the notes section for the definition).Vasya is lazy so he doesn't want to actually change the order of hashtags in already published news. Instead, he decided to delete some suffixes (consecutive characters at the end of the string) of some of the hashtags. He is allowed to delete any number of characters, even the whole string except for the symbol '#'. Vasya wants to pick such a way to delete suffixes that the total number of deleted symbols is minimum possible. If there are several optimal solutions, he is fine with any of them. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main
{
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw=new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
StringTokenizer s=new StringTokenizer(br.readLine());
int n=Integer.parseInt(s.nextToken());
String ar[]=new String[n];
for(int i=0;i<n;i++) {
s=new StringTokenizer(br.readLine());
String sb=s.nextToken();
ar[i]=sb.substring(1);
}
if(n==1) {
pw.print("#"+ar[0]);
pw.close();
}
for(int i=n-2;i>=0;i--) {
if(ar[i+1].compareTo(ar[i])>=0)
continue;
else {
ar[i]=bfs(ar,i);
}
}
for(int i=0;i<ar.length;i++) {
pw.println("#"+ar[i]);
}
pw.close();
}
private static String bfs(String[] ar, int i) {
// TODO Auto-generated method stub
String ans="";
int lo=0;
int hi=ar[i].length()-1;
while(lo<hi) {
int mid=(lo+hi)/2;
String tmp=ar[i].substring(0, mid+1);
int val=ar[i+1].compareTo(tmp);
if(val==0)
return tmp;
else if(val>0) {
ans=tmp;
lo=mid+1;
}else {
hi=mid;
}
}
return ans;
}
}
| Java | ["3\n#book\n#bigtown\n#big", "3\n#book\n#cool\n#cold", "4\n#car\n#cart\n#art\n#at", "3\n#apple\n#apple\n#fruit"] | 2 seconds | ["#b\n#big\n#big", "#book\n#co\n#cold", "#\n#\n#art\n#at", "#apple\n#apple\n#fruit"] | NoteWord a1,βa2,β...,βam of length m is lexicographically not greater than word b1,βb2,β...,βbk of length k, if one of two conditions hold: at first position i, such that aiββ βbi, the character ai goes earlier in the alphabet than character bi, i.e. a has smaller character than b in the first position where they differ; if there is no such position i and mββ€βk, i.e. the first word is a prefix of the second or two words are equal. The sequence of words is said to be sorted in lexicographical order if each word (except the last one) is lexicographically not greater than the next word.For the words consisting of lowercase English letters the lexicographical order coincides with the alphabet word order in the dictionary.According to the above definition, if a hashtag consisting of one character '#' it is lexicographically not greater than any other valid hashtag. That's why in the third sample we can't keep first two hashtags unchanged and shorten the other two. | Java 8 | standard input | [
"binary search",
"implementation",
"greedy",
"strings"
] | 27baf9b1241c0f8e3a2037b18f39fe34 | The first line of the input contains a single integer n (1ββ€βnββ€β500β000)Β β the number of hashtags being edited now. Each of the next n lines contains exactly one hashtag of positive length. It is guaranteed that the total length of all hashtags (i.e. the total length of the string except for characters '#') won't exceed 500β000. | 1,800 | Print the resulting hashtags in any of the optimal solutions. | standard output | |
PASSED | 7bbf6b8efa8c917225a183ff80ce27ed | train_003.jsonl | 1487930700 | Vasya is an administrator of a public page of organization "Mouse and keyboard" and his everyday duty is to publish news from the world of competitive programming. For each news he also creates a list of hashtags to make searching for a particular topic more comfortable. For the purpose of this problem we define hashtag as a string consisting of lowercase English letters and exactly one symbol '#' located at the beginning of the string. The length of the hashtag is defined as the number of symbols in it without the symbol '#'.The head administrator of the page told Vasya that hashtags should go in lexicographical order (take a look at the notes section for the definition).Vasya is lazy so he doesn't want to actually change the order of hashtags in already published news. Instead, he decided to delete some suffixes (consecutive characters at the end of the string) of some of the hashtags. He is allowed to delete any number of characters, even the whole string except for the symbol '#'. Vasya wants to pick such a way to delete suffixes that the total number of deleted symbols is minimum possible. If there are several optimal solutions, he is fine with any of them. | 256 megabytes |
import java.util.Scanner;
public class CloudOfHashtags {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String[] s = new String[n];
for(int i = 0; i < n; i++)
{
s[i] = sc.next();
}
for(int i = n-2; i >= 0; i--)
{ //compare with next
if(s[i].compareTo(s[i+1]) > 0)
{ //fixit
//how many do we need to delete?
for(int c = 0; c < s[i].length(); c++)
{
int c0 = s[i].charAt(c);
int c1 = s[i+1].length() > c? s[i+1].charAt(c) : -1 ;
if(c0 > c1)
{ //dis be illegal
// int gudlength = c;
s[i] = s[i].substring(0,c);
break;
}
}
}
}
StringBuilder sb = new StringBuilder();
for(int i = 0; i < n; i++)
{
sb.append(s[i]);
if(i<n-1)sb.append("\n");
// System.out.println(s[i]);
}
System.out.println(sb);
}
}
| Java | ["3\n#book\n#bigtown\n#big", "3\n#book\n#cool\n#cold", "4\n#car\n#cart\n#art\n#at", "3\n#apple\n#apple\n#fruit"] | 2 seconds | ["#b\n#big\n#big", "#book\n#co\n#cold", "#\n#\n#art\n#at", "#apple\n#apple\n#fruit"] | NoteWord a1,βa2,β...,βam of length m is lexicographically not greater than word b1,βb2,β...,βbk of length k, if one of two conditions hold: at first position i, such that aiββ βbi, the character ai goes earlier in the alphabet than character bi, i.e. a has smaller character than b in the first position where they differ; if there is no such position i and mββ€βk, i.e. the first word is a prefix of the second or two words are equal. The sequence of words is said to be sorted in lexicographical order if each word (except the last one) is lexicographically not greater than the next word.For the words consisting of lowercase English letters the lexicographical order coincides with the alphabet word order in the dictionary.According to the above definition, if a hashtag consisting of one character '#' it is lexicographically not greater than any other valid hashtag. That's why in the third sample we can't keep first two hashtags unchanged and shorten the other two. | Java 8 | standard input | [
"binary search",
"implementation",
"greedy",
"strings"
] | 27baf9b1241c0f8e3a2037b18f39fe34 | The first line of the input contains a single integer n (1ββ€βnββ€β500β000)Β β the number of hashtags being edited now. Each of the next n lines contains exactly one hashtag of positive length. It is guaranteed that the total length of all hashtags (i.e. the total length of the string except for characters '#') won't exceed 500β000. | 1,800 | Print the resulting hashtags in any of the optimal solutions. | standard output | |
PASSED | 460d1f65e168d012fd1a4b323bc65df9 | train_003.jsonl | 1596810900 | Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags! | 256 megabytes | import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.PriorityQueue;
import java.util.Scanner;
import java.util.Set;
import java.util.Stack;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
public class Main {
static FastReader sc= new FastReader();
static List<Integer> C;
static List<Long> B;
static int mod=(int)Math.pow(10, 9)+7;
public static void main(String[] args) {
int t=sc.nextInt();
while(t-->0) {
int n=sc.nextInt();
C=new ArrayList<Integer>();
HashMap<Integer,Long> map=new HashMap<>();
for(int i=0;i<n;i++) {
C.add(sc.nextInt());
if(!map.containsKey(C.get(i)))map.put(C.get(i),1l);
else map.put(C.get(i),map.get(C.get(i))+1);
}
long m=Collections.max(map.values());
int mf=0;
for(long i:map.values())if(i==m)mf++;
System.out.println((n-mf)/(m-1)-1);
}
}
static boolean isSubsetSum(int set[], int n, int sum)
{
// The value of subset[i][j] will be
// true if there is a subset of
// set[0..j-1] with sum equal to i
boolean subset[][] = new boolean[sum + 1][n + 1];
// If sum is 0, then answer is true
for (int i = 0; i <= n; i++)
subset[0][i] = true;
// If sum is not 0 and set is empty,
// then answer is false
for (int i = 1; i <= sum; i++)
subset[i][0] = false;
// Fill the subset table in botton
// up manner
for (int i = 1; i <= sum; i++) {
for (int j = 1; j <= n; j++) {
subset[i][j] = subset[i][j - 1];
if (i >= set[j - 1])
subset[i][j] = subset[i][j]
|| subset[i - set[j - 1]][j - 1];
}
}
return subset[sum][n];
}
static boolean search(ArrayList<Integer> a,int m,int h) {
PriorityQueue<Integer> p=new PriorityQueue<Integer>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
// TODO Auto-generated method stub
return o2-o1;
}
});
for(int i=0;i<m;i++) {
p.add(a.get(i));
}
int c=0;
//System.out.println(p);
while(!p.isEmpty()) {
//System.out.println(p);
h-=p.poll();
if(h<0)break;
c++;
// System.out.println(h+" "+p+" "+c+" "+m);
if(!p.isEmpty()) {
p.poll();
c++;}
}
// System.out.println(c!=m);
if(c!=m)return false;
return true;
}
// static int key=-1;
static boolean isPowerOfTwo(long n)
{
if (n == 0)
return false;
while (n != 1)
{
if (n % 2 != 0)
return false;
n = n / 2;
}
return true;
}
static boolean isPerfectSquare(double x)
{
// Find floating point value of
// square root of x.
double sr = Math.sqrt(x);
// If square root is an integer
return ((sr - Math.floor(sr)) == 0);
}
static int binarySearch(ArrayList<Long> arr, int l, int r, long x,int key)
{
if (r >= l) {
int mid = (r + l) / 2;
// if(mid>=arr.size())return -1;
// If the element is present at the
// middle itself
if (arr.get(mid) == x)
return mid+1;
// If element is smaller than mid, then
// it can only be present in left subarray
if (arr.get(mid) > x) {
return binarySearch(arr, l, mid - 1, x,key);
}
// Else the element can only be present
// in right subarray
key=mid+1;
return binarySearch(arr, mid + 1, r, x,key);
}
// We reach here when element is not present
// in array
return key;
}
static boolean isPrime(long n)
{
// Corner cases
if (n <= 1)
return false;
if (n <= 3)
return true;
// This is checked so that we can skip
// middle five numbers in below loop
if (n % 2 == 0 || n % 3 == 0)
return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
}
class Sol {
int value;int in;int i;
Sol(int value,int in,int i){
this.value=value;
this.in=in;
this.i=i;
}
}
class SegmentTree {
SegNode st[];
int n;
// long arr[];
public SegmentTree(int n) {
this.n=n;
//this.arr=arr;
st=new SegNode[4*n];
}
void init(long n) {
for(int i=0;i<4*n;i++) {
st[i]=new SegNode();
}
}
void set(int i,long v,int x,int lx,int rx) {
if(rx-lx==1) {
st[x].sum=v;
st[x].max=v;
return ;
}
int m=lx+(rx-lx)/2;
if(i<m) set(i,v,2*x+1,lx,m);
else set(i,v,2*x+2,m,rx);
st[x].sum=st[2*x+1].sum+st[2*x+2].sum;
long ma=Math.max(st[2*x+1].max,st[2*x+2].max);
st[x].max=Math.max(ma,st[x].sum);
}
void set (int i,long v) {
set(i,v,0,0,n);
}
long max=Integer.MIN_VALUE;
long sum(int l,int r,int x,int lx,int rx) {
if(lx>=r||l>=rx)return 0;
if(lx>=l||rx<=r)return st[x].sum;
int m=(rx+lx)/2;
long s1=sum(l,r,2*x+1,lx,m);
long s2=sum(l,r,2*x+2,m,rx);
return max= Math.max(Math.max(Math.max(s1,s2),s1+s2),max);
}
long sum(int l,int r) {
return sum(l,r,0,0,n);
}
}
class SegNode{
long max;long sum;
public SegNode() {
// TODO Auto-generated constructor stub
sum=0;
max=Integer.MIN_VALUE;
}
}
| Java | ["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"] | 2 seconds | ["3\n2\n0\n4"] | NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$). | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy",
"math"
] | 9d480b3979a7c9789fd8247120f31f03 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$. | 1,700 | For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag. | standard output | |
PASSED | 09874de9bfa8dcde2af006d29862899c | train_003.jsonl | 1596810900 | Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags! | 256 megabytes | import java.util.*;
import java.io.*;
import static java.lang.Math.*;
public class ACMIND
{
static FastReader scan;
static PrintWriter pw;
static long MOD = 1_000_000_007;
static long INF = 2_000_000_000_000_000_000L;
static long inf = 2_000_000_000;
public static void main(String[] args) {
new Thread(null,null,"BaZ",1<<27)
{
public void run()
{
try
{
solve();
}
catch(Exception e)
{
e.printStackTrace();
System.exit(1);
}
}
}.start();
}
static int n, arr[];
static void solve() throws IOException {
scan = new FastReader();
pw = new PrintWriter(System.out, true);
StringBuilder sb = new StringBuilder();
int t = ni();
while (t-->0) {
n = ni();
arr = new int[n];
for(int i=0;i<n;++i) {
arr[i] = ni();
}
int low = 0, high = n, mid, ans = 0;
while (low<=high) {
mid = (low+high)>>1;
if(check(mid)) {
ans = mid;
low = ++mid;
}
else {
high = --mid;
}
}
pl(ans);
}
pw.flush();
pw.close();
}
static boolean check(int x) {
int freq[] = new int[n+1];
for(int i=0;i<n;++i) {
++freq[arr[i]];
}
TreeSet<Pair> eligible = new TreeSet<>();
for(int i=1;i<=n;++i) {
if(freq[i]>0) {
eligible.add(new Pair(freq[i], i));
}
}
int res[] = new int[n];
for(int i=0;i<n;++i) {
if(eligible.size()==0) {
return false;
}
Pair p = eligible.pollLast();
res[i] = p.y;
freq[p.y]--;
if(i-x>=0 && freq[res[i-x]]>0) {
eligible.add(new Pair(freq[res[i-x]], res[i-x]));
}
}
return true;
}
static class Pair implements Comparable<Pair>
{
int x,y;
Pair(int x,int y)
{
this.x=x;
this.y=y;
}
public int compareTo(Pair other)
{
if(this.x!=other.x)
return this.x-other.x;
return this.y-other.y;
}
public String toString()
{
return "("+x+","+y+")";
}
}
static int ni() throws IOException
{
return scan.nextInt();
}
static long nl() throws IOException
{
return scan.nextLong();
}
static double nd() throws IOException
{
return scan.nextDouble();
}
static void pl()
{
pw.println();
}
static void p(Object o)
{
pw.print(o+" ");
}
static void pl(Object o)
{
pw.println(o);
}
static void psb(StringBuilder sb)
{
pw.print(sb);
}
static void pa(String arrayName, Object arr[])
{
pl(arrayName+" : ");
for(Object o : arr)
p(o);
pl();
}
static void pa(String arrayName, int arr[])
{
pl(arrayName+" : ");
for(int o : arr)
p(o);
pl();
}
static void pa(String arrayName, long arr[])
{
pl(arrayName+" : ");
for(long o : arr)
p(o);
pl();
}
static void pa(String arrayName, double arr[])
{
pl(arrayName+" : ");
for(double o : arr)
p(o);
pl();
}
static void pa(String arrayName, char arr[])
{
pl(arrayName+" : ");
for(char o : arr)
p(o);
pl();
}
static void pa(String listName, List list)
{
pl(listName+" : ");
for(Object o : list)
p(o);
pl();
}
static void pa(String arrayName, Object[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(Object o : arr[i])
p(o);
pl();
}
}
static void pa(String arrayName, int[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(int o : arr[i])
p(o);
pl();
}
}
static void pa(String arrayName, long[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(long o : arr[i])
p(o);
pl();
}
}
static void pa(String arrayName, char[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(char o : arr[i])
p(o);
pl();
}
}
static void pa(String arrayName, double[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(double o : arr[i])
p(o);
pl();
}
}
static class FastReader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public FastReader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public FastReader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
byte[] buf = new byte[1000000];
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = (c == '-');
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = (c == '-');
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ') c = read();
boolean neg = (c == '-');
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') while ((c = read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10);
if (neg) return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null) return;
din.close();
}
}
} | Java | ["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"] | 2 seconds | ["3\n2\n0\n4"] | NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$). | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy",
"math"
] | 9d480b3979a7c9789fd8247120f31f03 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$. | 1,700 | For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag. | standard output | |
PASSED | 2c4a309ac4862fd2c54346147bc070b6 | train_003.jsonl | 1596810900 | Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags! | 256 megabytes | import java.util.Scanner;
public class qwerty7
{
public static void qwer(int...q) {
int n = q.length;
int c[] = new int[n];
for(int d = 0; d<n; d++) {
c[q[d]-1]++;
}
int we = c[0];
int as = 1;
int ans =0;
int qw =0;
for(int g = 0; g<n; g++) {
if(n==1||n==2){
System.out.println("0");
return;
}
if(n>4){
if((n%2==0)&&(c[g]>n/2)){
System.out.println("0");
return;
}
if((n%2==0)&&(c[g]==n/2)){
System.out.println("1");
return;
}
}
if((n%2!=0)&&(c[g]>(n+1)/2)){
System.out.println("0");
return;
}
if((n%2!=0)&&(c[g]==(n+1)/2)){
System.out.println("1");
return;
}
if(c[g]>we) {
we = c[g];
}
}
for(int h = 0; h<n; h++) {
if(c[h] == we){
qw++;
}
}
ans = (qw-1) + (int)((n-qw*we)/(we-1));
// System.out.println(qw);
// System.out.println(we);
System.out.println(ans);
}
public static void main(String args[]) {
Scanner s2 = new Scanner(System.in);
int y = s2.nextInt();
int a[] = new int[y];
int b[][] = new int[y][];
for(int u = 0; u<y; u++) {
a[u] = s2.nextInt();
b[u] = new int[a[u]];
for(int e = 0; e<a[u]; e++) {
b[u][e] = s2.nextInt();
}
}
for(int f = 0; f<y; f++) {
qwer(b[f]);
}
}
}
| Java | ["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"] | 2 seconds | ["3\n2\n0\n4"] | NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$). | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy",
"math"
] | 9d480b3979a7c9789fd8247120f31f03 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$. | 1,700 | For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag. | standard output | |
PASSED | ff35a9393840422fa7b7cf1e6111d83b | train_003.jsonl | 1596810900 | Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags! | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
public class a
{
static final int mod = 1000000007;
public static void main (String[] args) throws java.lang.Exception
{
FastReader sc = new FastReader();
PrintWriter out = new PrintWriter(System.out);
int t = sc.nextInt();
while (t-->0) {
int n = sc.nextInt();
int arr[] = new int[n+1];
for ( int i = 0 ; i < n ; i++ )
arr[sc.nextInt()]++;
int maxfreq = 2 ;
int maxcount = 0 ;
for ( int i = 1 ; i <= n ; i++ ) {
if ( arr[i] == maxfreq ) {
maxcount++;
}
if ( arr[i] > maxfreq ) {
maxfreq = arr[i];
maxcount = 1;
}
}
if ( maxcount == 1 ) {
out.println((n-maxfreq)/(maxfreq-1));
}else {
out.println( (n-maxfreq-maxcount+1)/(maxfreq-1) );
}
}
out.flush();
}
}
class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
} | Java | ["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"] | 2 seconds | ["3\n2\n0\n4"] | NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$). | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy",
"math"
] | 9d480b3979a7c9789fd8247120f31f03 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$. | 1,700 | For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag. | standard output | |
PASSED | 23411a5b7d8c0e7805d03929879aefba | train_003.jsonl | 1596810900 | Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags! | 256 megabytes | import java.io.*;
import java.text.DecimalFormat;
import java.util.*;
public class B {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
int a[] = new int[n + 1];
for (int i = 0; i < n; i++) {
++a[sc.nextInt()];
}
Arrays.sort(a);
ArrayList<Integer> q = new ArrayList<>();
int x=n;
for (int j = n; j >= 0; j--) {
if (a[n] != a[j])
break;
x--;
}
System.out.println(x/(a[n]-1)-1);
}
}
///////////////////////////////////////////////////////////////////////////////////////////
static class pair implements Comparable<pair> {
int x, y;
pair(int s, int d) {
x = s;
y = d;
}
@Override
public int compareTo(pair p) {
return (x == p.x && y == p.y) ? 0 : 1;
}
@Override
public String toString() {
return x + " " + y;
}
}
static long mod(long ans, int mod) {
return (ans % mod + mod) % mod;
}
static long gcd(long a, long b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
static long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
public static int log(int n, int base) {
int ans = 0;
while (n + 1 > base) {
ans++;
n /= base;
}
return ans;
}
static long pow(long b, long e) {
long ans = 1;
while (e > 0) {
if ((e & 1) == 1)
ans = ((ans * 1l * b));
e >>= 1;
{
}
b = ((b * 1l * b));
}
return ans;
}
static int powmod(int b, long e, int mod) {
int ans = 1;
b %= mod;
while (e > 0) {
if ((e & 1) == 1)
ans = (int) ((ans * 1l * b) % mod);
e >>= 1;
b = (int) ((b * 1l * b) % mod);
}
return ans;
}
static int ceil(int a, int b) {
int ans = a / b;
return a % b == 0 ? ans : ans + 1;
}
static long ceil(long a, long b) {
long ans = a / b;
return a % b == 0 ? ans : ans + 1;
}
// Returns nCr % p
static int nCrModp(int n, int r, int p) {
if (r > n - r)
r = n - r;
// The array C is going to store last
// row of pascal triangle at the end.
// And last entry of last row is nCr
int C[] = new int[r + 1];
C[0] = 1; // Top row of Pascal Triangle
// One by constructs remaining rows of Pascal
// Triangle from top to bottom
for (int i = 1; i <= n; i++) {
// Fill entries of current row using previous
// row values
for (int j = Math.min(i, r); j > 0; j--)
// nCj = (n-1)Cj + (n-1)C(j-1);
C[j] = (C[j] + C[j - 1]) % p;
}
return C[r];
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public int[] intArr(int n) throws IOException {
int a[] = new int[n];
for (int i = 0; i < a.length; i++) {
a[i] = nextInt();
}
return a;
}
public long[] longArr(int n) throws IOException {
long a[] = new long[n];
for (int i = 0; i < a.length; i++) {
a[i] = nextLong();
}
return a;
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public boolean ready() throws IOException {
return br.ready();
}
}
public static void shuffle(int[] a) {
int n = a.length;
for (int i = 0; i < n; i++) {
int r = i + (int) (Math.random() * (n - i));
int tmp = a[i];
a[i] = a[r];
a[r] = tmp;
}
}
} | Java | ["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"] | 2 seconds | ["3\n2\n0\n4"] | NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$). | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy",
"math"
] | 9d480b3979a7c9789fd8247120f31f03 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$. | 1,700 | For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag. | standard output | |
PASSED | 3c32cb2406ffd14f9813fc68249d3b36 | train_003.jsonl | 1596810900 | Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags! | 256 megabytes | import java.io.*;
import java.util.*;
/* * */
public class _662C implements Runnable{
public static void main(String[] args) {
new Thread(null, new _662C(),"Main",1<<27).start();
}
@Override
public void run() {
FastReader fd = new FastReader(System.in);
PrintWriter out = new PrintWriter(System.out);
int t = fd.nextInt();
for(int te = 0; te < t; te++){
int n = fd.nextInt();
int index = n-1;
LinkedList<Integer> keep = new LinkedList<>();
int[] data = new int[n+1];
for (int i = 0; i< n; i++){
int key = fd.nextInt();
data[key]++;
}
Arrays.sort(data);
int max= data[n];
for(int temp = data[n];temp>0;temp--) keep.add(1);
for (;data[index] > 0;) {
Collections.sort(keep);
int count = data[index--];
if (count == max) {
int tempindex=0;
for(;count>0;count--,tempindex++) keep.set(tempindex,keep.get(tempindex)+1);
}
else {
int tempindex=1;
for(;count>0;count--,tempindex++) keep.set(tempindex,keep.get(tempindex)+1);
}
}
Collections.sort(keep);out.println(keep.size()<=1?0:(keep.get(1)-1));
}
out.close();
}
//Helper functions
static int[] getArray(int n,boolean isSorted, FastReader fd){
int[] data = new int[n];
for(int i = 0; i < data.length; i++){ data[i] = fd.nextInt(); }
if(isSorted) Arrays.sort(data);
return data;
}
static int gcd(int a, int b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
static int lcm(int a, int b) {
return (a*b)/gcd(a, b);
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public FastReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
}
catch (IOException e) {
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
public int nextInt() {
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"] | 2 seconds | ["3\n2\n0\n4"] | NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$). | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy",
"math"
] | 9d480b3979a7c9789fd8247120f31f03 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$. | 1,700 | For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag. | standard output | |
PASSED | 5b7edb66f6ebe7256292a5b002647c18 | train_003.jsonl | 1596810900 | Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags! | 256 megabytes | import java.io.*;
import java.util.*;
/* * */
public class _662C implements Runnable{
public static void main(String[] args) {
new Thread(null, new _662C(),"Main",1<<27).start();
}
@Override
public void run() {
FastReader fd = new FastReader(System.in);
PrintWriter out = new PrintWriter(System.out);
int t = fd.nextInt();
for(int te = 0; te < t; te++){
int n = fd.nextInt();
HashMap<Integer,Integer> keep = new HashMap<>();
int maxFreq = 0;
for (int i = 0; i< n; i++){
int key = fd.nextInt();
keep.put(key,keep.getOrDefault(key,0)+1);
maxFreq = Math.max(maxFreq,keep.get(key));
}
int totalMaxFreq = 0;
for(int val : keep.values())
if(val == maxFreq) totalMaxFreq++;
out.println((n-totalMaxFreq)/(maxFreq-1)-1);
}
out.close();
}
//Helper functions
static int[] getArray(int n,boolean isSorted, FastReader fd){
int[] data = new int[n];
for(int i = 0; i < data.length; i++){ data[i] = fd.nextInt(); }
if(isSorted) Arrays.sort(data);
return data;
}
static int gcd(int a, int b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
static int lcm(int a, int b) {
return (a*b)/gcd(a, b);
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public FastReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
}
catch (IOException e) {
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
public int nextInt() {
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"] | 2 seconds | ["3\n2\n0\n4"] | NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$). | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy",
"math"
] | 9d480b3979a7c9789fd8247120f31f03 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$. | 1,700 | For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag. | standard output | |
PASSED | 8b0d1c7b5b39d3fe4894a6630bff639a | train_003.jsonl | 1596810900 | Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags! | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int t = scan.nextInt(),n;
int a[] = new int[200005];
while( t-- != 0) {
n = scan.nextInt();
int num = 0, max1 = 0;
for (int i = 1, x; i <= n; i++) {
x = scan.nextInt();
a[x]++;
max1 = Math.max(max1, a[x]);
}
for (int i = 1; i <= n; i++) {
if (a[i] == max1) num++;
a[i] = 0;
}
int ans = (n - max1 * num) / (max1 - 1) + num - 1;
System.out.println(ans);
}
}
} | Java | ["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"] | 2 seconds | ["3\n2\n0\n4"] | NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$). | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy",
"math"
] | 9d480b3979a7c9789fd8247120f31f03 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$. | 1,700 | For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag. | standard output | |
PASSED | ac9fc9c8d3586d19e2afcc1efeca7384 | train_003.jsonl | 1596810900 | Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags! | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
int t = Integer.parseInt(br.readLine());
for (int i = 0; i < t; i++) {
int n = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
int[] a = new int[n];
for (int j = 0; j < a.length; j++) {
a[j]= Integer.parseInt(st.nextToken());
}
Arrays.sort(a);
ArrayList<Integer> runs = new ArrayList<Integer>();
int run=0;
for (int j = 0; j < a.length; j++) {
if(j>0 && a[j]!=a[j-1])
{
runs.add(run);run=0;
}
run++;
if(j==a.length-1)runs.add(run);
}
Collections.sort(runs, Collections.reverseOrder());
int ans=a.length-runs.get(0);
for (int j = 1; j < runs.size(); j++) {
if(runs.get(j)==runs.get(0))ans--;
}
pw.println(ans/(runs.get(0)-1));
}
pw.close();
}
}
| Java | ["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"] | 2 seconds | ["3\n2\n0\n4"] | NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$). | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy",
"math"
] | 9d480b3979a7c9789fd8247120f31f03 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$. | 1,700 | For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag. | standard output | |
PASSED | 627324b1923e2aae0bbf94e6ee61ba4c | train_003.jsonl | 1596810900 | Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags! | 256 megabytes | import java.util.*;
public class Simple {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int i=0,j=0,k=0;
int t=0;
t=sc.nextInt();
while (t-->0) {
int n=sc.nextInt();
int arr[]=new int[n+1];
for (i=0;i<n;i++)
arr[sc.nextInt()]++;
ArrayList<Integer> li=new ArrayList<>();
Arrays.sort(arr);
int ind=n;
int temp=arr[n];
int max=temp;
while (temp-->0)
{
li.add(1);
}
ind--;
while (arr[ind]>0)
{
Collections.sort(li);
int cnt=arr[ind--];
if (cnt==max)
{
int tempind=0;
while (cnt-->0)
{
li.set(tempind,li.get(tempind)+1);
tempind++;
}
}
else
{
int tempind=1;
while (cnt-->0)
{
li.set(tempind,li.get(tempind)+1);
tempind++;
}
}
}
Collections.sort(li);
if (li.size()>1)
{
System.out.println((li.get(1)-1));
}
else
System.out.print("0");
}
}
static boolean isPrime(long n) {
if(n < 2) return false;
if(n == 2 || n == 3) return true;
if(n%2 == 0 || n%3 == 0) return false;
long sqrtN = (long)Math.sqrt(n)+1;
for(long i = 6L; i <= sqrtN; i += 6) {
if(n%(i-1) == 0 || n%(i+1) == 0) return false;
}
return true;
}
}
| Java | ["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"] | 2 seconds | ["3\n2\n0\n4"] | NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$). | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy",
"math"
] | 9d480b3979a7c9789fd8247120f31f03 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$. | 1,700 | For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag. | standard output | |
PASSED | c7057278ed1ac563e112d4d096d030c7 | train_003.jsonl | 1596810900 | Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags! | 256 megabytes | import java.util.*;
import java.io.*;
public class cf {
public static void main(String[] args) throws IOException, InterruptedException {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
int[] arr = new int[n];
int[] freq = new int[n + 1];
for (int i = 0; i < arr.length; i++) {
arr[i] = sc.nextInt();
freq[arr[i]]++;
}
Arrays.sort(freq);
int c = 0, max = freq[freq.length - 1], cc = 0;
for (int i = freq.length - 1; i >= 0; i--) {
if (freq[i] >= max - 1) {
c++;
} else {
cc+=freq[i];
}
}
pw.println(c + cc/(max-1) - 1);
}
pw.close();
}
static PrintWriter pw = new PrintWriter(System.out);
static class pair implements Comparable<pair> {
int x;
int y;
public pair(int x, int y) {
this.x = x;
this.y = y;
}
public String toString() {
return x + " " + y;
}
public boolean equals(Object o) {
if (o instanceof pair) {
pair p = (pair) o;
return p.x == x && p.y == y;
}
return false;
}
public int hashCode() {
return new Double(x).hashCode() * 31 + new Double(y).hashCode();
}
public int compareTo(pair other) {
if (this.x == other.x) {
return Long.compare(this.y, other.y);
}
return Long.compare(this.x, other.x);
}
}
static class tuble implements Comparable<tuble> {
int x;
int y;
int z;
public tuble(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public String toString() {
return x + " " + y + " " + z;
}
public int compareTo(tuble other) {
if (this.x == other.x) {
if (this.y == other.y)
return this.z - other.z;
return this.y - other.y;
} else {
return this.x - other.x;
}
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public boolean hasNext() {
// TODO Auto-generated method stub
return false;
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
| Java | ["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"] | 2 seconds | ["3\n2\n0\n4"] | NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$). | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy",
"math"
] | 9d480b3979a7c9789fd8247120f31f03 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$. | 1,700 | For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag. | standard output | |
PASSED | f898f044021d83c5d73dcdd24746f244 | train_003.jsonl | 1596810900 | Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags! | 256 megabytes |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class C {
public static void main(String[] args) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(in.readLine());
for (int i = 0; i < t; i++) {
String line = in.readLine();
int n = Integer.parseInt(line);
//System.err.println(n);
line = in.readLine();
//System.err.println(line);
String[] s = line.split(" ");
int[] a = new int[n+1];
for (int j = 0; j < n; j++) {
a[Integer.parseInt(s[j])]++;
}
//System.err.println(Arrays.toString(a));
List<Integer> l = new ArrayList<Integer>();
for (int j = 0; j < a.length; j++) {
if (a[j]>0) l.add(a[j]);
}
Collections.sort(l);
int tot = 0;
int max = l.get(l.size()-1);
for (int j = 0; j < l.size() - 1; j++) {
tot += l.get(j);
if (l.get(j) == max) tot--;
}
//System.err.println(l);
//System.err.println("TOT="+tot);
//System.err.println("DIV="+tot/(max-1));
System.out.println(tot/(max-1));
//System.out.println(0);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| Java | ["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"] | 2 seconds | ["3\n2\n0\n4"] | NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$). | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy",
"math"
] | 9d480b3979a7c9789fd8247120f31f03 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$. | 1,700 | For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag. | standard output | |
PASSED | 837662c6131ccba4d85812460af5634e | train_003.jsonl | 1596810900 | Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags! | 256 megabytes | // package Round662;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.*;
public class typeC {
public static void main(String[] args) {
FastReader s = new FastReader();
int T = s.nextInt();
for(int t=0;t<T;t++) {
int n = s.nextInt();
int[] arr = new int[n];
for(int i=0;i<n;i++)
arr[i] = s.nextInt();
int[] freq = new int[100002];
// Arrays.fill(freq, -1);
for(int i=0;i<n;i++)
freq[arr[i]]++;
long max = -1;
for(int i=1;i<freq.length;i++){
max = Math.max(max ,freq[i]);
}
int count = 0;
for(int i=1;i<freq.length;i++){
if(freq[i]==max)
count++;
}
long st = 0 , e = n-1;
long ans = n-1;
while(st<=e){
long m = (st+e)/2;
long p = (max-1)*(m+1) + count-1;
if(p<n){
ans = m;
st = m+1;
}
else
e = m-1;
}
System.out.println(ans);
}
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
}
| Java | ["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"] | 2 seconds | ["3\n2\n0\n4"] | NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$). | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy",
"math"
] | 9d480b3979a7c9789fd8247120f31f03 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$. | 1,700 | For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag. | standard output | |
PASSED | 51d6469f7d076c9d1e8f0cdf081f0ea7 | train_003.jsonl | 1596810900 | Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags! | 256 megabytes | // package Round662;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.*;
public class typeC {
public static void main(String[] args) {
FastReader s = new FastReader();
int T = s.nextInt();
for(int t=0;t<T;t++) {
int n = s.nextInt();
int[] arr = new int[n];
for(int i=0;i<n;i++)
arr[i] = s.nextInt();
int[] freq = new int[100002];
// Arrays.fill(freq, -1);
for(int i=0;i<n;i++)
freq[arr[i]]++;
long max = -1;
for(int i=1;i<freq.length;i++){
max = Math.max(max ,freq[i]);
}
int count = 0;
for(int i=1;i<freq.length;i++){
if(freq[i]==max)
count++;
}
int st = 0 , e = n-1;
int ans = n-1;
while(st<=e){
int m = (st+e)/2;
long p = (long)(max-1)*(m+1) + count-1;
if(p<n){
ans = m;
st = m+1;
}
else
e = m-1;
}
System.out.println(ans);
}
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
}
| Java | ["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"] | 2 seconds | ["3\n2\n0\n4"] | NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$). | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy",
"math"
] | 9d480b3979a7c9789fd8247120f31f03 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$. | 1,700 | For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag. | standard output | |
PASSED | 4f8d2dd1365baf7ca4074fd6b1addb1c | train_003.jsonl | 1596810900 | Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags! | 256 megabytes | import java.io.*;
import java.util.*;
public class Main{
static void main() throws Exception{
int n=sc.nextInt();
int maxn=(int)1e5+1;
int[]occ=new int[maxn];
int maxOcc=0,freq=0;
for(int i=0;i<n;i++) {
int x=sc.nextInt();
occ[x]++;
if(occ[x]>maxOcc) {
maxOcc=occ[x];
freq=1;
}
else {
if(occ[x]==maxOcc) {
freq++;
}
}
}
// System.out.println(maxOcc+" "+freq);
for(int i=n;i>=0;i--) {
if(freq-1+(i*1l*(maxOcc-1))<n) {
pw.println(i-1);
break;
}
}
}
public static void main(String[] args) throws Exception{
sc=new MScanner(System.in);
pw = new PrintWriter(System.out);
int tc=1;
tc=sc.nextInt();
while(tc-->0)
main();
pw.flush();
}
static PrintWriter pw;
static MScanner sc;
static class MScanner {
StringTokenizer st;
BufferedReader br;
public MScanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public MScanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int[] intArr(int n) throws IOException {
int[]inArr=new int[n];for(int i=0;i<n;i++)inArr[i]=nextInt();
return inArr;
}
public long[] longArr(int n) throws IOException {
long[]inArr=new long[n];for(int i=0;i<n;i++)inArr[i]=nextLong();
return inArr;
}
public int[] intSortedArr(int n) throws IOException {
int[]inArr=new int[n];for(int i=0;i<n;i++)inArr[i]=nextInt();
shuffle(inArr);
Arrays.sort(inArr);
return inArr;
}
public long[] longSortedArr(int n) throws IOException {
long[]inArr=new long[n];for(int i=0;i<n;i++)inArr[i]=nextLong();
shuffle(inArr);
Arrays.sort(inArr);
return inArr;
}
public Integer[] IntegerArr(int n) throws IOException {
Integer[]inArr=new Integer[n];for(int i=0;i<n;i++)inArr[i]=nextInt();
return inArr;
}
public Long[] LongArr(int n) throws IOException {
Long[]inArr=new Long[n];for(int i=0;i<n;i++)inArr[i]=nextLong();
return inArr;
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
static void shuffle(int[]inArr) {
for(int i=0;i<inArr.length;i++) {
int idx=i+(int)(Math.random()*(inArr.length-i));
int tmp=inArr[i];
inArr[i]=inArr[idx];
inArr[idx]=tmp;
}
}
static void shuffle(long[]inArr) {
for(int i=0;i<inArr.length;i++) {
int idx=i+(int)(Math.random()*(inArr.length-i));
long tmp=inArr[i];
inArr[i]=inArr[idx];
inArr[idx]=tmp;
}
}
static void shuffle(String[]inArr) {
for(int i=0;i<inArr.length;i++) {
int idx=i+(int)(Math.random()*(inArr.length-i));
String tmp=inArr[i];
inArr[i]=inArr[idx];
inArr[idx]=tmp;
}
}
} | Java | ["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"] | 2 seconds | ["3\n2\n0\n4"] | NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$). | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy",
"math"
] | 9d480b3979a7c9789fd8247120f31f03 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$. | 1,700 | For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag. | standard output | |
PASSED | 5c5896ca0f31205b4b2987e247b5bf4c | train_003.jsonl | 1596810900 | Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags! | 256 megabytes |
import java.io.*;
import java.util.*;
public class Main {
static BufferedReader br;
static int cin() throws Exception
{
return Integer.valueOf(br.readLine());
}
static int[] split() throws Exception
{
String[] cmd=br.readLine().split(" ");
int[] ans=new int[cmd.length];
for(int i=0;i<cmd.length;i++)
{
ans[i]=Integer.valueOf(cmd[i]);
}
return ans;
}
static boolean possible(int[]fre,int dist,int n)
{
ArrayList<Integer>[] lis=new ArrayList[n];
for(int i=0;i<n;i++)
{
lis[i]=new ArrayList<>();
}
for(int i=0;i<n;i++)
{
lis[0].add(-fre[i]);
}
PriorityQueue<Integer> pq=new PriorityQueue<>();
for(int i=0;i<n;i++)
{
for(int j:lis[i])
{
pq.add(j);
}
if(pq.isEmpty())
return false;
int x=pq.poll();
x++;
if(x!=0)
{
if(i+dist+1>=n)
return false;
lis[i+dist+1].add(x);
}
}
return true;
}
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
br=new BufferedReader(new InputStreamReader(System.in));
int cases=cin();
while(cases!=0)
{
cases--;
int n=cin();
int[]arr=split();
int lo=1;
int hi=n;
int[] fre=new int[n];
for(int i=0;i<n;i++)
{
fre[arr[i]-1]++;
}
while(lo<=hi)
{
int mid=(lo+hi)/2;
if(possible(fre,mid,n))
lo=mid+1;
else
hi=mid-1;
}
System.out.println(hi);
}
}
}
| Java | ["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"] | 2 seconds | ["3\n2\n0\n4"] | NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$). | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy",
"math"
] | 9d480b3979a7c9789fd8247120f31f03 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$. | 1,700 | For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag. | standard output | |
PASSED | 05d0a10cf3c90aaf23cf77ce740c1527 | train_003.jsonl | 1596810900 | Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags! | 256 megabytes | // package Quarantine;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class PinkyPatty {
public static void main(String[] args)throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int test=Integer.parseInt(br.readLine());
StringBuilder print=new StringBuilder();
while(test--!=0){
int n=Integer.parseInt(br.readLine());
int freq[]=new int[n+1];
StringTokenizer st=new StringTokenizer(br.readLine());
for(int i=1;i<=n;i++){
int x=Integer.parseInt(st.nextToken());
freq[x]++;
}
PinkyPair pair[]=new PinkyPair[n+1];
for(int i=1;i<=n;i++){
pair[i]=new PinkyPair(i,freq[i]);
}
int low=0,high=n;
int ans=0;
while(low<=high){
int mid=(low+high)>>1;
boolean f=check(mid,pair,n);
if(f){
ans=mid;
low=mid+1;
}
else{
high=mid-1;
}
}
print.append(ans).append("\n");
}
System.out.print(print.toString());
}
public static boolean check(int x,PinkyPair pair[],int n){
TreeSet<PinkyPair> set=new TreeSet<>(Collections.reverseOrder());
// System.out.println(x+" X");
PinkyPair copy[]=pair.clone();
for(int i=1;i<=n;i++){
set.add(copy[i]);
}
// System.out.println(set.toString());
int a[]=new int[n+1];
for(int i=1;i<=x+1;i++){
PinkyPair curr=set.pollFirst();
if(curr.freq==0){
return false;
}
a[i]=curr.ind;
copy[curr.ind]=new PinkyPair(curr.ind,curr.freq-1);
// System.out.println(set.toString());
}
for(int i=x+2;i<=n;i++){
set.add(copy[a[i-x-1]]);
PinkyPair curr=set.pollFirst();
if(curr.freq==0){
return false;
}
a[i]=curr.ind;
copy[curr.ind]=new PinkyPair(curr.ind,curr.freq-1);
// System.out.println(set.toString()+" "+i);
}
return true;
}
}
class PinkyPair implements Comparable<PinkyPair>{
int ind,freq;
public PinkyPair(int ind,int freq){
this.ind=ind;
this.freq=freq;
}
@Override
public int compareTo(PinkyPair o) {
if(this.freq!=o.freq){
return this.freq-o.freq;
}
else{
return this.ind-o.ind;
}
}
@Override
public String toString() {
return this.ind+" "+this.freq;
}
}
| Java | ["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"] | 2 seconds | ["3\n2\n0\n4"] | NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$). | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy",
"math"
] | 9d480b3979a7c9789fd8247120f31f03 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$. | 1,700 | For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag. | standard output | |
PASSED | 24f192a57afd5e47f124ec0f531ada60 | train_003.jsonl | 1596810900 | Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags! | 256 megabytes | import java.io.*;
import java.util.*;
public class Main
{
static ArrayList<ArrayList<Integer>> adj=new ArrayList<ArrayList<Integer>>();
public static void main(String[] args) throws IOException
{
FastScanner fs=new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int t=1;
t=fs.nextInt();
while(t-->0){
solve(fs,out);
}
out.flush();
}
public static void solve(FastScanner fs,PrintWriter out){
int n=fs.nextInt();
int f[]=new int[1_000_05];
Set<Integer> set=new HashSet<Integer>();
for(int i=1;i<=n;i++){
int num=fs.nextInt();
set.add(num);
f[num]++;
}
int max=Integer.MIN_VALUE;
for(int i=1;i<1_000_05;i++){
max=Integer.max(max,f[i]);
}
int count=0;
for(int i=1;i<1_000_05;i++){
if(f[i]==max)count++;
}
n-=(max*count);
n/=max-1;
int ans=count+n-1;
out.println(ans);
}
}
class freq{
int curr,two,four,six,eight;
freq(int curr,int two,int four,int six,int eight){
this.curr=curr;
this.two=two;
this.four=four;
this.six=six;
this.eight=eight;
}
}
class SegmentTree{
freq t[];
SegmentTree(int n){
t=new freq[n*4];
}
freq combine(freq a,freq b){
int curr=a.curr+b.curr;
int two=a.two+b.two;
int four=a.four+b.four;
int six=a.six+b.six;
int eight=a.eight+b.eight;
return new freq(curr,two,four,six,eight);
}
void build(int a[],int v,int tl,int tr){
if(tl==tr){
int val=a[tl];
int two=0;
int four=0;
int six=0;
int eight=0;
if(val>=8){
eight=1;
}else if(val>=6){
six=1;
}else if(val>=4){
four=1;
}else if(val>=2){
two=1;
}
t[v]=new freq(val,two,four,six,eight);
}else{
int tm=(tl+tr)/2;
build(a,2*v,tl,tm);
build(a,2*v+1,tm+1,tr);
t[v]=combine(t[2*v],t[2*v+1]);
}
}
void update(int v,int tl,int tr,int pos,int new_val){
if(tl==tr){
int val=t[v].curr+new_val;
int two=0;
int four=0;
int six=0;
int eight=0;
if(val>=8){
eight=1;
}else if(val>=6){
six=1;
}else if(val>=4){
four=1;
}else if(val>=2){
two=1;
}
t[v]=new freq(val,two,four,six,eight);
}else{
int tm=(tl+tr)/2;
if(pos<=tm)
update(2*v,tl,tm,pos,new_val);
else
update(2*v+1,tm+1,tr,pos,new_val);
t[v]=combine(t[2*v],t[2*v+1]);
}
}
freq querry(){
return t[1];
}
}
class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] nextIntArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
long[] nextLongArray(int n) {
long[] a=new long[n];
for (int i=0; i<n; i++) a[i]=nextLong();
return a;
}
} | Java | ["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"] | 2 seconds | ["3\n2\n0\n4"] | NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$). | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy",
"math"
] | 9d480b3979a7c9789fd8247120f31f03 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$. | 1,700 | For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag. | standard output | |
PASSED | b314d376d8945c6ce53c252a90cf1dcb | train_003.jsonl | 1596810900 | Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags! | 256 megabytes | import java.util.*;
import java.io.*;
public class PinkiePiePattyCakes {
public static int MAXN = 100001;
public static void main(String[] args) throws IOException{
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
int t = Integer.parseInt(f.readLine());
while(t-->0){
int n = Integer.parseInt(f.readLine());
int[] freqs = new int[MAXN];
StringTokenizer st = new StringTokenizer(f.readLine());
for(int i = 0; i < n; i++){
int a = Integer.parseInt(st.nextToken());
freqs[a]++;
}
int max = 0;
for(int i = 0; i < MAXN; i++) max = Math.max(freqs[i], max);
int cnt = 0;
for(int i = 0; i < MAXN; i++) if(freqs[i] == max) cnt++;
out.println(((n-cnt)/(max-1))-1);
}
out.close();
}
} | Java | ["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"] | 2 seconds | ["3\n2\n0\n4"] | NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$). | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy",
"math"
] | 9d480b3979a7c9789fd8247120f31f03 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$. | 1,700 | For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag. | standard output | |
PASSED | 8556606589b498ee0d489cfdb01d07de | train_003.jsonl | 1596810900 | Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags! | 256 megabytes | import java.io.*;
import java.util.*;
public class TaskC {
static class Pair {
int x;
int y;
Pair(int a, int b) {
x = a;
y = b;
}
}
public static void main(String[] args) throws Exception {
Reader sc = new Reader();
PrintWriter pw = new PrintWriter(System.out);
try {
int t = sc.nextInt();
while(t-->0) {
int n = sc.nextInt();
TreeMap<Integer, Integer> tm = new TreeMap<>();
for(int i=0 ; i<n ; i++) {
int x = sc.nextInt();
tm.put(x, tm.getOrDefault(x, 0) + 1);
}
int m = tm.size();
Pair[] p = new Pair[m];
int ind = 0;
for(Map.Entry<Integer, Integer> ent: tm.entrySet()) {
p[ind++] = new Pair(ent.getKey(), ent.getValue());
}
Arrays.sort(p, (o1, o2) -> o2.y - o1.y);
int l = 1;
int r = n;
int ans = 0;
while(l<=r) {
int mid = (l+r)/2;
int dif = n/mid;
int rem = n%mid;
if(rem == 0) {
rem = mid;
}
else {
dif++;
}
boolean poss = true;
if(dif == p[0].y) {
int c = 0;
for(Pair x: p) {
if(dif == x.y) {
c++;
}
}
if(c > rem) poss = false;
}
else if(dif < p[0].y) poss = false;
if(poss) {
ans = mid;
l = mid+1;
}
else r = mid-1;
}
pw.println(ans-1);
}
}
finally {
pw.flush();
pw.close();
}
}
static class Reader {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while(!st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
}
catch(IOException io) {
io.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"] | 2 seconds | ["3\n2\n0\n4"] | NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$). | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy",
"math"
] | 9d480b3979a7c9789fd8247120f31f03 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$. | 1,700 | For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag. | standard output | |
PASSED | 38f2890dc48750680d58b26f558a04a2 | train_003.jsonl | 1596810900 | Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags! | 256 megabytes | /**
* BaZ :D
*/
import java.util.*;
import java.io.*;
import static java.lang.Math.*;
public class ACMIND
{
static FastReader scan;
static PrintWriter pw;
static long MOD = 1_000_000_007;
static long INF = 2_000_000_000_000_000_000L;
static long inf = 2_000_000_000;
public static void main(String[] args) {
new Thread(null,null,"BaZ",1<<27)
{
public void run()
{
try
{
solve();
}
catch(Exception e)
{
e.printStackTrace();
System.exit(1);
}
}
}.start();
}
static int n, arr[];
static void solve() throws IOException {
scan = new FastReader();
pw = new PrintWriter(System.out, true);
StringBuilder sb = new StringBuilder();
int t = ni();
while (t-->0) {
n = ni();
arr = new int[n];
for(int i=0;i<n;++i) {
arr[i] = ni();
}
int low = 0, high = n, mid, ans = 0;
while (low<=high) {
mid = (low+high)>>1;
if(check(mid)) {
ans = mid;
low = ++mid;
}
else {
high = --mid;
}
}
pl(ans);
}
pw.flush();
pw.close();
}
static boolean check(int x) {
int freq[] = new int[n+1];
for(int i=0;i<n;++i) {
++freq[arr[i]];
}
TreeSet<Pair> eligible = new TreeSet<>();
for(int i=1;i<=n;++i) {
if(freq[i]>0) {
eligible.add(new Pair(freq[i], i));
}
}
int res[] = new int[n];
for(int i=0;i<n;++i) {
if(eligible.size()==0) {
return false;
}
Pair p = eligible.pollLast();
res[i] = p.y;
freq[p.y]--;
if(i-x>=0 && freq[res[i-x]]>0) {
eligible.add(new Pair(freq[res[i-x]], res[i-x]));
}
}
return true;
}
static class Pair implements Comparable<Pair>
{
int x,y;
Pair(int x,int y)
{
this.x=x;
this.y=y;
}
public int compareTo(Pair other)
{
if(this.x!=other.x)
return this.x-other.x;
return this.y-other.y;
}
public String toString()
{
return "("+x+","+y+")";
}
}
static int ni() throws IOException
{
return scan.nextInt();
}
static long nl() throws IOException
{
return scan.nextLong();
}
static double nd() throws IOException
{
return scan.nextDouble();
}
static void pl()
{
pw.println();
}
static void p(Object o)
{
pw.print(o+" ");
}
static void pl(Object o)
{
pw.println(o);
}
static void psb(StringBuilder sb)
{
pw.print(sb);
}
static void pa(String arrayName, Object arr[])
{
pl(arrayName+" : ");
for(Object o : arr)
p(o);
pl();
}
static void pa(String arrayName, int arr[])
{
pl(arrayName+" : ");
for(int o : arr)
p(o);
pl();
}
static void pa(String arrayName, long arr[])
{
pl(arrayName+" : ");
for(long o : arr)
p(o);
pl();
}
static void pa(String arrayName, double arr[])
{
pl(arrayName+" : ");
for(double o : arr)
p(o);
pl();
}
static void pa(String arrayName, char arr[])
{
pl(arrayName+" : ");
for(char o : arr)
p(o);
pl();
}
static void pa(String listName, List list)
{
pl(listName+" : ");
for(Object o : list)
p(o);
pl();
}
static void pa(String arrayName, Object[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(Object o : arr[i])
p(o);
pl();
}
}
static void pa(String arrayName, int[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(int o : arr[i])
p(o);
pl();
}
}
static void pa(String arrayName, long[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(long o : arr[i])
p(o);
pl();
}
}
static void pa(String arrayName, char[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(char o : arr[i])
p(o);
pl();
}
}
static void pa(String arrayName, double[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(double o : arr[i])
p(o);
pl();
}
}
static class FastReader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public FastReader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public FastReader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
byte[] buf = new byte[1000000];
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = (c == '-');
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = (c == '-');
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ') c = read();
boolean neg = (c == '-');
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') while ((c = read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10);
if (neg) return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null) return;
din.close();
}
}
} | Java | ["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"] | 2 seconds | ["3\n2\n0\n4"] | NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$). | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy",
"math"
] | 9d480b3979a7c9789fd8247120f31f03 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$. | 1,700 | For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag. | standard output | |
PASSED | c3345575e7796389548df8edd90c7d5e | train_003.jsonl | 1596810900 | Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags! | 256 megabytes | /* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{ FastReader in = new FastReader(System.in);
StringBuilder sb = new StringBuilder();
int t=1;
t=in.nextInt();
while(t>0){
--t;
int n=in.nextInt();
int arr[]=new int[n];
int max=0;
int cnt=0;
int count[]=new int[n+1];
for(int i=0;i<n;i++){
arr[i]=in.nextInt();
++count[arr[i]];
if(count[arr[i]]>max)
{
max=count[arr[i]];
cnt=1;
}
else if(count[arr[i]]==max)
++cnt;
}
int ans=n-(cnt*max);
int ans2=ans/(max-1)+cnt-1;
sb.append(ans2+"\n");
}
System.out.print(sb);
}
static int upper_bound(int arr[],int x){
int a=Arrays.binarySearch(arr,x);
if(a<0){
a*=(-1);
return a-1;
}
else{
while(a<arr.length && arr[a]==x)
++a;
return a;
}
}
static long gcd(long a ,long b)
{
if(a==0)
return b;
else return gcd(b%a,a);
}
//------making a Fendwick tree ---//
// creating a fendwick tree
static long ftree[];
static void buildFendwicktree(int arr[],int n)
{
ftree=new long[n+1];
for(int i=0;i<n;i++)
upftree(arr[i],i,n);
}
static void upftree(int value,int n,int i)
{
int index=i+1;
while(index<=n)
{
ftree[index]+=value;
index+=(index&(-index)); // adding last bit to the index
}
}
static long getSum(int index)
{
long sum=0;
index+=1;
while(index>0)
{
sum+=ftree[index];
index-=(index&(-index)); // fliping last index of the tree;
}
return sum;
}
//------Fendwick tree ends ---------//
}
class sgmtree{
int arr[];
sgmtree(int input[],int n){
arr=new int[100001];
buildtree(input,1,0,n-1);
}
void buildtree(int input[],int si,int ss,int se){
if(ss==se){
arr[si]=input[ss];
return;
}
int mid=(ss+se)/2;
buildtree(input,2*si,ss,mid);
buildtree(input,2*si+1,mid+1,se);
arr[si]=Math.min(arr[2*si],arr[2*si+1]);
}
int query(int si,int ss,int se,int qs,int qe){
if(qs>se || qe<ss)
return Integer.MAX_VALUE;
if(ss>=qs && qe>=se)
return arr[si];
int mid=(ss+se)/2;
int l=query(2*si,ss,mid,qs,qe);
int r=query(2*si+1,mid+1,se,qs,qe);
return Math.min(l,r);
}
void update(int input[],int index,int value){
input[index]=value;
updateutils(input,1,0,input.length-1,index);
}
void updateutils(int input[],int si,int ss,int se,int qi){
if(ss==se){
arr[si]=input[ss];
return;
}
int mid=(ss+se)/2;
if(qi<=mid)
updateutils(input,2*si,ss,mid,qi);
else
updateutils(input,2*si+1,mid+1,se,qi);
arr[si]=Math.min(arr[2*si],arr[2*si+1]);
}
}
/* This is for sorting first accorting to gain[1] if gain[1] is same the gain[0]
Arrays.sort(gain, (long[] l1, long[] l2) -> {
if(l1[1] != l2[1])return Long.compare(l2[1], l1[1]);//Sorting in non-increasing order of gain
return Long.compare(l1[0], l2[0]);//Choosing smallest bit among all bits having same gain
});
*/
class pair{
int x,y;
pair(int x,int y){
this.x=x;
this.y=y;
}
}
class CompareValue {
static void compare(pair arr[], int n)
{
Arrays.sort(arr, new Comparator<pair>() {
public int compare(pair p1, pair p2)
{
return p1.y - p2.y;
}
});
}
}
class CompareKey{
static void compare(pair arr[],int n){
Arrays.sort(arr,new Comparator<pair>(){
public int compare(pair p1,pair p2)
{
return p2.x-p1.x;
}
});
}
}
class FastReader {
byte[] buf = new byte[2048];
int index, total;
InputStream in;
FastReader(InputStream is) {
in = is;
}
int scan() throws IOException {
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0) {
return -1;
}
}
return buf[index++];
}
String next() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan()) ;
StringBuilder sb = new StringBuilder();
for (; c > 32; c = scan()) {
sb.append((char) c);
}
return sb.toString();
}
String nextLine() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan()) ;
StringBuilder sb = new StringBuilder();
for (; c != 10 && c != 13; c = scan()) {
sb.append((char) c);
}
return sb.toString();
}
char nextChar() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan()) ;
return (char) c;
}
int nextInt() throws IOException {
int c, val = 0;
for (c = scan(); c <= 32; c = scan()) ;
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
long nextLong() throws IOException {
int c;
long val = 0;
for (c = scan(); c <= 32; c = scan()) ;
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
} | Java | ["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"] | 2 seconds | ["3\n2\n0\n4"] | NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$). | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy",
"math"
] | 9d480b3979a7c9789fd8247120f31f03 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$. | 1,700 | For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag. | standard output | |
PASSED | f8b8ba1f4d6de901342898083af9f23f | train_003.jsonl | 1596810900 | Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags! | 256 megabytes | import com.sun.org.apache.xpath.internal.SourceTree;
import com.sun.org.apache.xpath.internal.functions.FuncFalse;
import javafx.util.Pair;
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class Contest {
public static class pair implements Comparable<pair> {
long l;
long r;
public pair(long lef, long ri) {
l = lef;
r = ri;
}
@Override
public int compareTo(pair p) {
if (l == p.l)
return Long.compare(r, p.r);
return Long.compare(l, p.l);
}
}
static int n, m;
static ArrayList<Integer>[] adj;
static int dist[];
static int parent[];
static long inf = (long) 1e18;
static int INF = (int) 1e9;
public static boolean isSimilar(char[] Arr, int s, int k) {
for (int i = s; i < k - 1; i++) {
if (Arr[i + 1] != Arr[i])
return false;
}
return true;
}
public static int ciel(int d, int mod) {
if (d % mod == 0)
return d / mod;
return (d / mod) + 1;
}
public static long gcd(long u, long v) {
if (v == 0)
return u;
return gcd(v, u % v);
}
static int k, Arr[], lefAcc[], riAcc[];
static PrintWriter pw;
static long memo[][];
static char[][] Matrix;
static int[] dx = new int[]{-1, 1, 0, 0};
static int[] dy = new int[]{0, 0, -1, 1};
static boolean valid(int i, int j) {
return i != -1 && j != -1 && i != n && j != m;
}
static boolean[][] vis = new boolean[n][m];
static void dfs2(int i, int j) {
vis[i][j] = true; //mark as visited
for (int k = 0; k < 4; ++k) {
int x = i + dx[k], y = j + dy[k];
if (valid(x, y) && Matrix[x][y] != '#' && !vis[x][y])
dfs2(x, y);
}
}
public static int getnum(int[][] matrix, int i, int j) {
int c = 0;
for (int k = 0; k < 4; ++k) {
int x = i + dx[k], y = j + dy[k];
if (valid(x, y))
c++;
}
return c;
}
static String str;
public static int howManyChar(char c, int lo, int hi) {
int cnt = 0;
for (int i = lo; i <= hi; i++) {
if (str.charAt(i) == c) cnt++;
}
return (hi - lo + 1) - cnt;
}
public static long divCon(int lo, int hi, char c) {
if (lo == hi)
return c == str.charAt(lo) ? 0 : 1;
int mid = (lo + hi) >> 1;
char next = (char) (c + 1);
return min(howManyChar(c, lo, mid) + divCon(mid + 1, hi, next),
howManyChar(c, mid + 1, hi) + divCon(lo, mid, next));
}
static Stack<Integer> topo;
public static boolean dfs(int u, int vv) {
viss[u] = vv;
boolean ans = true;
for (int v : adj[u]) {
if (viss[v] == vv)
ans = false;
if (viss[v] == 0)
ans = dfs(v, vv) & ans;
}
topo.add(u);
return ans;
}
static int viss[];
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
pw = new PrintWriter(System.out);
int t=sc.nextInt();
while(t-->0){
int n=sc.nextInt();
int[]Arr=new int[n];
int[]map=new int[n+5];
int max=0;
for (int i = 0; i < n; i++) {
Arr[i]=sc.nextInt();
map[Arr[i]]++;
max=max(max,map[Arr[i]]);
}
int num=0;
for (int i = 0; i < n+5; i++) {
if(map[i]==max)num++;
}
pw.println((n-num*max)/(max-1)+(num-1));
}
pw.close();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public boolean ready() throws IOException, IOException {
return br.ready();
}
}
} | Java | ["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"] | 2 seconds | ["3\n2\n0\n4"] | NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$). | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy",
"math"
] | 9d480b3979a7c9789fd8247120f31f03 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$. | 1,700 | For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag. | standard output | |
PASSED | a023358ec91181836d130fb84b81edbf | train_003.jsonl | 1596810900 | Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags! | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Pranay2516
*/
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);
TaskC solver = new TaskC();
int testCount = Integer.parseInt(in.next());
for (int i = 1; i <= testCount; i++)
solver.solve(i, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, FastReader in, PrintWriter out) {
int n = in.nextInt(), a[] = in.readIntArray(n), f[] = new int[n + 1];
Arrays.fill(f, 0);
for (int i = 0; i < n; ++i) f[a[i]]++;
func.sort(f);
int max = f[n], sum = 0;
for (int i = n - 1; i > 0; --i) {
if (f[i] != max) sum += f[i];
else sum += max - 1;
}
out.println(max != 1 ? sum / (max - 1) : sum);
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private FastReader.SpaceCharFilter filter;
public FastReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public String next() {
int c = read();
while (isSpaceChar(c)) c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int[] readIntArray(int size) {
int[] array = new int[(int) size];
for (int i = 0; i < size; i++) array[i] = nextInt();
return array;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class func {
public static void sort(int[] arr) {
int n = arr.length, mid, h, s, l, i, j, k;
int[] res = new int[n];
n--;
for (s = 1; s <= n; s <<= 1) {
for (l = 0; l < n; l += (s << 1)) {
h = Math.min(l + (s << 1) - 1, n);
mid = Math.min(l + s - 1, n);
i = l;
j = mid + 1;
k = l;
while (i <= mid && j <= h) res[k++] = (arr[i] <= arr[j] ? arr[i++] : arr[j++]);
while (i <= mid) res[k++] = arr[i++];
while (j <= h) res[k++] = arr[j++];
for (k = l; k <= h; k++) arr[k] = res[k];
}
}
}
}
}
| Java | ["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"] | 2 seconds | ["3\n2\n0\n4"] | NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$). | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy",
"math"
] | 9d480b3979a7c9789fd8247120f31f03 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$. | 1,700 | For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag. | standard output | |
PASSED | f8107e1bbbf3f38d427c1c3ee818dd79 | train_003.jsonl | 1596810900 | Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags! | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Pranay2516
*/
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);
TaskC solver = new TaskC();
int testCount = Integer.parseInt(in.next());
for (int i = 1; i <= testCount; i++)
solver.solve(i, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, FastReader in, PrintWriter out) {
int n = in.nextInt(), a[] = in.readIntArray(n), f[] = new int[n + 1];
Arrays.fill(f, 0);
for (int i = 0; i < n; ++i) f[a[i]]++;
Arrays.sort(f);
int max = f[n], sum = 0;
for (int i = n - 1; i > 0; --i) {
if (f[i] != max) sum += f[i];
else sum += max - 1;
}
out.println(max != 1 ? sum / (max - 1) : sum);
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private FastReader.SpaceCharFilter filter;
public FastReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public String next() {
int c = read();
while (isSpaceChar(c)) c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int[] readIntArray(int size) {
int[] array = new int[(int) size];
for (int i = 0; i < size; i++) array[i] = nextInt();
return array;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"] | 2 seconds | ["3\n2\n0\n4"] | NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$). | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy",
"math"
] | 9d480b3979a7c9789fd8247120f31f03 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$. | 1,700 | For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag. | standard output | |
PASSED | 0ed72f16800122743eb09e540e3a51c7 | train_003.jsonl | 1596810900 | Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags! | 256 megabytes | import java.util.*;
import java.io.*;
public class C662C{
static class FastReader {
BufferedReader br;
StringTokenizer st;
private 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());
}
int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
int[] nextIntArrayOne(int n) {
int[] a = new int[n+1];
for (int i = 1; i < n+1; i++)
a[i] = nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args) {
FastReader s =new FastReader();
int t = s.nextInt();
StringBuilder str = new StringBuilder();
while(t-- >0) {
int n = s.nextInt();
HashMap<Integer, Integer> map = new HashMap<>();
int batch = 0;
for(int i = 0 ; i<n; i++) {
int cur = s.nextInt();
if(map.containsKey(cur)) {
int val = map.get(cur) + 1;
map.put(cur, val);
batch = Math.max(batch, val);
}else {
map.put(cur, 1);
batch = Math.max(batch, 1);
}
}
int count = 0;
for(Map.Entry<Integer, Integer> entry : map.entrySet()) {
if(entry.getValue() == batch) {
count++;
}
}
int rem = n - batch * count;
int ans = count - 1;
ans += rem / (batch - 1);
str.append(ans +"\n");
}
System.out.println(str);
}
}
| Java | ["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"] | 2 seconds | ["3\n2\n0\n4"] | NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$). | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy",
"math"
] | 9d480b3979a7c9789fd8247120f31f03 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$. | 1,700 | For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag. | standard output | |
PASSED | 64aed858f82cc2601020247da7ef634b | train_003.jsonl | 1596810900 | Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags! | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
MyScanner sc = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out));
int t = sc.nextInt();
for (int i=0; i<t; i++) {
int n = sc.nextInt();
Map<Integer, Integer> m = new HashMap<>();
for (int j=0;j<n;j++) {
int newKey = sc.nextInt();
m.put(newKey, m.getOrDefault(newKey, 0) + 1);
}
int s = 0;
int countUnique = m.size();
int maxV = Integer.MIN_VALUE;
int maxVOcc = 0;
for (Map.Entry<Integer, Integer> entry: m.entrySet()) {
int tempV = entry.getValue();
if (tempV > maxV) {
maxV = tempV;
maxVOcc = 0;
} else if (tempV == maxV) {
maxVOcc++;
}
s += tempV;
}
s -= maxV;
s -= maxVOcc;
out.println(Math.min(countUnique - 1, s/(maxV - 1)));
}
out.close();
}
public static PrintWriter out;
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"] | 2 seconds | ["3\n2\n0\n4"] | NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$). | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy",
"math"
] | 9d480b3979a7c9789fd8247120f31f03 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$. | 1,700 | For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag. | standard output | |
PASSED | f9e7198dc41df1312ecf700f95a9c3d6 | train_003.jsonl | 1596810900 | Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags! | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Solution {
public static void main(String[] args) {
FastReader in = new FastReader();
int t = in.nextInt();
for (int x = 0; x < t; x++) {
int n = in.nextInt();
HashMap<Integer, Integer> freq = new HashMap<>();
int maxFreq = 0;
for (int y = 0; y < n; y++) {
int next = in.nextInt();
freq.put(next, freq.getOrDefault(next, 0) + 1);
maxFreq = Math.max(maxFreq, freq.get(next));
}
int elements = -(maxFreq - 1);
for (int frequency : freq.values()) {
elements += frequency;
if (frequency == maxFreq) elements--;
}
System.out.println(elements / (maxFreq - 1));
}
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
public int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; ++i) array[i] = nextInt();
return array;
}
public int[] nextSortedIntArray(int n) {
int array[] = nextIntArray(n);
Arrays.sort(array);
return array;
}
public int[] nextteamsNumIntArray(int n) {
int[] array = new int[n];
array[0] = nextInt();
for (int i = 1; i < n; ++i) array[i] = array[i - 1] + nextInt();
return array;
}
public long[] nextLongArray(int n) {
long[] array = new long[n];
for (int i = 0; i < n; ++i) array[i] = nextLong();
return array;
}
public long[] nextteamsNumLongArray(int n) {
long[] array = new long[n];
array[0] = nextInt();
for (int i = 1; i < n; ++i) array[i] = array[i - 1] + nextInt();
return array;
}
public long[] nextSortedLongArray(int n) {
long array[] = nextLongArray(n);
Arrays.sort(array);
return array;
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| Java | ["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"] | 2 seconds | ["3\n2\n0\n4"] | NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$). | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy",
"math"
] | 9d480b3979a7c9789fd8247120f31f03 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$. | 1,700 | For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag. | standard output | |
PASSED | c461cff37a1aa9d37613cb3740eda057 | train_003.jsonl | 1596810900 | Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags! | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.*;
public class code4{
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
public static void main(String args[]){
FastReader sc=new FastReader();
int t=sc.nextInt();
while(t-->0){
int n=sc.nextInt();
Map<Integer,Integer> map=new HashMap<>();
for(int i=0;i<n;i++){
int a=sc.nextInt();
map.put(a,map.getOrDefault(a,0)+1);
}
int ar[]=new int[n+1];
int max=0;
for(Map.Entry<Integer,Integer> entry:map.entrySet()){
ar[entry.getValue()]++;
max=Math.max(max,entry.getValue());
}
int ans=0;
int grp=max-1;
ans+=ar[max]-1;
//int s=0;
//for(int i=max-1;i>0;i--){s+=ar[i];}
ans+=(n-ar[max]*max)/grp;
System.out.println(ans);
}
}
} | Java | ["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"] | 2 seconds | ["3\n2\n0\n4"] | NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$). | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy",
"math"
] | 9d480b3979a7c9789fd8247120f31f03 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$. | 1,700 | For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag. | standard output | |
PASSED | d46b816b6323883c9defaabe83d47db7 | train_003.jsonl | 1596810900 | Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags! | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
//
static class TaskC {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int t =in.nextInt();
for (int d = 0; d <t ; d++) {
int n = in.nextInt();
int[] arr = new int[n+1];
int max = 0;
long sum = 0;
for (int i = 0; i <n; i++){
int v = in.nextInt();
arr[v]++;
if (arr[v]>arr[max])max=v;
}
for (int i = 1; i <=n; i++) {
if (i==max)continue;
if (arr[i]==arr[max])arr[i]--;
sum+=arr[i];
}
if (arr[max]-1==0) System.out.println(0);
else System.out.println((sum/(arr[max]-1)));
}
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
} | Java | ["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"] | 2 seconds | ["3\n2\n0\n4"] | NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$). | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy",
"math"
] | 9d480b3979a7c9789fd8247120f31f03 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$. | 1,700 | For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag. | standard output | |
PASSED | 0d0d435fddf524079dc39e7f0a096ffb | train_003.jsonl | 1596810900 | Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags! | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class C {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
// code goes here
int t = nextInt(br);
while (t-- > 0){
int n = nextInt(br);
int[] arr = nextIntArray(br, n);
HashMap<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < arr.length; i++){
map.put(arr[i], map.getOrDefault(arr[i], 0) + 1);
}
List<Pair<Integer, Integer>> list = new ArrayList<>();
for(Integer key : map.keySet()){
list.add(new Pair<>(key, map.get(key)));
}
list.sort(new Comparator<Pair<Integer, Integer>>() {
@Override
public int compare(Pair<Integer, Integer> o1, Pair<Integer, Integer> o2) {
return o2.second - o1.second;
}
});
int count = 1;
int val = list.get(0).second;
for(int i = 1; i < list.size(); i++){
if(list.get(i).second != val) break;
count++;
}
int x = n - count + 1 - list.get(0).second;
sb.append(x/(list.get(0).second - 1)).append("\n");
}
System.out.print(sb.toString());
}
private static int nextInt(BufferedReader br) throws IOException{
return Integer.parseInt(br.readLine());
}
private static int[] nextIntArray(BufferedReader br, int n) throws IOException{
StringTokenizer st = new StringTokenizer(br.readLine());
int[] arr = new int[n];
for(int i = 0; i < n; i++){
arr[i] = Integer.parseInt(st.nextToken());
}
return arr;
}
static class Pair<A, B>{
A first;
B second;
public Pair(A first, B second){
this.first = first;
this.second = second;
}
}
}
| Java | ["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"] | 2 seconds | ["3\n2\n0\n4"] | NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$). | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy",
"math"
] | 9d480b3979a7c9789fd8247120f31f03 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$. | 1,700 | For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag. | standard output | |
PASSED | 8f9d484b6e0b44f4c85f6804a8cce2ed | train_003.jsonl | 1596810900 | Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags! | 256 megabytes | import java.io.*;
import java.util.*;
import java.lang.*;
public class Rextester{
static boolean possible(int[] array,int dist,int n){
boolean[] result = new boolean[n];
for(int i=array.length-1;i>=0;i--){
if(array[i]==1){
return true;
}
int z = array[i];
int start = array.length-1-i;
while(z>0){
if(result[start]){
return true;
}
result[start]=true;
start+=dist+1;
z--;
if(start>=n&&z>0){
return false;
}
}
}
return true;
}
public static void main(String[] args)throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
StringBuffer sb = new StringBuffer();
while(t-->0){
int n = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
int[] array = new int[n+1];
int max = 0;
for(int i=0;i<n;i++){
int a = Integer.parseInt(st.nextToken());
array[a]++;
max = Math.max(max,array[a]);
}
Arrays.sort(array);
int high= Integer.MAX_VALUE,low = 0;
while(high>low){
int mid = (high+low)/2;
if(possible(array,mid,n)){
low = mid+1;
}
else{
high = mid;
}
}
if(possible(array,low,n)){
while(low<n&&possible(array,low,n)){
low++;
}
sb.append(low-1).append("\n");
}
else{
while(low>=0&&!possible(array,low,n)){
low--;
}
sb.append(low).append("\n");
}
}
br.close();
System.out.println(sb);
}
}
| Java | ["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"] | 2 seconds | ["3\n2\n0\n4"] | NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$). | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy",
"math"
] | 9d480b3979a7c9789fd8247120f31f03 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$. | 1,700 | For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag. | standard output | |
PASSED | e6310e0f9d3e01f9021afb1fc9d6986d | train_003.jsonl | 1596810900 | Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags! | 256 megabytes | import java.util.*;
import java.io.*;
public class Main{
public static void main(String args[])throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int t=Integer.parseInt(br.readLine().trim());
StringBuffer result=new StringBuffer();
while(t-->0){
int n=Integer.parseInt(br.readLine().trim());
String inp[]=br.readLine().trim().split(" ");
int arr[]=new int[n+1];
for(int i=0;i<n;i++){
arr[Integer.parseInt(inp[i])]++;
}
Arrays.sort(arr);
int low = 0;
int high = n-2;
int ans=0;
while(low<=high){
int mid = low+(high-low)/2;
if(valid(mid,arr,n)){
ans=mid;
low=mid+1;
}
else{
high=mid-1;
}
}
result.append(ans+"\n");
}
System.out.print(result);
}
public static boolean valid(int sp,int arr[],int n){
ArrayList<Integer> toAdd[]=new ArrayList[n+1];
for(int i=0;i<=n;i++)
toAdd[i] = new ArrayList<>();
PriorityQueue<Integer> pq=new PriorityQueue<>(Collections.reverseOrder());
for(int i=1;i<=n;i++)
pq.add(arr[i]);
boolean flag=true;
for(int i=1;i<=n;i++){
for(int x:toAdd[i])
pq.add(x);
if(pq.isEmpty())
return false;
int temp =pq.poll();
temp--;
if(temp>0){
if(i+sp+1 > n)
return false;
toAdd[i+sp+1].add(temp);
}
}
return true;
}
} | Java | ["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"] | 2 seconds | ["3\n2\n0\n4"] | NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$). | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy",
"math"
] | 9d480b3979a7c9789fd8247120f31f03 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$. | 1,700 | For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag. | standard output | |
PASSED | 50ca7c6557e99ad380674d63ca1e6e56 | train_003.jsonl | 1596810900 | Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags! | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class r662c {
public static void main(String[] args) {
FastScanner scan=new FastScanner();
int t=scan.nextInt();
for(int tt=0;tt<t;tt++) {
int n=scan.nextInt();
int[] f=new int[n+1];
int fr=0;
int max=0;
for(int i=0;i<n;i++) {
int x=scan.nextInt();
f[x]++;
if(f[x]>max) {
max=f[x];
fr=1;
}
else if(f[x]==max) fr++;
}
System.out.println((n-fr*max)/(max-1)+(fr-1));
// if(max>(n+1)/2) System.out.println(0);
// else {
//
// int res=(int)Math.ceil(n*1.0/max)-1;
// if(max==2) res=Math.max(res,n-2*fr);
// System.out.println(res);
// }
}
}
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 = "";
if(st.hasMoreTokens()) line = st.nextToken();
else try {return br.readLine();}catch(IOException e){e.printStackTrace();}
while(st.hasMoreTokens()) line += " "+st.nextToken();
return line;
}
}
} | Java | ["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"] | 2 seconds | ["3\n2\n0\n4"] | NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$). | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy",
"math"
] | 9d480b3979a7c9789fd8247120f31f03 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$. | 1,700 | For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag. | standard output | |
PASSED | 4aa3d349775dd72bd4ece19b542861aa | train_003.jsonl | 1596810900 | Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags! | 256 megabytes |
import java.util.*;
public class Solution {
public static int mod=1000000007;
int N;
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
for(int a=1;a<=t;a++) {
int n=sc.nextInt();
int arr[]=new int[n];
int max=0;
int maxCount=0;
Map<Integer,Integer> hmap=new HashMap<>();
for(int i=0;i<n;i++) {
arr[i]=sc.nextInt();
hmap.put(arr[i],hmap.getOrDefault(arr[i],0)+1);
if(hmap.get(arr[i])==max)
maxCount++;
if(hmap.get(arr[i])>max)
{
max=hmap.get(arr[i]);
maxCount=1;
}
}
int low=0;
int high=arr.length-1;
while(low<high) {
int mid=low+(high-low)/2;
mid++;
int slots=max-1; // total slots
int countSlots=mid-(maxCount-1); //space in each slot
long total=arr.length-(long) max*maxCount;
long emptySlots=(long) slots*countSlots; //unallocated slots
long idle=emptySlots-total;
if(idle>0) {
high=mid-1;
}
else {
low=mid;
}
}
System.out.println(low);
}
}
}
| Java | ["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"] | 2 seconds | ["3\n2\n0\n4"] | NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$). | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy",
"math"
] | 9d480b3979a7c9789fd8247120f31f03 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$. | 1,700 | For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag. | standard output | |
PASSED | 90dfd182919673c14d048996adcda044 | train_003.jsonl | 1596810900 | Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags! | 256 megabytes | //package codeforces.div2;
import java.util.*;
public class PinkiePieEatsPattyCakes {
static public class Custom {
int val;
int count;
public Custom(int val, int count) {
this.val = val;
this.count = count;
}
public int getVal() {
return val;
}
public void setVal(int val) {
this.val = val;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
static public void print(int arr[]) {
PriorityQueue<Custom> priorityQueue = new PriorityQueue<>(new Comparator<Custom>() {
@Override
public int compare(Custom o1, Custom o2) {
Integer val = o1.val;
Integer val1 = o2.val;
return val.compareTo(val1);
}
});
HashMap<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < arr.length; i++) {
map.put(arr[i], map.getOrDefault(arr[i], 0) + 1);
}
for(Map.Entry<Integer, Integer> entry : map.entrySet()) {
priorityQueue.add(new Custom(entry.getKey(), entry.getValue()));
}
int count = Integer.MAX_VALUE;
while (priorityQueue.size() > 0) {
List<Custom> list = new ArrayList<>();
int size = priorityQueue.size();
while (priorityQueue.size() > 0) {
Custom x = priorityQueue.poll();
if((x.count+1)<=priorityQueue.size()) {
list.add(priorityQueue.poll());
} else {
break;
}
}
for(int j = 0; j < list.size(); j++) {
if(list.get(j).count > 1) {
Custom x = list.get(j);
x.setCount(x.count - 1);
priorityQueue.add(x);
}
}
if(priorityQueue.size()!=0) {
count = Math.min(count, size);
}
}
System.out.println(Math.max(0, count));
}
public static void main(String []args) {
Scanner sc = new Scanner(System.in);
int p = sc.nextInt();
while ( p > 0) {
int n = sc.nextInt();
int[] a = new int[n];
int[] num = new int[n+1];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
num[a[i]]++;
}
Arrays.sort(num);
int max = num[num.length-1];
int count = 0;
for (int i = 0; i < num.length; i++) {
if (max == num[i]) {
count++;
}
}
System.out.println((n-count)/(max-1)-1);
p--;
}
}
}
| Java | ["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"] | 2 seconds | ["3\n2\n0\n4"] | NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$). | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy",
"math"
] | 9d480b3979a7c9789fd8247120f31f03 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$. | 1,700 | For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag. | standard output | |
PASSED | 4d5baf76bd5fdb2f4d4a87525fd9661d | train_003.jsonl | 1596810900 | Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags! | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class Main
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tokenizer=null;
public static void main(String[] args) throws IOException
{
new Main().execute();
}
void debug(Object...os)
{
System.out.println(Arrays.deepToString(os));
}
int ni() throws IOException
{
return Integer.parseInt(ns());
}
long nl() throws IOException
{
return Long.parseLong(ns());
}
double nd() throws IOException
{
return Double.parseDouble(ns());
}
String ns() throws IOException
{
while (tokenizer == null || !tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(br.readLine());
return tokenizer.nextToken();
}
String nline() throws IOException
{
tokenizer=null;
return br.readLine();
}
//Main Code starts Here
int totalCases, testnum;
void execute() throws IOException
{
totalCases = ni();
for(testnum = 1; testnum <= totalCases; testnum++)
{
if(!input())
break;
solve();
}
}
void solve() throws IOException
{
ni();
int[] arr = niarr();
int[] count = new int[arr.length+1];
int maxVal = -1;
int maxIndex = -1;
for( int i=0; i<arr.length; i++) {
count[arr[i]]++;
if( count[arr[i]] > maxVal ) {
maxVal = count[arr[i]];
maxIndex = arr[i];
}
}
int reqPartitions = maxVal-1;
int maxSize = 0;
int rem = 0;
for( int i=1; i<count.length; i++) {
if( count[i] != 0 && i != maxIndex ) {
if (count[i] >= reqPartitions) {
maxSize++;
} else {
if( rem + count[i] >= reqPartitions ) {
maxSize++;
rem += count[i];
rem -= reqPartitions;
} else {
rem += count[i];
}
}
}
}
System.out.println(maxSize);
}
boolean input() throws IOException
{
return true;
}
int[] niarr() throws IOException {
String str = nline();
String[] tokens = str.split(" ");
int[] arr = new int[tokens.length];
for( int i=0; i<arr.length; i++) {
arr[i] = Integer.parseInt(tokens[i]);
}
return arr;
}
} | Java | ["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"] | 2 seconds | ["3\n2\n0\n4"] | NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$). | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy",
"math"
] | 9d480b3979a7c9789fd8247120f31f03 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$. | 1,700 | For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag. | standard output | |
PASSED | 77f7a197a7d9392243762bc56d5163a6 | train_003.jsonl | 1596810900 | Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags! | 256 megabytes | // Main Code at the Bottom
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.BigInteger;
public class Main{
//Fast IO class
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
boolean env=System.getProperty("ONLINE_JUDGE") != null;
if(!env) {
try {
br=new BufferedReader(new FileReader("src\\input.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
else br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static long MOD=1000000000+7;
//debug
static void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
// Pair
static class pair{
long x,y;
pair(long a,long b){
this.x=a;
this.y=b;
}
public boolean equals(Object obj) {
if(obj == null || obj.getClass()!= this.getClass()) return false;
pair p = (pair) obj;
return (this.x==p.x && this.y==p.y);
}
public int hashCode() {
return Objects.hash(x,y);
}
}
static FastReader sc=new FastReader();
static PrintWriter out=new PrintWriter(System.out);
//Global variables and functions
static int n;
static Integer map[];
static ArrayList<pair> a;
static boolean check(int x) {
int a[]=new int[n],cur=0;
Arrays.fill(a, -1);
for(int i=0;i<=n;i++) {
if(map[i]==0) break;
while(cur<n && a[cur]!=-1) cur++;
int tmp=cur;
for(int j=0;j<map[i];j++) {
if(tmp>=n) return false;
a[tmp]=i;
tmp+=x+1;
}
}
for(int i=0;i<n;i++) if(a[i]==-1) return false;
return true;
}
//Main function(The main code starts from here)
public static void main (String[] args) throws java.lang.Exception {
int test=1;
test=sc.nextInt();
while(test-->0){
n=sc.nextInt();
map=new Integer[n+1];
Arrays.fill(map, 0);
for(int i=0;i<n;i++) map[sc.nextInt()]++;
Arrays.parallelSort(map,Collections.reverseOrder());
int l=0,r=n-2,ans=n-2;
int val=n;
for(int i=0;i<=n;i++) {
if(map[i]==0) break;
//debug(map[i]);
int x=Integer.MAX_VALUE;
if(map[i]>1)x=(val-map[i])/(map[i]-1);
ans=Math.min(ans, x);
val--;
}
//debug(val);
// while(l<=r) {
// int mid=l+(r-l)/2;
// if(check(mid)) {
// ans=mid;
// l=mid+1;
// }
// else r=mid-1;
// }
// debug(check(2));
out.println(ans);
}
out.flush();
out.close();
}
} | Java | ["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"] | 2 seconds | ["3\n2\n0\n4"] | NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$). | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy",
"math"
] | 9d480b3979a7c9789fd8247120f31f03 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$. | 1,700 | For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag. | standard output | |
PASSED | aec3a8b3ef3b8894f2e400e1dc69c11e | train_003.jsonl | 1596810900 | Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags! | 256 megabytes | // Main Code at the Bottom
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.BigInteger;
public class Main{
//Fast IO class
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
boolean env=System.getProperty("ONLINE_JUDGE") != null;
if(!env) {
try {
br=new BufferedReader(new FileReader("src\\input.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
else br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static long MOD=1000000000+7;
//debug
static void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
// Pair
static class pair{
long x,y;
pair(long a,long b){
this.x=a;
this.y=b;
}
public boolean equals(Object obj) {
if(obj == null || obj.getClass()!= this.getClass()) return false;
pair p = (pair) obj;
return (this.x==p.x && this.y==p.y);
}
public int hashCode() {
return Objects.hash(x,y);
}
}
static FastReader sc=new FastReader();
static PrintWriter out=new PrintWriter(System.out);
//Global variables and functions
static int n;
static Integer map[];
static ArrayList<pair> a;
static boolean check(int x) {
int blocks=n/(x+1),rem=n%(x+1);
for(int i: map) {
if(i==0) break;
if(i>blocks+1) return false;
if(rem<=0 && i==blocks+1) return false;
if(i==blocks+1) rem--;
}
return true;
}
//Main function(The main code starts from here)
public static void main (String[] args) throws java.lang.Exception {
int test=1;
test=sc.nextInt();
while(test-->0){
n=sc.nextInt();
map=new Integer[n+1];
Arrays.fill(map, 0);
for(int i=0;i<n;i++) map[sc.nextInt()]++;
Arrays.parallelSort(map,Collections.reverseOrder());
int l=0,r=n-2,ans=0;
while(l<=r) {
int mid=l+(r-l)/2;
if(check(mid)) {
ans=mid;
l=mid+1;
}
else r=mid-1;
}
out.println(ans);
}
out.flush();
out.close();
}
} | Java | ["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"] | 2 seconds | ["3\n2\n0\n4"] | NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$). | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy",
"math"
] | 9d480b3979a7c9789fd8247120f31f03 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$. | 1,700 | For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag. | standard output | |
PASSED | 9e6407c4669d1065c8db5ffbe501d546 | train_003.jsonl | 1596810900 | Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags! | 256 megabytes |
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int i=0;i<T;i++){
int n = sc.nextInt();
int[] arr = new int[n];
Map<Integer,Integer> map = new HashMap<>(n);
int min = Integer.MAX_VALUE;
int max = -1;
int most = 0;
for (int j=0;j<arr.length;j++) {
arr[j] = sc.nextInt();
if (arr[j] < min) min = arr[j];
if (arr[j] > max) max = arr[j];
if (map.containsKey(arr[j])) {
map.put(arr[j], map.get(arr[j]) + 1);
if(most < map.get(arr[j])) most = map.get(arr[j]);
} else {
map.put(arr[j], 1);
}
}
int key = 0;//ε δΈͺζε€§
Set<Integer> set = map.keySet();
for (Integer ii:set){
if(map.get(ii) == most) key++;
}
System.out.println((key-1)+((n-most*key)/(most-1)));
}
sc.close();
}
}
| Java | ["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"] | 2 seconds | ["3\n2\n0\n4"] | NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$). | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy",
"math"
] | 9d480b3979a7c9789fd8247120f31f03 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$. | 1,700 | For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag. | standard output | |
PASSED | 9b004001fb0b8fb69b16f7eeb248966a | train_003.jsonl | 1596810900 | Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags! | 256 megabytes | import java.util.*;
import java.io.*;
public class Main
{
public static void main(String args[])throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw=new PrintWriter(System.out);
int t=Integer.parseInt(br.readLine());
int mx=(int)1e5+1;
while(t-->0)
{
int n=Integer.parseInt(br.readLine());
int arr[]=new int[n+1];
String str[]=br.readLine().split(" ");
for(int i=0;i<n;i++)
arr[Integer.parseInt(str[i])]++;
Arrays.sort(arr);
int nt=0,cnt=0;
for(int i=n-1;i>=0;i--)
{
if(arr[i]==arr[n])
nt++;
else
cnt+=arr[i];
}
pw.println(nt+cnt/(arr[n]-1));
}
pw.flush();
pw.close();
}
} | Java | ["4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4"] | 2 seconds | ["3\n2\n0\n4"] | NoteFor the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$3$$$).For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (in this way, the minimum distance is equal to $$$2$$$). | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy",
"math"
] | 9d480b3979a7c9789fd8247120f31f03 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$): the number of patty-cakes in it. The second line of the bag description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of $$$n$$$ over all bags does not exceed $$$10^5$$$. | 1,700 | For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag. | standard output | |
PASSED | 616048ee5bf783533103554c375defc9 | train_003.jsonl | 1470578700 | Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).q events are about to happen (in chronological order). They are of three types: Application x generates a notification (this new notification is unread). Thor reads all notifications generated so far by application x (he may re-read some notifications). Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation. Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone. | 256 megabytes | //package HackerEarthA;
import java.io.*;
import java.util.*;
import java.util.Map.Entry;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import javafx.scene.layout.Priority;
import java.awt.Point;
/**
*
* @author prabhat // use stringbuilder, priorityQueue
*/
public class easy18{
public static long[] BIT;
public static long[] tree;
public static long[] sum;
public static int mod=1000000007;
public static int[][] dp;
public static boolean[][] isPalin;
public static int max1=1000010;
public static int[][] g;
public static LinkedList<Pair> l[];
public static int n,m,q,k,t,arr[],b[],cnt[],chosen[],pos[],val[],blocksize,count;
public static long V[],low,high,min=Long.MAX_VALUE,cap[],has[],ans,max;
public static ArrayList<Integer> adj[],al;
public static TreeSet<Integer> ts;
public static char[][] s;
public static int depth,mini,maxi;
public static boolean visit[][],isPrime[],used[];
public static int[][] dist;
public static ArrayList<Integer>prime;
public static int[] x={0,1};
public static int[] y={-1,0};
public static ArrayList<Integer> divisor[]=new ArrayList[1500005];
public static int[][] subtree,parent,mat;
public static TreeMap<Integer,Integer> tm;
public static LongPoint[] p;
public static int[][] grid,memo;
public static ArrayList<Pair> list;
public static TrieNode root;
public static LinkedHashMap<String,Integer> map;
public static ArrayList<String> al1;
public static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws Exception
{
InputReader in = new InputReader(System.in);
PrintWriter pw=new PrintWriter(System.out);
n=in.ii();
q=in.ii();
int[] a=new int[q];
int[] ll=new int[n+1];
int[] kk=new int[n+1];
int t=0;
int m=0;
int indx=0;
for(int i=0;i<q;i++)
{
int ty=in.ii();
int x=in.ii();
if(ty==1)
{
a[t++]=x;
kk[x]++;
m++;
}
else if(ty==2)
{
ll[x]+=kk[x];
m-=kk[x];
kk[x]=0;
}
else{
while(indx<x)
{
int u=a[indx];
if(ll[u]>0)ll[u]--;
else{
m--;
kk[u]--;
}
indx++;
}
}
pw.println(m);
}
pw.close();
}
static void Seive()
{
isPrime=new boolean[100005];
Arrays.fill(isPrime,true);
isPrime[1]=false;
// for(int i=0;i<1500005;i++){divisor[i]=new ArrayList<>();}
//int u=0;
//prime=new ArrayList<>();
for(int i=2;i<=(100000);i++)
{
if(isPrime[i])
{
// prime.add(i);
for(int j=2*i;j<=100000;j+=i)
{
//divisor[j].add(i);
isPrime[j]=false;
}
}
}
}
static int orient(Point a,Point b,Point c)
{
//return (int)(c.x-a.x)*(int)(b.y-a.y)-(int)(c.y-a.y)*(int)(b.x-a.x);
Point p1=c.minus(a);
Point p2=b.minus(a);
return (int)(p1.cross(p2));
}
public static class Polygon {
static final double EPS = 1e-15;
public int n;
public Point p[];
Polygon(int n, Point x[]) {
this.n = n;
p = Arrays.copyOf(x, n);
}
long area(){ //returns 2 * area
long ans = 0;
for(int i = 1; i + 1 < n; i++)
ans += p[i].minus(p[0]).cross(p[i + 1].minus(p[0]));
return ans;
}
boolean PointInPolygon(Point q) {
boolean c = false;
for (int i = 0; i < n; i++){
int j = (i+1)%n;
if ((p[i].y <= q.y && q.y < p[j].y ||
p[j].y <= q.y && q.y < p[i].y) &&
q.x < p[i].x + (p[j].x - p[i].x) * (q.y - p[i].y) / (p[j].y - p[i].y))
c = !c;
}
return c;
}
// determine if point is on the boundary of a polygon
boolean PointOnPolygon(Point q) {
for (int i = 0; i < n; i++)
if (ProjectPointSegment(p[i], p[(i+1)%n], q).dist(q) < EPS)
return true;
return false;
}
// project point c onto line segment through a and b
Point ProjectPointSegment(Point a, Point b, Point c) {
double r = b.minus(a).dot(b.minus(a));
if (Math.abs(r) < EPS) return a;
r = c.minus(a).dot(b.minus(a))/r;
if (r < 0) return a;
if (r > 1) return b;
return a.plus(b.minus(a).mul(r));
}
}
public static class Point {
public double x, y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public Point minus(Point b) {
return new Point(x - b.x, y - b.y);
}
public Point plus(Point a){
return new Point(x + a.x, y + a.y);
}
public double cross(Point b) {
return (double)x * b.y - (double)y * b.x;
}
public double dot(Point b) {
return (double)x * b.x + (double)y * b.y;
}
public Point mul(double r){
return new Point(x * r, y * r);
}
public double dist(Point p){
return Math.sqrt(fastHypt( x - p.x , y - p.y));
}
public double fastHypt(double x, double y){
return x * x + y * y;
}
}
static class Query implements Comparable<Query>{
int index,k;
int L;
int R;
public Query(){}
public Query(int a,int b,int index)
{
this.L=a;
this.R=b;
this.index=index;
}
public int compareTo(Query o)
{
if(L/blocksize!=o.L/blocksize)return L/blocksize-o.L/blocksize;
else return R-o.R;
}
}
static double dist(Point p1,Point p2)
{
return Math.sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y));
}
static class coder {
int indx;
String name;
coder(int indx,String name)
{
this.indx=indx;
this.name=name;
}
}
static class TrieNode
{
int value; // Only used in leaf nodes
int freq;
TrieNode[] arr = new TrieNode[2];
public TrieNode() {
value = 0;
freq=0;
arr[0] = null;
arr[1] = null;
}
}
static void insert(int pre_xor,int add)
{
TrieNode temp = root;
// Start from the msb, insert all bits of
// pre_xor into Trie
for (int i=31; i>=0; i--)
{
// Find current bit in given prefix
int val = (pre_xor & (1<<i)) >=1 ? 1 : 0;
// Create a new node if needed
if (temp.arr[val] == null)
temp.arr[val] = new TrieNode();
temp = temp.arr[val];
temp.freq+=add;
}
// Store value at leaf node
//temp.value = pre_xor;
}
static long query(int pre_xor)
{
TrieNode temp = root;
long ans=0;
for (int i=31; i>=0; i--)
{
// Find current bit in given prefix
int val = (pre_xor & (1<<i)) >= 1 ? 1 : 0;
if(temp.arr[1-val]!=null&&temp.arr[1-val].freq>0)
{
ans|=1l<<i;
temp=temp.arr[1-val];
}
else if(temp.arr[val]!=null&&temp.arr[val].freq>0)
temp=temp.arr[val];
else break;
}
return ans;
}
static void update(int indx,long val)
{
while(indx<max1)
{
BIT[indx]+=val;
indx+=(indx&(-indx));
}
}
static long query1(int indx)
{
long sum=0;
while(indx>0)
{
sum+=BIT[indx];
indx-=(indx&(-indx));
}
return sum;
}
static int gcd(int a, int b)
{
int res=0;
while(a!=0)
{
res=a;
a=b%a;
b=res;
}
return b;
}
static slope getSlope(Point p, Point q)
{
int dx = (int)(q.x - p.x), dy = (int)(q.y - p.y);
int g = gcd(dx, dy);
return new slope(dy / g, dx / g);
}
static class slope implements Comparable<slope>
{
int x,y;
public slope(int y,int x)
{
this.x=x;
this.y=y;
}
public int compareTo(slope s)
{
if(s.y!=y)return y-s.y;
return x-s.x;
}
}
static class Ball implements Comparable
{
int r;
int occ;
public Ball(int r,int occ)
{
this.r = r;
this.occ = occ;
}
@Override
public int compareTo(Object o) {
Ball b = (Ball) o;
return b.occ-this.occ;
}
}
static class E implements Comparable<E>{
int x,y;
char c;
E(int x,int y,char c)
{
this.x=x;
this.y=y;
this.c=c;
}
public int compareTo(E o)
{
if(x!=o.x)return o.x-x;
else return y-o.y;
}
}
static ArrayList<String> dfs(String s,String[] sarr,HashMap<String, ArrayList<String>> map)
{
if(map.containsKey(s))return map.get(s);
ArrayList<String> res=new ArrayList<>();
if(s.length()==0)
{
res.add("");
return res;
}
for(String word:sarr)
{
if(s.startsWith(word))
{
ArrayList<String > sub=dfs(s.substring(word.length()),sarr,map);
for(String s2:sub)
{
res.add(word+ (s2.isEmpty() ? "" : " ")+s2);
}
}
}
map.put(s,res);
return res;
}
static class SegmentTree{
int n;
int max_bound;
public SegmentTree(int n)
{
this.n=n;
tree=new long[4*n+1];
build(1,0,n-1);
}
void build(int c,int s,int e)
{
if(s==e)
{
tree[c]=arr[s];
return ;
}
int mid=(s+e)>>1;
build(2*c,s,mid);
build(2*c+1,mid+1,e);
tree[c]=(tree[2*c]&tree[2*c+1]);
}
void put(int c,int s, int e,int l,int r,int v) {
if(l>e||r<s||s>e)return ;
if (s == e)
{
tree[c] = arr[s]^v;
return;
}
int mid = (s + e) >> 1;
if (l>mid) put(2*c+1,m+1, e , l,r, v);
else if(r<=mid)put(2*c,s,m,l,r , v);
else{
}
}
long query(int c,int s,int e,int l,int r)
{
if(e<l||s>r)return 0L;
if(s>=l&&e<=r)
{
return tree[c];
}
int mid=(s+e)>>1;
long ans=(1l<<30)-1;
if(l>mid)return query(2*c+1,mid+1,e,l,r);
else if(r<=mid)return query(2*c,s,mid,l,r);
else{
return query(2*c,s,mid,l,r)&query(2*c+1,mid+1,e,l,r);
}
}
}
public static ListNode removeNthFromEnd(ListNode a, int b) {
int cnt=0;
ListNode ra1=a;
ListNode ra2=a;
while(ra1!=null){ra1=ra1.next; cnt++;}
if(b>cnt)return a.next;
else if(b==1&&cnt==1)return null;
else{
int y=cnt-b+1;
int u=0;
ListNode prev=null;
while(a!=null)
{
u++;
if(u==y)
{
if(a.next==null)prev.next=null;
else
{
if(prev==null)return ra2.next;
prev.next=a.next;
a.next=null;
}
break;
}
prev=a;
a=a.next;
}
}
return ra2;
}
static ListNode rev(ListNode a)
{
ListNode prev=null;
ListNode cur=a;
ListNode next=null;
while(cur!=null)
{
next=cur.next;
cur.next=prev;
prev=cur;
cur=next;
}
return prev;
}
static class ListNode {
public int val;
public ListNode next;
ListNode(int x) { val = x; next = null; }
}
public static String add(String s1,String s2)
{
int n=s1.length()-1;
int m=s2.length()-1;
int rem=0;
int carry=0;
int i=n;
int j=m;
String ans="";
while(i>=0&&j>=0)
{
int c1=(int)(s1.charAt(i)-'0');
int c2=(int)(s2.charAt(j)-'0');
int sum=c1+c2;
sum+=carry;
rem=sum%10;
carry=sum/10;
ans=rem+ans;
i--; j--;
}
while(i>=0)
{
int c1=(int)(s1.charAt(i)-'0');
int sum=c1;
sum+=carry;
rem=sum%10;
carry=sum/10;
ans=rem+ans;
i--;
}
while(j>=0)
{
int c2=(int)(s2.charAt(j)-'0');
int sum=c2;
sum+=carry;
rem=sum%10;
carry=sum/10;
ans=rem+ans;
j--;
}
if(carry>0)ans=carry+ans;
return ans;
}
public static String[] multiply(String A, String B) {
int lb=B.length();
char[] a=A.toCharArray();
char[] b=B.toCharArray();
String[] s=new String[lb];
int cnt=0;
int y=0;
String s1="";
q=0;
for(int i=b.length-1;i>=0;i--)
{
int rem=0;
int carry=0;
for(int j=a.length-1;j>=0;j--)
{
int mul=(int)(b[i]-'0')*(int)(a[j]-'0');
mul+=carry;
rem=mul%10;
carry=mul/10;
s1=rem+s1;
}
s1=carry+s1;
s[y++]=s1;
q=Math.max(q,s1.length());
s1="";
for(int i1=0;i1<y;i1++)s1+='0';
}
return s;
}
public static long nCr(long total, long choose)
{
if(total < choose)
return 0;
if(choose == 0 || choose == total)
return 1;
return nCr(total-1,choose-1)+nCr(total-1,choose);
}
static int get(long s)
{
int ans=0;
for(int i=0;i<n;i++)
{
if(p[i].x<=s&&s<=p[i].y)ans++;
}
return ans;
}
static class LongPoint {
public long x;
public long y;
public LongPoint(long x, long y) {
this.x = x;
this.y = y;
}
public LongPoint subtract(LongPoint o) {
return new LongPoint(x - o.x, y - o.y);
}
public long cross(LongPoint o) {
return x * o.y - y * o.x;
}
}
static int CountPs(String s,int n)
{
boolean b=false;
char[] S=s.toCharArray();
int[][] dp=new int[n][n];
boolean[][] p=new boolean[n][n];
for(int i=0;i<n;i++)p[i][i]=true;
for(int i=0;i<n-1;i++)
{
if(S[i]==S[i+1])
{
p[i][i+1]=true;
dp[i][i+1]=0;
b=true;
}
}
for(int gap=2;gap<n;gap++)
{
for(int i=0;i<n-gap;i++)
{
int j=gap+i;
if(S[i]==S[j]&&p[i+1][j-1]){p[i][j]=true;}
if(p[i][j])
dp[i][j]=dp[i][j-1]+dp[i+1][j]+1-dp[i+1][j-1];
else if(!p[i][j]) dp[i][j]=dp[i][j-1]+dp[i+1][j]-dp[i+1][j-1];
//if(dp[i][j]>=1)
// return true;
}
}
// return b;
return dp[0][n-1];
}
static long divCeil(long a,long b)
{
return (a+b-1)/b;
}
static long root(int pow, long x) {
long candidate = (long)Math.exp(Math.log(x)/pow);
candidate = Math.max(1, candidate);
while (pow(candidate, pow) <= x) {
candidate++;
}
return candidate-1;
}
static long pow(long x, int pow)
{
long result = 1;
long p = x;
while (pow > 0) {
if ((pow&1) == 1) {
if (result > Long.MAX_VALUE/p) return Long.MAX_VALUE;
result *= p;
}
pow >>>= 1;
if (pow > 0 && p >= 4294967296L) return Long.MAX_VALUE;
p *= p;
}
return result;
}
static boolean valid(int i,int j)
{
if(i>=0&&i<n&&j>=0&&j<m)return true;
return false;
}
private static class DSU{
int[] parent;
int[] rank;
int cnt;
public DSU(int n){
parent=new int[n];
rank=new int[n];
for(int i=0;i<n;i++){
parent[i]=i;
rank[i]=1;
}
cnt=n;
}
int find(int i){
while(parent[i] !=i){
parent[i]=parent[parent[i]];
i=parent[i];
}
return i;
}
int Union(int x, int y){
int xset = find(x);
int yset = find(y);
if(xset!=yset)
cnt--;
if(rank[xset]<rank[yset]){
parent[xset] = yset;
rank[yset]+=rank[xset];
rank[xset]=0;
return yset;
}else{
parent[yset]=xset;
rank[xset]+=rank[yset];
rank[yset]=0;
return xset;
}
}
}
public static int[][] packU(int n, int[] from, int[] to, int max) {
int[][] g = new int[n][];
int[] p = new int[n];
for (int i = 0; i < max; i++) p[from[i]]++;
for (int i = 0; i < max; i++) p[to[i]]++;
for (int i = 0; i < n; i++) g[i] = new int[p[i]];
for (int i = 0; i < max; i++) {
g[from[i]][--p[from[i]]] = to[i];
g[to[i]][--p[to[i]]] = from[i];
}
return g;
}
public static int[][] parents3(int[][] g, int root) {
int n = g.length;
int[] par = new int[n];
Arrays.fill(par, -1);
int[] depth = new int[n];
depth[0] = 0;
int[] q = new int[n];
q[0] = root;
for (int p = 0, r = 1; p < r; p++) {
int cur = q[p];
for (int nex : g[cur]) {
if (par[cur] != nex) {
q[r++] = nex;
par[nex] = cur;
depth[nex] = depth[cur] + 1;
}
}
}
return new int[][]{par, q, depth};
}
public static int lower_bound(int[] nums, int target) {
int low = 0, high = nums.length - 1;
while (low < high) {
int mid = low + (high - low) / 2;
if (nums[mid] < target)
low = mid + 1;
else
high = mid;
}
return nums[low] == target ? low : -1;
}
public static int upper_bound(int[] nums, int target) {
int low = 0, high = nums.length - 1;
while (low < high) {
int mid = low + (high + 1 - low) / 2;
if (nums[mid] > target)
high = mid - 1;
else
low = mid;
}
return nums[low] == target ? low : -1;
}
public static boolean palin(String s)
{
int i=0;
int j=s.length()-1;
while(i<j)
{
if(s.charAt(i)==s.charAt(j))
{
i++;
j--;
}
else return false;
}
return true;
}
static int lcm(int a,int b)
{
return (a*b)/(gcd(a,b));
}
public static long pow(long n,long p,long m)
{
long result = 1;
if(p==0)
return 1;
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;
}
/**
*
* @param n
* @param p
* @return
*/
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 Edge implements Comparator<Edge> {
private int u;
private int v;
private long w;
public Edge() {
}
public Edge(int u, int v, long w) {
this.u=u;
this.v=v;
this.w=w;
}
public int getU() {
return u;
}
public void setU(int u) {
this.u = u;
}
public int getV() {
return v;
}
public void setV(int v) {
this.v = v;
}
public long getW() {
return w;
}
public void setW(int w) {
this.w = w;
}
public long compareTo(Edge e)
{
return (this.getW() - e.getW());
}
@Override
public int compare(Edge o1, Edge o2) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
static class Pair implements Comparable<Pair>
{
int x,y;
Pair (int a,int b)
{
this.x=a;
this.y=b;
}
public int compareTo(Pair o) {
// TODO Auto-generated method stub
if(this.x!=o.x)
return -Integer.compare(this.x,o.x);
else
return -Integer.compare(this.y, o.y);
//return 0;
}
public boolean equals(Object o) {
if (o instanceof Pair) {
Pair p = (Pair)o;
return p.x == x && p.y == y;
}
return false;
}
public int hashCode() {
return new Integer(x).hashCode() * 31 + new Integer(y).hashCode();
}
}
static class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private SpaceCharFilter filter;
byte inbuffer[] = new byte[1024];
int lenbuffer = 0, ptrbuffer = 0;
final int M = (int) 1e9 + 7;
int md=(int)(1e7+1);
int[] SMP=new int[md];
final double eps = 1e-6;
final double pi = Math.PI;
PrintWriter out;
String check = "";
InputStream obj = check.isEmpty() ? System.in : new ByteArrayInputStream(check.getBytes());
public InputReader(InputStream stream)
{
this.stream = stream;
}
int readByte() {
if (lenbuffer == -1) throw new InputMismatchException();
if (ptrbuffer >= lenbuffer) {
ptrbuffer = 0;
try {
lenbuffer = obj.read(inbuffer);
} catch (IOException e) {
throw new InputMismatchException();
}
}
if (lenbuffer <= 0) return -1;
return inbuffer[ptrbuffer++];
}
public int read()
{
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;
}
String is() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) // when nextLine, (isSpaceChar(b) && b!=' ')
{
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public int ii() {
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();
}
}
public long il() {
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();
}
}
boolean isSpaceChar(int c) {
return (!(c >= 33 && c <= 126));
}
int skip()
{
int b;
while ((b = readByte()) != -1 && isSpaceChar(b)) ;
return b;
}
float nf() {
return Float.parseFloat(is());
}
double id() {
return Double.parseDouble(is());
}
char ic() {
return (char) skip();
}
int[] iia(int n) {
int a[] = new int[n];
for (int i = 0; i<n; i++) a[i] = ii();
return a;
}
long[] ila(int n) {
long a[] = new long[n];
for (int i = 0; i <n; i++) a[i] = il();
return a;
}
String[] isa(int n) {
String a[] = new String[n];
for (int i = 0; i < n; i++) a[i] = is();
return a;
}
long mul(long a, long b) { return a * b % M; }
long div(long a, long b)
{
return mul(a, pow(b, M - 2));
}
double[][] idm(int n, int m) {
double a[][] = new double[n][m];
for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) a[i][j] = id();
return a;
}
int[][] iim(int n, int m) {
int a[][] = new int[n][m];
for (int i = 0; i < n; i++) for (int j = 0; j <m; j++) a[i][j] = ii();
return a;
}
public String readLine() {
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 interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
public boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
}
| Java | ["3 4\n1 3\n1 1\n1 2\n2 3", "4 6\n1 2\n1 4\n1 2\n3 3\n1 3\n1 3"] | 2 seconds | ["1\n2\n3\n2", "1\n2\n3\n0\n1\n2"] | NoteIn the first sample: Application 3 generates a notification (there is 1 unread notification). Application 1 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads the notification generated by application 3, there are 2 unread notifications left. In the second sample test: Application 2 generates a notification (there is 1 unread notification). Application 4 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads first three notifications and since there are only three of them so far, there will be no unread notification left. Application 3 generates a notification (there is 1 unread notification). Application 3 generates a notification (there are 2 unread notifications). | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | a5e724081ad84f88813bb4de23a8230e | The first line of input contains two integers n and q (1ββ€βn,βqββ€β300β000)Β β the number of applications and the number of events to happen. The next q lines contain the events. The i-th of these lines starts with an integer typeiΒ β type of the i-th event. If typeiβ=β1 or typeiβ=β2 then it is followed by an integer xi. Otherwise it is followed by an integer ti (1ββ€βtypeiββ€β3,β1ββ€βxiββ€βn,β1ββ€βtiββ€βq). | 1,600 | Print the number of unread notifications after each event. | standard output | |
PASSED | 89873c7729edbc6dd8d92e760779c479 | train_003.jsonl | 1470578700 | Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).q events are about to happen (in chronological order). They are of three types: Application x generates a notification (this new notification is unread). Thor reads all notifications generated so far by application x (he may re-read some notifications). Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation. Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] line = br.readLine().split(" ");
int n = Integer.parseInt(line[0]);
int q = Integer.parseInt(line[1]);
int[][] arr = new int[q][2];
for(int i = 0; i < q; i++) {
line = br.readLine().split(" ");
arr[i][0] = Integer.parseInt(line[0]);
arr[i][1] = Integer.parseInt(line[1]);
}
int[] ans = computeUnreadNotification(arr, n);
for(int i = 0; i < ans.length; i++) {
bw.write(String.valueOf(ans[i]));
bw.newLine();
}
br.close();
bw.close();
}
private static int[] computeUnreadNotification(int[][] arr, int n) {
List<Queue<ThorPair<Integer, Integer>>> apps = new ArrayList<Queue<ThorPair<Integer, Integer>>>();
Queue<ThorPair<Integer, Integer>> Q = new LinkedList<ThorPair<Integer, Integer>>();
for(int i = 0; i < n+1; i++) {
apps.add(new LinkedList<ThorPair<Integer, Integer>>());
}
int[] unread = new int[arr.length];
int cur = 0;
int ctr = 0;
for(int i = 0; i < arr.length; i++) {
switch(arr[i][0]) {
case 1: {
cur += 1;
ThorPair<Integer, Integer> p = new ThorPair<Integer, Integer>(new Integer(++ctr), new Integer(arr[i][1]));
apps.get(arr[i][1]).add(p);
Q.add(p);
unread[i] = cur;
break;
}
case 2: {
while(!apps.get(arr[i][1]).isEmpty()) {
apps.get(arr[i][1]).poll().clearFlag();
--cur;
}
unread[i] = cur;
break;
}
case 3: {
while(!Q.isEmpty() && Q.peek().getX() <= arr[i][1]) {
ThorPair <Integer, Integer> p = Q.poll();
if(p.getFlag()) {
--cur;
apps.get(p.getY()).poll();
}
}
unread[i] = cur;
break;
}
}
}
return unread;
}
}
class ThorPair <T, Z>{
private T x;
private Z y;
private boolean flag;
public ThorPair(T x, Z y) {
this.x = x;
this.y = y;
flag = true;
}
public T getX() {
return x;
}
public Z getY() {
return y;
}
public void clearFlag() {
this.flag = false;
}
public boolean getFlag() {
return flag;
}
}
| Java | ["3 4\n1 3\n1 1\n1 2\n2 3", "4 6\n1 2\n1 4\n1 2\n3 3\n1 3\n1 3"] | 2 seconds | ["1\n2\n3\n2", "1\n2\n3\n0\n1\n2"] | NoteIn the first sample: Application 3 generates a notification (there is 1 unread notification). Application 1 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads the notification generated by application 3, there are 2 unread notifications left. In the second sample test: Application 2 generates a notification (there is 1 unread notification). Application 4 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads first three notifications and since there are only three of them so far, there will be no unread notification left. Application 3 generates a notification (there is 1 unread notification). Application 3 generates a notification (there are 2 unread notifications). | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | a5e724081ad84f88813bb4de23a8230e | The first line of input contains two integers n and q (1ββ€βn,βqββ€β300β000)Β β the number of applications and the number of events to happen. The next q lines contain the events. The i-th of these lines starts with an integer typeiΒ β type of the i-th event. If typeiβ=β1 or typeiβ=β2 then it is followed by an integer xi. Otherwise it is followed by an integer ti (1ββ€βtypeiββ€β3,β1ββ€βxiββ€βn,β1ββ€βtiββ€βq). | 1,600 | Print the number of unread notifications after each event. | standard output | |
PASSED | b07a9a5a767944914e247871807b7712 | train_003.jsonl | 1470578700 | Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).q events are about to happen (in chronological order). They are of three types: Application x generates a notification (this new notification is unread). Thor reads all notifications generated so far by application x (he may re-read some notifications). Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation. Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone. | 256 megabytes | import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Scanner;
import java.util.Set;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int q = sc.nextInt();
int[] types = new int[q];
int[] arguments = new int[q];
for (int i = 0; i < q; i++) {
types[i] = sc.nextInt();
arguments[i] = sc.nextInt();
}
System.out.println(solve(n, types, arguments));
sc.close();
}
static String solve(int n, int[] types, int[] arguments) {
List<Integer> result = new ArrayList<>();
int unread = 0;
int maxReadForType3 = 0;
@SuppressWarnings("unchecked")
Set<Integer>[] timesInApplication = new Set[n + 1];
for (int i = 1; i < timesInApplication.length; i++) {
timesInApplication[i] = new HashSet<>();
}
Queue<Integer> queue = new LinkedList<>();
for (int time = 0; time < types.length; time++) {
if (types[time] == 1) {
unread++;
timesInApplication[arguments[time]].add(time);
queue.offer(time);
} else if (types[time] == 2) {
unread -= timesInApplication[arguments[time]].size();
timesInApplication[arguments[time]].clear();
} else {
int count = Math.max(0, arguments[time] - maxReadForType3);
maxReadForType3 += count;
for (int i = 0; i < count; i++) {
int readTime = queue.poll();
if (timesInApplication[arguments[readTime]].contains(readTime)) {
unread--;
timesInApplication[arguments[readTime]].remove(readTime);
}
}
}
result.add(unread);
}
return result.stream().map(String::valueOf).collect(Collectors.joining("\n"));
}
}
| Java | ["3 4\n1 3\n1 1\n1 2\n2 3", "4 6\n1 2\n1 4\n1 2\n3 3\n1 3\n1 3"] | 2 seconds | ["1\n2\n3\n2", "1\n2\n3\n0\n1\n2"] | NoteIn the first sample: Application 3 generates a notification (there is 1 unread notification). Application 1 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads the notification generated by application 3, there are 2 unread notifications left. In the second sample test: Application 2 generates a notification (there is 1 unread notification). Application 4 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads first three notifications and since there are only three of them so far, there will be no unread notification left. Application 3 generates a notification (there is 1 unread notification). Application 3 generates a notification (there are 2 unread notifications). | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | a5e724081ad84f88813bb4de23a8230e | The first line of input contains two integers n and q (1ββ€βn,βqββ€β300β000)Β β the number of applications and the number of events to happen. The next q lines contain the events. The i-th of these lines starts with an integer typeiΒ β type of the i-th event. If typeiβ=β1 or typeiβ=β2 then it is followed by an integer xi. Otherwise it is followed by an integer ti (1ββ€βtypeiββ€β3,β1ββ€βxiββ€βn,β1ββ€βtiββ€βq). | 1,600 | Print the number of unread notifications after each event. | standard output | |
PASSED | 8970bff4c2a5ad3d8712ccd3a2a487b0 | train_003.jsonl | 1470578700 | Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).q events are about to happen (in chronological order). They are of three types: Application x generates a notification (this new notification is unread). Thor reads all notifications generated so far by application x (he may re-read some notifications). Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation. Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) {
FastScanner in = new FastScanner();
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out), true);
int numApps = in.nextInt();
int numEvents = in.nextInt();
int unreadNotifications = 0;
Queue<Notification> allNotifications = new LinkedList<>();
int allNotificationsDismissed = 0;
HashMap<Integer, ArrayList<Notification>> appNotifications = new HashMap<>();
for(int i = 0; i < numEvents; ++i){
int eventType = in.nextInt();
switch(eventType) {
case 1: {
int app = in.nextInt();
Notification newNotification = new Notification();
allNotifications.offer(newNotification);
ArrayList<Notification> notifications = appNotifications.getOrDefault(app, new ArrayList<Notification>());
notifications.add(newNotification);
appNotifications.put(app, notifications);
++unreadNotifications;
break;
}
case 2: {
int app = in.nextInt();
ArrayList<Notification> notifications = appNotifications.getOrDefault(app, new ArrayList<Notification>());
for(Notification notification: notifications) {
if(notification.unread) {
notification.markRead();
--unreadNotifications;
}
}
appNotifications.put(app, new ArrayList<Notification>());
break;
}
case 3: {
int notificationsToRead = in.nextInt();
if(notificationsToRead <= allNotificationsDismissed) break;
for(int j = 0; j < notificationsToRead - allNotificationsDismissed; ++j) {
Notification notification = allNotifications.poll();
if(notification.unread) {
notification.markRead();
--unreadNotifications;
}
}
allNotificationsDismissed = notificationsToRead;
break;
}
}
out.println(unreadNotifications);
}
}
}
class Notification{
public boolean unread;
public Notification() {
unread = true;
}
public void markRead() {
unread = false;
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(Reader in) {
br = new BufferedReader(in);
}
public FastScanner() {
this(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 readNextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] readIntArray(int n) {
int[] a = new int[n];
for (int idx = 0; idx < n; idx++) {
a[idx] = nextInt();
}
return a;
}
long[] readLongArray(int n) {
long[] a = new long[n];
for (int idx = 0; idx < n; idx++) {
a[idx] = nextLong();
}
return a;
}
} | Java | ["3 4\n1 3\n1 1\n1 2\n2 3", "4 6\n1 2\n1 4\n1 2\n3 3\n1 3\n1 3"] | 2 seconds | ["1\n2\n3\n2", "1\n2\n3\n0\n1\n2"] | NoteIn the first sample: Application 3 generates a notification (there is 1 unread notification). Application 1 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads the notification generated by application 3, there are 2 unread notifications left. In the second sample test: Application 2 generates a notification (there is 1 unread notification). Application 4 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads first three notifications and since there are only three of them so far, there will be no unread notification left. Application 3 generates a notification (there is 1 unread notification). Application 3 generates a notification (there are 2 unread notifications). | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | a5e724081ad84f88813bb4de23a8230e | The first line of input contains two integers n and q (1ββ€βn,βqββ€β300β000)Β β the number of applications and the number of events to happen. The next q lines contain the events. The i-th of these lines starts with an integer typeiΒ β type of the i-th event. If typeiβ=β1 or typeiβ=β2 then it is followed by an integer xi. Otherwise it is followed by an integer ti (1ββ€βtypeiββ€β3,β1ββ€βxiββ€βn,β1ββ€βtiββ€βq). | 1,600 | Print the number of unread notifications after each event. | standard output | |
PASSED | 63a67e2b36a7234ff22bfc4be52d56ed | train_003.jsonl | 1470578700 | Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).q events are about to happen (in chronological order). They are of three types: Application x generates a notification (this new notification is unread). Thor reads all notifications generated so far by application x (he may re-read some notifications). Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation. Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone. | 256 megabytes | import java.io.*;
import java.util.*;
public class A {
@SuppressWarnings("unchecked")
public static void solution(BufferedReader reader, PrintWriter out)
throws IOException {
In in = new In(reader);
int n = in.nextInt(), q = in.nextInt();
LinkedList<Integer>[] notif = new LinkedList[n + 1];
for (int i = 1; i <= n; i++)
notif[i] = new LinkedList<Integer>();
boolean[] check = new boolean[q];
int nid = 0, cid = 0;
int ans = 0;
for (int i = 0; i < q; i++) {
int t = in.nextInt();
if (t == 1) {
int x = in.nextInt();
notif[x].add(nid++);
ans++;
}
else if (t == 2) {
int x = in.nextInt();
for (Integer id : notif[x])
if (!check[id]) {
check[id] = true;
ans--;
}
notif[x].clear();
}
else if (t == 3) {
int id = in.nextInt();
for (; cid < id; cid++) {
if (!check[cid]) {
check[cid] = true;
ans--;
}
}
}
out.println(ans);
}
}
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 4\n1 3\n1 1\n1 2\n2 3", "4 6\n1 2\n1 4\n1 2\n3 3\n1 3\n1 3"] | 2 seconds | ["1\n2\n3\n2", "1\n2\n3\n0\n1\n2"] | NoteIn the first sample: Application 3 generates a notification (there is 1 unread notification). Application 1 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads the notification generated by application 3, there are 2 unread notifications left. In the second sample test: Application 2 generates a notification (there is 1 unread notification). Application 4 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads first three notifications and since there are only three of them so far, there will be no unread notification left. Application 3 generates a notification (there is 1 unread notification). Application 3 generates a notification (there are 2 unread notifications). | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | a5e724081ad84f88813bb4de23a8230e | The first line of input contains two integers n and q (1ββ€βn,βqββ€β300β000)Β β the number of applications and the number of events to happen. The next q lines contain the events. The i-th of these lines starts with an integer typeiΒ β type of the i-th event. If typeiβ=β1 or typeiβ=β2 then it is followed by an integer xi. Otherwise it is followed by an integer ti (1ββ€βtypeiββ€β3,β1ββ€βxiββ€βn,β1ββ€βtiββ€βq). | 1,600 | Print the number of unread notifications after each event. | standard output | |
PASSED | 7ee9bbebd464c56e7744184190a5298d | train_003.jsonl | 1470578700 | Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).q events are about to happen (in chronological order). They are of three types: Application x generates a notification (this new notification is unread). Thor reads all notifications generated so far by application x (he may re-read some notifications). Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation. Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.BigInteger;
import java.math.MathContext;
import java.text.DecimalFormat;
import java.text.Format;
import static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
import java.awt.List;
public class Main {
public static void main(String[] args){
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
//public ArrayList<Integer> ar;
public boolean[] bs;
// GCD && LCM
long gcd(long a ,long b){return b == 0 ? a : gcd(b , a % b);}
long lcm(long a , long b){return a*(b/gcd(a, b));}
// Sieve of erothenese
void sieve(int UB){
// ar = new ArrayList();
bs = new boolean[UB+1];
bs[0] = bs[1] = true;
for(int i = 2; i*i <= UB; i++){
if(!bs[i]){
for(int j = i*i ; j <= UB ; j += i)
bs[j] = true;
}
}
/* for(int i = 2; i <= UB; i++){
if(!bs[i])ar.add(i);
}*/
}
// REverse a String
String rev(String s){
return new StringBuilder(s).reverse().toString();
}
/* SOLUTION IS RIGHT HERE */
public void solve(int testNumber, InputReader in, PrintWriter out) {
// BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// Scanner sc = new Scanner(System.in);
int n = in.nextInt(),
q = in.nextInt();
TreeSet<Integer>[] tree = new TreeSet[n+1];
for(int i = 1; i <= n; i++ )
tree[i] = new TreeSet<>();
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
int prev = 1 , res = 0, count = 1;
for(int i = 0; i < q; i++){
int cas = in.nextInt() , x = in.nextInt();
switch(cas){
case 1 :{ tree[x].add(count); count++; res++; list.add(x); break;}
case 2 :{ res -= tree[x].size(); tree[x] = new TreeSet<>(); break;}
case 3 :{
for(int k = prev; k <= x; k++ ){
int h = list.get(k);
if(tree[h].contains(k)){
res--;
}
tree[h].remove(k);
}
prev = max(x , prev);
break;}
}
out.println(res);
}
}
}
// ||||||| INPUT READER ||||||||
static class InputReader {
private byte[] buf = new byte[2048];
private int index;
private int total;
private InputStream in;
public InputReader(InputStream stream){
in = stream;
}
public int scan(){
if(total == -1)
throw new InputMismatchException();
if(index >= total){
index = 0;
try{
total = in.read(buf);
}catch(IOException e){
throw new InputMismatchException();
}
if(total <= 0)
return -1;
}
return buf[index++];
}
public long scanlong(){
long integer = 0;
int n = scan();
while(isWhiteSpace(n))
n = scan();
int neg = 1;
if(n == '-'){
neg = -1;
n = scan();
}
while(!isWhiteSpace(n)){
if(n >= '0' && n <= '9'){
integer *= 10;
integer += n - '0';
n = scan();
}
else throw new InputMismatchException();
}
return neg*integer;
}
private int scanInt() {
int integer = 0;
int n = scan();
while(isWhiteSpace(n))
n = scan();
int neg = 1;
if(n == '-'){
neg = -1;
n = scan();
}
while(!isWhiteSpace(n)){
if(n >= '0' && n <= '9'){
integer *= 10;
integer += n - '0';
n = scan();
}
else throw new InputMismatchException();
}
return neg*integer;
}
public double scandouble(){
double doubll = 0;
int n = scan();
int neg = 1;
while(isWhiteSpace(n))
n = scan();
if(n == '-'){
neg = -1;
n = scan();
}
while(!isWhiteSpace(n) && n != '.'){
if(n >= '0' && n <= '9'){
doubll *= 10;
doubll += n - '0';
n = scan();
}
}
if(n == '.'){
n = scan();
double temp = 1;
while(!isWhiteSpace(n)){
if(n >= '0' && n <= '9'){
temp /= 10;
doubll += (n - '0')*temp;
n = scan();
}
}
}
return neg*doubll;
}
private float scanfloat() {
float doubll = 0;
int n = scan();
int neg = 1;
while(isWhiteSpace(n))
n = scan();
if(n == '-'){
neg = -1;
n = scan();
}
while(!isWhiteSpace(n) && n != '.'){
if(n >= '0' && n <= '9'){
doubll *= 10;
doubll += n - '0';
n = scan();
}
}
if(n == '.'){
n = scan();
double temp = 1;
while(!isWhiteSpace(n)){
if(n >= '0' && n <= '9'){
temp /= 10;
doubll += (n - '0')*temp;
n = scan();
}
}
}
return neg*doubll;
}
public String scanstring(){
StringBuilder sb = new StringBuilder();
int n = scan();
while(isWhiteSpace(n))
n = scan();
while(!isWhiteSpace(n)){
sb.append((char)n);
n = scan();
}
return sb.toString();
}
public boolean isWhiteSpace(int n){
if(n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1)
return true;
return false;
}
/// Input module
public int nextInt(){
return scanInt();
}
public long nextLong(){
return scanlong();
}
public double nextDouble(){
return scandouble();
}
public float nextFloat(){
return scanfloat();
}
public String next(){
return scanstring();
}
public int[] readIntArray(int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = nextInt();
}
return array;
}
}
}
| Java | ["3 4\n1 3\n1 1\n1 2\n2 3", "4 6\n1 2\n1 4\n1 2\n3 3\n1 3\n1 3"] | 2 seconds | ["1\n2\n3\n2", "1\n2\n3\n0\n1\n2"] | NoteIn the first sample: Application 3 generates a notification (there is 1 unread notification). Application 1 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads the notification generated by application 3, there are 2 unread notifications left. In the second sample test: Application 2 generates a notification (there is 1 unread notification). Application 4 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads first three notifications and since there are only three of them so far, there will be no unread notification left. Application 3 generates a notification (there is 1 unread notification). Application 3 generates a notification (there are 2 unread notifications). | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | a5e724081ad84f88813bb4de23a8230e | The first line of input contains two integers n and q (1ββ€βn,βqββ€β300β000)Β β the number of applications and the number of events to happen. The next q lines contain the events. The i-th of these lines starts with an integer typeiΒ β type of the i-th event. If typeiβ=β1 or typeiβ=β2 then it is followed by an integer xi. Otherwise it is followed by an integer ti (1ββ€βtypeiββ€β3,β1ββ€βxiββ€βn,β1ββ€βtiββ€βq). | 1,600 | Print the number of unread notifications after each event. | standard output | |
PASSED | e86ebea211c28cfb66acec8feef96a41 | train_003.jsonl | 1470578700 | Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).q events are about to happen (in chronological order). They are of three types: Application x generates a notification (this new notification is unread). Thor reads all notifications generated so far by application x (he may re-read some notifications). Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation. Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone. | 256 megabytes | import java.io.*;
import java.util.*;
public class Testes {
static BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
static BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));
static class Notification {
boolean beenRead = false;
void read() {
this.beenRead = true;
}
}
public static void main(String[] args) throws IOException {
int n, q, x, type, t = 0, unread = 0;
ArrayList<Notification>[] apps;
ArrayList<Notification> notes;
notes = new ArrayList<>();
String nums = input.readLine();
StringTokenizer st = new StringTokenizer(nums);
n = Integer.parseInt(st.nextToken());
q = Integer.parseInt(st.nextToken());
apps = new ArrayList[n];
for (; q > 0; q--) {
nums = input.readLine();
st = new StringTokenizer(nums);
type = Integer.parseInt(st.nextToken());
x = Integer.parseInt(st.nextToken());
switch (type) {
case 1:
Notification note = new Notification();
if (apps[x-1] == null) {
apps[x-1] = new ArrayList<>();
}
apps[x-1].add(note);
notes.add(note);
unread++;
break;
case 2:
if (apps[x-1] == null) {
break;
}
for (Notification note2: apps[x-1]) {
if (!note2.beenRead) {
note2.read();
unread--;
}
}
apps[x-1].clear();
break;
case 3:
for (int i = t; i < x; i++) {
Notification note3 = notes.get(i);
if (!note3.beenRead) {
note3.read();
unread--;
}
}
t = Math.max(t, x);
break;
}
output.write(unread + "\n");
}
output.flush();
}
} | Java | ["3 4\n1 3\n1 1\n1 2\n2 3", "4 6\n1 2\n1 4\n1 2\n3 3\n1 3\n1 3"] | 2 seconds | ["1\n2\n3\n2", "1\n2\n3\n0\n1\n2"] | NoteIn the first sample: Application 3 generates a notification (there is 1 unread notification). Application 1 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads the notification generated by application 3, there are 2 unread notifications left. In the second sample test: Application 2 generates a notification (there is 1 unread notification). Application 4 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads first three notifications and since there are only three of them so far, there will be no unread notification left. Application 3 generates a notification (there is 1 unread notification). Application 3 generates a notification (there are 2 unread notifications). | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | a5e724081ad84f88813bb4de23a8230e | The first line of input contains two integers n and q (1ββ€βn,βqββ€β300β000)Β β the number of applications and the number of events to happen. The next q lines contain the events. The i-th of these lines starts with an integer typeiΒ β type of the i-th event. If typeiβ=β1 or typeiβ=β2 then it is followed by an integer xi. Otherwise it is followed by an integer ti (1ββ€βtypeiββ€β3,β1ββ€βxiββ€βn,β1ββ€βtiββ€βq). | 1,600 | Print the number of unread notifications after each event. | standard output | |
PASSED | dadf028674800b6b01c5be824901a935 | train_003.jsonl | 1470578700 | Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).q events are about to happen (in chronological order). They are of three types: Application x generates a notification (this new notification is unread). Thor reads all notifications generated so far by application x (he may re-read some notifications). Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation. Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone. | 256 megabytes | import java.util.*;
import java.io.*;
import java.lang.*;
import java.security.KeyStore.Entry;
public class Q2 {
static ArrayList<Integer> adj[];
static int color[],red[],black[],previs[];
static boolean b[],visited[],possible;
static Map<Long,Long> dict;
static int totalnodes,colored,time,v[],l[],r[];
//static int p[];
static HashMap<Integer,int[]> hm;//static
//static boolean[] isPrime=new boolean[N];
//static int[] Primefact=new int[N];
void solve(){
in=new InputReader(System.in);
w=new PrintWriter(System.out);
int n=in.nextInt();
int q=in.nextInt();
LinkedList<Pair> nb =new LinkedList<>();
LinkedList<Integer> app[]=new LinkedList[n+1];
for(int i=1;i<=n;i++)
{
app[i]=new LinkedList<>();
}
int total=1;
int unread=0;
boolean read[]=new boolean[300001];
while(q--!=0)
{
int type=in.nextInt();
if(type==1)
{
int x=in.nextInt();
app[x].add(total);
nb.add(new Pair(total,x));
total++;
unread++;
w.println(unread);
}
else if(type==2)
{
int x=in.nextInt();
unread=unread-app[x].size();
// for(int i:app[x])
// read[i]=true;
app[x].clear();
w.println(unread);
}
else
{
int t=in.nextInt();int i=0;
while( !nb.isEmpty() && nb.peek().i<=t )
{
Pair p=nb.poll();
if(!app[p.x].isEmpty() && app[p.x].peek()==p.i)
{
app[p.x].poll();
unread-=1;
}
}
w.println(unread);
}
}
w.close();
}
public static void main(String[] args) throws IOException{
new Q2().solve();
}
void seive(int N){
//isPrime = new boolean[(int) (n+1)];
}
int modularExponentiation(int x,int n,int M)
{
if(n==0)
return 1;
else if(n%2 == 0) //n is even
return modularExponentiation((x*x)%M,n/2,M);
else //n is odd
return (x*modularExponentiation((x*x)%M,(n-1)/2,M))%M;
}
/* void dfs(int u,int low,int high)
{
if(u==-1 || low>high)
return;
if(low<=v[u] && v[u]<=high){
hm.put(v[u],true);
}
dfs(l[u],low,high<v[u]-1?high:v[u]-1);
dfs(r[u],low>v[u]+1?low:v[u]+1,high);
}
int dfs_red(int i)
{
previs[i]=time++;
visited[i]=true;
if(color[i]==0)
red[i]++;
for(int j:adj[i])
{
if(!visited[j])
red[i]+=dfs_red(j);
}
return red[i];
}
int dfs_black(int i)
{
visited[i]=true;
if(color[i]==1)
black[i]++;
for(int j:adj[i])
{
if(!visited[j])
black[i]+=dfs_black(j);
}
return black[i];
}*/
public static class dsu
{
int n;
int parent[];
int s[];
dsu(int n)
{
this.n=n;
parent=new int[n+1];
s=new int[n+1];
for(int i=0;i<=n;i++)
{
parent[i]=i;
s[i]=1;
}
}
int find(int i)
{
if (parent[i] == i)
return i;
else
{
int result = find(parent[i]);
parent[i] = result;
return result;
}
}
}
static InputReader in;
static PrintWriter w;
public boolean oj = System.getProperty("ONLINE_JUDGE") != null;
public void tr(Object... o) {
if (!oj)
System.out.println(Arrays.deepToString(o));
}
public static long power(long a,long b,long c)
{
long ans = 1;
while(b!=0)
{
if(b%2==1)
{
ans = ans*a;
ans = ans % c;
}
a = a*a;
a = a%c;
b = b/2;
}
return ans;
}
static class Pair implements Comparable<Pair> {
int i,x,w;
public Pair(){
}
public Pair(int u,int v) {
this.i=u;
this.x=v;
this.w=Math.min(u, v);
}
public int compareTo(Pair other) {
return 0;
}
/*public String toString() {
return "[u=" + u + ", v=" + v + "]";
}*/
}
static class Node2{
Node2 left = null;
Node2 right = null;
Node2 parent = null;
int data;
}
//binaryStree
static class BinarySearchTree{
Node2 root = null;
int height = 0;
int max = 0;
int cnt = 1;
ArrayList<Integer> parent = new ArrayList<>();
HashMap<Integer, Integer> hm = new HashMap<>();
public void insert(int x){
Node2 n = new Node2();
n.data = x;
if(root==null){
root = n;
}
else{
Node2 temp = root,temp2 = null;
while(temp!=null){
temp2 = temp;
if(x>temp.data) temp = temp.right;
else temp = temp.left;
}
if(x>temp2.data) temp2.right = n;
else temp2.left = n;
n.parent = temp2;
parent.add(temp2.data);
}
}
public Node2 getSomething(int x, int y, Node2 n){
if(n.data==x || n.data==y) return n;
else if(n.data>x && n.data<y) return n;
else if(n.data<x && n.data<y) return getSomething(x,y,n.right);
else return getSomething(x,y,n.left);
}
public Node2 search(int x,Node2 n){
if(x==n.data){
max = Math.max(max, n.data);
return n;
}
if(x>n.data){
max = Math.max(max, n.data);
return search(x,n.right);
}
else{
max = Math.max(max, n.data);
return search(x,n.left);
}
}
public int getHeight(Node2 n){
if(n==null) return 0;
height = 1+ Math.max(getHeight(n.left), getHeight(n.right));
return height;
}
}
public static void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
public static String rev(String s)
{
StringBuilder sb=new StringBuilder(s);
sb.reverse();
return sb.toString();
}
static long lcm(long a, long b)
{
return a * (b / gcd(a, b));
}
static long gcd(long a, long b)
{
while (b > 0)
{
long temp = b;
b = a % b; // % is remainder
a = temp;
}
return a;
}
public static long max(long x, long y, long z){
if(x>=y && x>=z) return x;
if(y>=x && y>=z) return y;
return z;
}
static int[] sieve(int n,int[] arr)
{
for(int i=2;i*i<=n;i++)
{
if(arr[i]==0)
{
for(int j=i*2;j<=n;j+=i)
arr[j]=1;
}
}
return arr;
}
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) {
return nextIntArray(n, 0);
}
public int[] nextIntArray(int n, int off) {
int[] arr = new int[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
return nextLongArray(n, 0);
}
public long[] nextLongArray(int n, int off) {
long[] arr = new long[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextLong();
}
return arr;
}
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 | ["3 4\n1 3\n1 1\n1 2\n2 3", "4 6\n1 2\n1 4\n1 2\n3 3\n1 3\n1 3"] | 2 seconds | ["1\n2\n3\n2", "1\n2\n3\n0\n1\n2"] | NoteIn the first sample: Application 3 generates a notification (there is 1 unread notification). Application 1 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads the notification generated by application 3, there are 2 unread notifications left. In the second sample test: Application 2 generates a notification (there is 1 unread notification). Application 4 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads first three notifications and since there are only three of them so far, there will be no unread notification left. Application 3 generates a notification (there is 1 unread notification). Application 3 generates a notification (there are 2 unread notifications). | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | a5e724081ad84f88813bb4de23a8230e | The first line of input contains two integers n and q (1ββ€βn,βqββ€β300β000)Β β the number of applications and the number of events to happen. The next q lines contain the events. The i-th of these lines starts with an integer typeiΒ β type of the i-th event. If typeiβ=β1 or typeiβ=β2 then it is followed by an integer xi. Otherwise it is followed by an integer ti (1ββ€βtypeiββ€β3,β1ββ€βxiββ€βn,β1ββ€βtiββ€βq). | 1,600 | Print the number of unread notifications after each event. | standard output | |
PASSED | 2fbc0b9996d103e99b604a4329f2ee64 | train_003.jsonl | 1470578700 | Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).q events are about to happen (in chronological order). They are of three types: Application x generates a notification (this new notification is unread). Thor reads all notifications generated so far by application x (he may re-read some notifications). Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation. Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone. | 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 temp1 {
public static class MyScanner {
BufferedReader bf;
StringTokenizer st;
MyScanner() {
bf = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
if (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(bf.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
}
public static void main(String args[]) {
MyScanner in = new MyScanner();
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
int q = in.nextInt();
int summary = 0;
int index = 0;
Struct[] struct = new Struct[n];
for (int i = 0; i < n; i++) {
struct[i]=new Struct();
}
TreeSet<Integer> test = new TreeSet<Integer>();
for (int i = 0; i < q; i++) {
int operation = in.nextInt();
int number = in.nextInt();
if (operation == 1) {
number--;
summary++;
struct[number].unread++;
struct[number].ts.add(index);
test.add(index);
index++;
}else
if (operation == 2) {
number--;
struct[number].unread=0;
test.removeAll(struct[number].ts);
struct[number].ts.clear();
}else
if (operation == 3) {
while(test.lower(number) != null) test.pollFirst();
}
out.println(test.size());
}
out.close();
}
}
class Struct {
int unread;
TreeSet<Integer> ts;
public Struct() {
unread=0;
ts = new TreeSet<Integer>();
}
} | Java | ["3 4\n1 3\n1 1\n1 2\n2 3", "4 6\n1 2\n1 4\n1 2\n3 3\n1 3\n1 3"] | 2 seconds | ["1\n2\n3\n2", "1\n2\n3\n0\n1\n2"] | NoteIn the first sample: Application 3 generates a notification (there is 1 unread notification). Application 1 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads the notification generated by application 3, there are 2 unread notifications left. In the second sample test: Application 2 generates a notification (there is 1 unread notification). Application 4 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads first three notifications and since there are only three of them so far, there will be no unread notification left. Application 3 generates a notification (there is 1 unread notification). Application 3 generates a notification (there are 2 unread notifications). | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | a5e724081ad84f88813bb4de23a8230e | The first line of input contains two integers n and q (1ββ€βn,βqββ€β300β000)Β β the number of applications and the number of events to happen. The next q lines contain the events. The i-th of these lines starts with an integer typeiΒ β type of the i-th event. If typeiβ=β1 or typeiβ=β2 then it is followed by an integer xi. Otherwise it is followed by an integer ti (1ββ€βtypeiββ€β3,β1ββ€βxiββ€βn,β1ββ€βtiββ€βq). | 1,600 | Print the number of unread notifications after each event. | standard output | |
PASSED | f03bbef9719b4c1b9a999be873e88b41 | train_003.jsonl | 1470578700 | Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).q events are about to happen (in chronological order). They are of three types: Application x generates a notification (this new notification is unread). Thor reads all notifications generated so far by application x (he may re-read some notifications). Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation. Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone. | 256 megabytes | import java.io.File;
import java.util.LinkedList;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class p011 {
public static void main(String args[]) throws Exception {
StringTokenizer stok = new StringTokenizer(new Scanner(System.in).useDelimiter("\\A").next());
StringBuilder sb = new StringBuilder();
int n = Integer.parseInt(stok.nextToken());
int q = Integer.parseInt(stok.nextToken());
LinkedList<int[]> lst = new LinkedList<int[]>();
TreeSet<int[]> st = new TreeSet<int[]>(
(x,y)->x[0]==y[0]?Integer.compare(x[1], y[1]):Integer.compare(x[0], y[0]));
int ur = 0,msg=0;
for(int i=0;i<q;i++) {
int id = Integer.parseInt(stok.nextToken());
int x = Integer.parseInt(stok.nextToken());
if(id==1) {
ur++;msg++;
int[] a = new int[] {x,msg,0};
lst.addLast(a);
st.add(a);
sb.append(ur+"\n");
}
else if(id==2) {
int[] a = new int[] {x,-1,0};
int[] c = st.higher(a);
while(c!=null && c[0]==x) {
if(c[2]==0) {ur--;c[2]=1;}
st.remove(c);
c = st.higher(a);
}
sb.append(ur+"\n");
}
else {
while(!lst.isEmpty()) {
int[] a = lst.getFirst();
if(a[1]>x) break;
if(a[2]==0) {ur--;a[2]=1;}
lst.pollFirst();
}
sb.append(ur+"\n");
}
}
System.out.println(sb);
}
} | Java | ["3 4\n1 3\n1 1\n1 2\n2 3", "4 6\n1 2\n1 4\n1 2\n3 3\n1 3\n1 3"] | 2 seconds | ["1\n2\n3\n2", "1\n2\n3\n0\n1\n2"] | NoteIn the first sample: Application 3 generates a notification (there is 1 unread notification). Application 1 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads the notification generated by application 3, there are 2 unread notifications left. In the second sample test: Application 2 generates a notification (there is 1 unread notification). Application 4 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads first three notifications and since there are only three of them so far, there will be no unread notification left. Application 3 generates a notification (there is 1 unread notification). Application 3 generates a notification (there are 2 unread notifications). | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | a5e724081ad84f88813bb4de23a8230e | The first line of input contains two integers n and q (1ββ€βn,βqββ€β300β000)Β β the number of applications and the number of events to happen. The next q lines contain the events. The i-th of these lines starts with an integer typeiΒ β type of the i-th event. If typeiβ=β1 or typeiβ=β2 then it is followed by an integer xi. Otherwise it is followed by an integer ti (1ββ€βtypeiββ€β3,β1ββ€βxiββ€βn,β1ββ€βtiββ€βq). | 1,600 | Print the number of unread notifications after each event. | standard output | |
PASSED | 09dae359db294f07a708c8036c8cad07 | train_003.jsonl | 1470578700 | Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).q events are about to happen (in chronological order). They are of three types: Application x generates a notification (this new notification is unread). Thor reads all notifications generated so far by application x (he may re-read some notifications). Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation. Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone. | 256 megabytes | import java.util.*;
public class SlideWindow1 {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int q = sc.nextInt();
int mark[] = new int[q+1];
Queue<Integer>[] apps = new Queue[n];
StringBuilder sb = new StringBuilder();
for(int i=0; i<n; i++) {
apps[i] = new LinkedList<Integer>();
}
Queue<int[]> notif = new LinkedList();
int ans = 0;
int message = 1;
for(int i=0; i<q; i++) {
int t = sc.nextInt();
if(t == 1) {
int idx = sc.nextInt() - 1;
ans++;
apps[idx].add(message);
notif.add(new int[] {message++, idx});
}
if(t == 2) {
int idx = sc.nextInt() - 1;
ans -= apps[idx].size();
while(!apps[idx].isEmpty()) {
mark[apps[idx].poll()] = 1;
}
}
if(t == 3) {
int c = sc.nextInt();
while(!notif.isEmpty() && notif.peek()[0] <= c) {
int[] m = notif.poll();
if(mark[m[0]] == 0) {
// System.out.println("remove "+m[0]);
mark[m[0]] = 1;
ans--;
apps[m[1]].poll();
}
}
}
// System.out.println(ans);
sb.append(ans+"\n");
}
System.out.println(sb);
}
}
| Java | ["3 4\n1 3\n1 1\n1 2\n2 3", "4 6\n1 2\n1 4\n1 2\n3 3\n1 3\n1 3"] | 2 seconds | ["1\n2\n3\n2", "1\n2\n3\n0\n1\n2"] | NoteIn the first sample: Application 3 generates a notification (there is 1 unread notification). Application 1 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads the notification generated by application 3, there are 2 unread notifications left. In the second sample test: Application 2 generates a notification (there is 1 unread notification). Application 4 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads first three notifications and since there are only three of them so far, there will be no unread notification left. Application 3 generates a notification (there is 1 unread notification). Application 3 generates a notification (there are 2 unread notifications). | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | a5e724081ad84f88813bb4de23a8230e | The first line of input contains two integers n and q (1ββ€βn,βqββ€β300β000)Β β the number of applications and the number of events to happen. The next q lines contain the events. The i-th of these lines starts with an integer typeiΒ β type of the i-th event. If typeiβ=β1 or typeiβ=β2 then it is followed by an integer xi. Otherwise it is followed by an integer ti (1ββ€βtypeiββ€β3,β1ββ€βxiββ€βn,β1ββ€βtiββ€βq). | 1,600 | Print the number of unread notifications after each event. | standard output | |
PASSED | f5b54fbd1f21fb4a3da9f9f9336cb621 | train_003.jsonl | 1470578700 | Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).q events are about to happen (in chronological order). They are of three types: Application x generates a notification (this new notification is unread). Thor reads all notifications generated so far by application x (he may re-read some notifications). Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation. Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
static class IntegerPair {
Integer first;
Integer second;
IntegerPair(Integer f, Integer s) {
first = f;
second = s;
}
}
private static InputReader br = new InputReader(System.in);
private static PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
public static void main(String[] args) {
int n = br.nextInt();
int q = br.nextInt();
Queue<Integer> qu = new LinkedList<Integer>();
ArrayList<TreeSet<Integer>> set = new ArrayList<TreeSet<Integer>>();
for (int i = 0; i < n; i++) {
set.add(new TreeSet<Integer>());
}
int unread_notification = 0;
int total_notification = 0;
int noti = 1;
for (int i = 0; i < q; i++) {
int type = br.nextInt();
if (type == 1) {
int app = br.nextInt() - 1;
unread_notification++;
total_notification++;
set.get(app).add(total_notification);
qu.add(app);
}
else if (type == 2) {
int app = br.nextInt() - 1;
unread_notification -= set.get(app).size();
set.get(app).clear();
}
else {
int read_number = br.nextInt();
while (noti <= read_number) {
if (set.get(qu.peek()).contains(noti)) {
unread_notification--;
set.get(qu.peek()).remove(noti);
}
noti++;
qu.poll();
}
}
pr.println(unread_notification);
}
pr.close();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public String nextLine() {
String line;
try {
line = reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return line;
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
}
| Java | ["3 4\n1 3\n1 1\n1 2\n2 3", "4 6\n1 2\n1 4\n1 2\n3 3\n1 3\n1 3"] | 2 seconds | ["1\n2\n3\n2", "1\n2\n3\n0\n1\n2"] | NoteIn the first sample: Application 3 generates a notification (there is 1 unread notification). Application 1 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads the notification generated by application 3, there are 2 unread notifications left. In the second sample test: Application 2 generates a notification (there is 1 unread notification). Application 4 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads first three notifications and since there are only three of them so far, there will be no unread notification left. Application 3 generates a notification (there is 1 unread notification). Application 3 generates a notification (there are 2 unread notifications). | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | a5e724081ad84f88813bb4de23a8230e | The first line of input contains two integers n and q (1ββ€βn,βqββ€β300β000)Β β the number of applications and the number of events to happen. The next q lines contain the events. The i-th of these lines starts with an integer typeiΒ β type of the i-th event. If typeiβ=β1 or typeiβ=β2 then it is followed by an integer xi. Otherwise it is followed by an integer ti (1ββ€βtypeiββ€β3,β1ββ€βxiββ€βn,β1ββ€βtiββ€βq). | 1,600 | Print the number of unread notifications after each event. | standard output | |
PASSED | 0ddb301c7fa6a7fbaa8d1410c9fc4487 | train_003.jsonl | 1470578700 | Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).q events are about to happen (in chronological order). They are of three types: Application x generates a notification (this new notification is unread). Thor reads all notifications generated so far by application x (he may re-read some notifications). Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation. Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone. | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
import java.util.stream.*;
@SuppressWarnings("unchecked")
public class P704A {
class Event {
int idx, x;
Event prev, next, prevX, nextX;
public Event(int idx, int x) {
this.idx = idx;
this.x = x;
}
}
//----------------------------------------------------------
class EventQueue {
Event first, last;
Event [] firstX, lastX;
int size;
public EventQueue(int events) {
firstX = new Event [events];
lastX = new Event [events];
}
public void add(int idx, int x) {
Event e = new Event(idx, x);
e.prev = last;
if (last != null) {
last.next = e;
}
last = e;
if (first == null) {
first = e;
}
e.prevX = lastX[x];
if (lastX[x] != null) {
lastX[x].nextX = e;
}
lastX[x] = e;
if (firstX[x] == null) {
firstX[x] = e;
}
size++;
}
public Event remove(Event e) {
int x = e.x;
if (first == e) {
first = e.next;
}
if (last == e) {
last = e.prev;
}
if (firstX[x] == e) {
firstX[x] = e.nextX;
}
if (lastX[x] == e) {
lastX[x] = e.prevX;
}
if (e.prev != null) {
e.prev.next = e.next;
}
if (e.next != null) {
e.next.prev = e.prev;
}
if (e.prevX != null) {
e.prevX.nextX = e.nextX;
}
if (e.nextX != null) {
e.nextX.prevX = e.prevX;
}
size--;
return e;
}
public void removeX(int x) {
for (Event e = firstX[x]; e != null; e = remove(e).nextX);
}
public void removeT(int idx) {
for (Event e = first; (e != null) && (e.idx <= idx); e = remove(e).next);
}
@Override
public String toString() {
return Integer.toString(size);
}
}
//----------------------------------------------------------
public void run() throws Exception {
EventQueue eq = new EventQueue(nextInt());
for (int mi = 1, q = nextInt(); q > 0; q--) {
switch (nextInt()) {
case 1 :
eq.add(mi++, nextInt() - 1);
break;
case 2 :
eq.removeX(nextInt() - 1);
break;
default : // case 3
eq.removeT(nextInt());
}
println(eq);
}
}
public static void main(String... args) throws Exception {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedOutputStream(System.out));
new P704A().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);
}
} | Java | ["3 4\n1 3\n1 1\n1 2\n2 3", "4 6\n1 2\n1 4\n1 2\n3 3\n1 3\n1 3"] | 2 seconds | ["1\n2\n3\n2", "1\n2\n3\n0\n1\n2"] | NoteIn the first sample: Application 3 generates a notification (there is 1 unread notification). Application 1 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads the notification generated by application 3, there are 2 unread notifications left. In the second sample test: Application 2 generates a notification (there is 1 unread notification). Application 4 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads first three notifications and since there are only three of them so far, there will be no unread notification left. Application 3 generates a notification (there is 1 unread notification). Application 3 generates a notification (there are 2 unread notifications). | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | a5e724081ad84f88813bb4de23a8230e | The first line of input contains two integers n and q (1ββ€βn,βqββ€β300β000)Β β the number of applications and the number of events to happen. The next q lines contain the events. The i-th of these lines starts with an integer typeiΒ β type of the i-th event. If typeiβ=β1 or typeiβ=β2 then it is followed by an integer xi. Otherwise it is followed by an integer ti (1ββ€βtypeiββ€β3,β1ββ€βxiββ€βn,β1ββ€βtiββ€βq). | 1,600 | Print the number of unread notifications after each event. | standard output | |
PASSED | 8e70096f951ca2c81987ad07ecbf4f3b | train_003.jsonl | 1470578700 | Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).q events are about to happen (in chronological order). They are of three types: Application x generates a notification (this new notification is unread). Thor reads all notifications generated so far by application x (he may re-read some notifications). Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation. Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone. | 256 megabytes | import org.omg.PortableInterceptor.INACTIVE;
import java.io.*;
import java.util.*;
public class Solution{
class LazyPropSegmentTree {
int[] tree, lazy, orig;
int len;
LazyPropSegmentTree(int n) {
len = n * 33;
tree = new int[len];
lazy = new int[len];
}
/**
* Build and init tree
*/
void build_tree(int node, int a, int b) {
if (a > b) return;
if (a == b) {
tree[node] = orig[a];
return;
}
build_tree(node * 2, a, (a + b) / 2); // Init left child
build_tree(node * 2 + 1, 1 + (a + b) / 2, b); // Init right child
tree[node] = tree[node * 2] + tree[node * 2 + 1]; // Init root value
}
/**
* Increment elements within range [i, j] with value value
*/
void update_tree(int node, int a, int b, int i, int j, int value) {
if (lazy[node] != 0) { // This node needs to be updated
tree[node] += lazy[node]; // Update it
if (a != b) {
lazy[node * 2] += lazy[node]; // Mark child as lazy
lazy[node * 2 + 1] += lazy[node]; // Mark child as lazy
}
lazy[node] = 0; // Reset it
}
if (a > b || a > j || b < i) // Current segment is not within range [i, j]
return;
if (a >= i && b <= j) { // Segment is fully within range
tree[node] += value;
if (a != b) { // Not leaf node
lazy[node * 2] += value;
lazy[node * 2 + 1] += value;
}
return;
}
update_tree(node * 2, a, (a + b) / 2, i, j, value); // Updating left child
update_tree(1 + node * 2, 1 + (a + b) / 2, b, i, j, value); // Updating right child
tree[node] = tree[node * 2] + tree[node * 2 + 1]; // Updating root with max value
}
/**
* Query tree to get max element value within range [i, j]
*/
int query_tree(int node, int a, int b, int i, int j) {
if (a > b || a > j || b < i) return 0; // Out of range
if (lazy[node] != 0) { // This node needs to be updated
tree[node] += lazy[node]; // Update it
if (a != b) {
lazy[node * 2] += lazy[node]; // Mark child as lazy
lazy[node * 2 + 1] += lazy[node]; // Mark child as lazy
}
lazy[node] = 0; // Reset it
}
if (a >= i && b <= j) // Current segment is totally within range [i, j]
return tree[node];
int q1 = query_tree(node * 2, a, (a + b) / 2, i, j); // Query left child
int q2 = query_tree(1 + node * 2, 1 + (a + b) / 2, b, i, j); // Query right child
int res = q1+q2; // Return final result
return res;
}
}
private class Apps {
LinkedList<Integer> turn = new LinkedList<>();
}
Kattio io = new Kattio(System.in, System.out);
int n, q, lastRead = 0, insertCounter = 1;
Apps[] apps;
int[] inserts;
LazyPropSegmentTree segTree;
Solution() {
n = io.getInt(); q = io.getInt();
apps = new Apps[n+1];
inserts = new int[q+1];
segTree = new LazyPropSegmentTree(n);
for(int i=1; i<=n; i++) {
apps[i] = new Apps();
}
segTree = new LazyPropSegmentTree(n);
for(int i=0; i<q; i++){
int op = io.getInt();
int val = io.getInt();
//inserting a new message
if(op == 1){
segTree.update_tree(1,1,n,val,val,1);
inserts[insertCounter] = val;
apps[val].turn.addLast(insertCounter);
insertCounter++;
}
//read all messages from a given cell
else if(op == 2){
int counter = apps[val].turn.size();
segTree.update_tree(1,1,n,val, val, -counter);
apps[val].turn.clear();
}
//read or reread the first k messages
else{
//if we are expanding first k read, iterate up to k, and remove
//the messages not yet removed by operation 2.
if(val > lastRead){
for(int j=lastRead+1; j<=val; j++){
int appId = inserts[j];
//remove the message from front of local list if it exists
if(!apps[appId].turn.isEmpty() && apps[appId].turn.peekFirst() == j){
segTree.update_tree(1,1,n,appId,appId,-1);
apps[appId].turn.pollFirst();
}
lastRead++;
}
}
}
io.println(segTree.query_tree(1,1,n,1,n));
}
io.close();
}
public static void main(String[] args) {
new Solution();
}
}
/**
* Simple yet moderately fast I/O routines.
* <p>
* Example usage:
* <p>
* Kattio io = new Kattio(System.in, System.out);
* <p>
* while (io.hasMoreTokens()) {
* int n = io.getInt();
* double d = io.getDouble();
* double ans = d*n;
* <p>
* io.println("Answer: " + ans);
* }
* <p>
* io.close();
* <p>
* <p>
* Some notes:
* <p>
* - When done, you should always do io.close() or io.flush() on the
* Kattio-instance, otherwise, you may lose output.
* <p>
* - The getInt(), getDouble(), and getLong() methods will throw an
* exception if there is no more data in the input, so it is generally
* a good idea to use hasMoreTokens() to check for end-of-file.
*
* @author: Kattis
*/
class Kattio extends PrintWriter {
public Kattio(InputStream i) {
super(new BufferedOutputStream(System.out));
r = new BufferedReader(new InputStreamReader(i));
}
public Kattio(InputStream i, OutputStream o) {
super(new BufferedOutputStream(o));
r = new BufferedReader(new InputStreamReader(i));
}
public boolean hasMoreTokens() {
return peekToken() != null;
}
public int getInt() {
return Integer.parseInt(nextToken());
}
public double getDouble() {
return Double.parseDouble(nextToken());
}
public long getLong() {
return Long.parseLong(nextToken());
}
public String getWord() {
return nextToken();
}
public String getLine() {
try {
return r.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private BufferedReader r;
private String line;
private StringTokenizer st;
private String token;
private String peekToken() {
if (token == null)
try {
while (st == null || !st.hasMoreTokens()) {
line = r.readLine();
if (line == null) return null;
st = new StringTokenizer(line);
}
token = st.nextToken();
} catch (IOException e) {
e.printStackTrace();
}
return token;
}
private String nextToken() {
String ans = peekToken();
token = null;
return ans;
}
} | Java | ["3 4\n1 3\n1 1\n1 2\n2 3", "4 6\n1 2\n1 4\n1 2\n3 3\n1 3\n1 3"] | 2 seconds | ["1\n2\n3\n2", "1\n2\n3\n0\n1\n2"] | NoteIn the first sample: Application 3 generates a notification (there is 1 unread notification). Application 1 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads the notification generated by application 3, there are 2 unread notifications left. In the second sample test: Application 2 generates a notification (there is 1 unread notification). Application 4 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads first three notifications and since there are only three of them so far, there will be no unread notification left. Application 3 generates a notification (there is 1 unread notification). Application 3 generates a notification (there are 2 unread notifications). | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | a5e724081ad84f88813bb4de23a8230e | The first line of input contains two integers n and q (1ββ€βn,βqββ€β300β000)Β β the number of applications and the number of events to happen. The next q lines contain the events. The i-th of these lines starts with an integer typeiΒ β type of the i-th event. If typeiβ=β1 or typeiβ=β2 then it is followed by an integer xi. Otherwise it is followed by an integer ti (1ββ€βtypeiββ€β3,β1ββ€βxiββ€βn,β1ββ€βtiββ€βq). | 1,600 | Print the number of unread notifications after each event. | standard output | |
PASSED | bf1f1496d20906fed4bc4f983bf2b51a | train_003.jsonl | 1470578700 | Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).q events are about to happen (in chronological order). They are of three types: Application x generates a notification (this new notification is unread). Thor reads all notifications generated so far by application x (he may re-read some notifications). Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation. Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone. | 256 megabytes | import java.util.*;
import java.io.*;
public class A
{
public static void main(String ar[]) throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s1[]=br.readLine().split(" ");
int n=Integer.parseInt(s1[0]);
int m=Integer.parseInt(s1[1]);
Queue<B> q=new LinkedList<B>();
TreeSet<Integer> ts[]=new TreeSet[n+1];
for(int i=1;i<=n;i++)
ts[i]=new TreeSet<Integer>();
int r=1;
int t=0;
boolean b[]=new boolean[m+1];
StringBuffer sb=new StringBuffer();
for(int i=0;i<m;i++)
{
String s2[]=br.readLine().split(" ");
int u=Integer.parseInt(s2[0]);
int v=Integer.parseInt(s2[1]);
if(u==1)
{
ts[v].add(r);
q.add(new B(r,v));
r++;
t++;
}
else if(u==2)
{
while(!ts[v].isEmpty())
{
int p=ts[v].pollFirst();
b[p]=true;
t--;
}
}
else
{
while(!q.isEmpty() && q.peek().num<=v)
{
B b1=q.poll();
if(!b[b1.num])
{
ts[b1.ind].remove(b1.num);
t--;
}
}
}
sb.append(t).append("\n");
}
System.out.println(sb);
}
}
class B
{
int num=0,ind=0;
public B(int n,int i)
{
num=n;
ind=i;
}
} | Java | ["3 4\n1 3\n1 1\n1 2\n2 3", "4 6\n1 2\n1 4\n1 2\n3 3\n1 3\n1 3"] | 2 seconds | ["1\n2\n3\n2", "1\n2\n3\n0\n1\n2"] | NoteIn the first sample: Application 3 generates a notification (there is 1 unread notification). Application 1 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads the notification generated by application 3, there are 2 unread notifications left. In the second sample test: Application 2 generates a notification (there is 1 unread notification). Application 4 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads first three notifications and since there are only three of them so far, there will be no unread notification left. Application 3 generates a notification (there is 1 unread notification). Application 3 generates a notification (there are 2 unread notifications). | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | a5e724081ad84f88813bb4de23a8230e | The first line of input contains two integers n and q (1ββ€βn,βqββ€β300β000)Β β the number of applications and the number of events to happen. The next q lines contain the events. The i-th of these lines starts with an integer typeiΒ β type of the i-th event. If typeiβ=β1 or typeiβ=β2 then it is followed by an integer xi. Otherwise it is followed by an integer ti (1ββ€βtypeiββ€β3,β1ββ€βxiββ€βn,β1ββ€βtiββ€βq). | 1,600 | Print the number of unread notifications after each event. | standard output | |
PASSED | 7088dbe9ff594ed187784fa48f681ad5 | train_003.jsonl | 1470578700 | Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).q events are about to happen (in chronological order). They are of three types: Application x generates a notification (this new notification is unread). Thor reads all notifications generated so far by application x (he may re-read some notifications). Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation. Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone. | 256 megabytes | import java.util.*;
import java.io.*;
public class A
{
public static void main(String ar[]) throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s1[]=br.readLine().split(" ");
int n=Integer.parseInt(s1[0]);
int t=Integer.parseInt(s1[1]);
Queue<Integer> q[]=new Queue[n+1];
for(int i=1;i<=n;i++)
q[i]=new LinkedList<Integer>();
Queue<B> Q=new LinkedList<B>();
int ans=0;
int r=1;
boolean mark[]=new boolean[t+1];
Arrays.fill(mark,false);
StringBuffer sb=new StringBuffer();
for(int i=0;i<t;i++)
{
String s2[]=br.readLine().split(" ");
int u=Integer.parseInt(s2[0]);
int v=Integer.parseInt(s2[1]);
if(u==1)
{
q[v].add(r);
Q.add(new B(v,r));
r++;
ans++;
}
else if(u==2)
{
while(!q[v].isEmpty())
{
int x=q[v].poll();
mark[x]=true;
ans--;
}
}
else
{
//System.out.println(Q.peek().ind+" "+v);
while(!Q.isEmpty() && Q.peek().ind<=v)
{
B b1=Q.poll();
int x=b1.pos;
int y=b1.ind;
//System.out.println(x+" "+y);
if(!mark[y])
{
mark[y]=true;
q[x].poll();
ans--;
}
}
}
sb.append(ans).append("\n");
}
System.out.println(sb);
}
}
class B
{
int ind=0,pos=0;
public B(int x,int y)
{
ind=y; pos=x;
}
} | Java | ["3 4\n1 3\n1 1\n1 2\n2 3", "4 6\n1 2\n1 4\n1 2\n3 3\n1 3\n1 3"] | 2 seconds | ["1\n2\n3\n2", "1\n2\n3\n0\n1\n2"] | NoteIn the first sample: Application 3 generates a notification (there is 1 unread notification). Application 1 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads the notification generated by application 3, there are 2 unread notifications left. In the second sample test: Application 2 generates a notification (there is 1 unread notification). Application 4 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads first three notifications and since there are only three of them so far, there will be no unread notification left. Application 3 generates a notification (there is 1 unread notification). Application 3 generates a notification (there are 2 unread notifications). | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | a5e724081ad84f88813bb4de23a8230e | The first line of input contains two integers n and q (1ββ€βn,βqββ€β300β000)Β β the number of applications and the number of events to happen. The next q lines contain the events. The i-th of these lines starts with an integer typeiΒ β type of the i-th event. If typeiβ=β1 or typeiβ=β2 then it is followed by an integer xi. Otherwise it is followed by an integer ti (1ββ€βtypeiββ€β3,β1ββ€βxiββ€βn,β1ββ€βtiββ€βq). | 1,600 | Print the number of unread notifications after each event. | standard output | |
PASSED | f1e7dbf7599670ee4841132ecafee644 | train_003.jsonl | 1470578700 | Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).q events are about to happen (in chronological order). They are of three types: Application x generates a notification (this new notification is unread). Thor reads all notifications generated so far by application x (he may re-read some notifications). Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation. Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone. | 256 megabytes | /** https://codeforces.com/problemset/problem/704/A
* idea: just use queue
*/
import java.util.Deque;
import java.util.LinkedList;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.InputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.*;
public class Thor {
public static void main(String[] args) throws Exception {
MyScanner sc = new MyScanner(System.in);
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
int n = sc.nextInt();
int q = sc.nextInt();
int[] addedArr = new int[n+1];
int[] minusArr = new int[n+1];
int[] readArr = new int[n+1];
int prev_read = 0;
Deque<Node> qu = new LinkedList<>();
int tmp;
int type;
int val;
Node node;
int prev_nodeVal = 0;
int allNotifications = 0;
int unreadNotifications = 0;
int read = 0;
for (int i=0; i < q; i++) {
type = sc.nextInt();
tmp = sc.nextInt();
if (1 == type) {
addedArr[tmp] += 1;
if (qu.isEmpty() || prev_nodeVal != tmp) {
prev_nodeVal = tmp;
node = new Node(tmp, 1);
qu.addLast(node);
} else {
node = qu.peekLast();
node.repeated += 1;
}
allNotifications += 1;
unreadNotifications += 1;
} else if (2 == type) {
unreadNotifications -= addedArr[tmp] - minusArr[tmp];
minusArr[tmp] = addedArr[tmp];
} else {
int times = Math.min(tmp, allNotifications) - prev_read;
prev_read = Math.max(prev_read, Math.min(tmp, allNotifications));
while (!qu.isEmpty() && times > 0) {
node = qu.peekFirst();
val = node.val;
if (node.repeated <= times) {
read = node.repeated;
qu.pollFirst();
} else {
node.repeated -= times;
read = times;
}
readArr[val] += read;
if (readArr[val] > minusArr[val]) {
unreadNotifications -= readArr[val] - minusArr[val];
minusArr[val] = readArr[val];
}
times -= read;
}
}
//pw.println(unreadNotifications);
out.write(String.format("%d\n", unreadNotifications));
//System.out.println(unreadNotifications);
}
out.flush();
}
}
class Node {
int val, repeated;
Node (int val, int repeated) {
this.val = val;
this.repeated = repeated;
}
}
class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
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 4\n1 3\n1 1\n1 2\n2 3", "4 6\n1 2\n1 4\n1 2\n3 3\n1 3\n1 3"] | 2 seconds | ["1\n2\n3\n2", "1\n2\n3\n0\n1\n2"] | NoteIn the first sample: Application 3 generates a notification (there is 1 unread notification). Application 1 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads the notification generated by application 3, there are 2 unread notifications left. In the second sample test: Application 2 generates a notification (there is 1 unread notification). Application 4 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads first three notifications and since there are only three of them so far, there will be no unread notification left. Application 3 generates a notification (there is 1 unread notification). Application 3 generates a notification (there are 2 unread notifications). | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | a5e724081ad84f88813bb4de23a8230e | The first line of input contains two integers n and q (1ββ€βn,βqββ€β300β000)Β β the number of applications and the number of events to happen. The next q lines contain the events. The i-th of these lines starts with an integer typeiΒ β type of the i-th event. If typeiβ=β1 or typeiβ=β2 then it is followed by an integer xi. Otherwise it is followed by an integer ti (1ββ€βtypeiββ€β3,β1ββ€βxiββ€βn,β1ββ€βtiββ€βq). | 1,600 | Print the number of unread notifications after each event. | standard output | |
PASSED | 4969bf0fea67349d37ac5001f59b2ab5 | train_003.jsonl | 1470578700 | Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).q events are about to happen (in chronological order). They are of three types: Application x generates a notification (this new notification is unread). Thor reads all notifications generated so far by application x (he may re-read some notifications). Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation. Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone. | 256 megabytes | import java.io.*;
import java.util.*;
import java.util.function.*;
public class Main{
int N;
int Q;
HashMap<Integer, ArrayDeque<Integer>> count;
public void solve(){
N = nextInt();
Q = nextInt();
count = new HashMap<>();
int[] note = new int[Q];
int ni = 0;
int max = 0;
int ans = 0;
for(int i = 0; i < Q; i++){
int t = nextInt();
int x = nextInt();
if(t == 1){
note[ni] = x;
ni++;
get(x).addLast(ni);
ans++;
}else if(t == 2){
Queue<Integer> c = get(x);
ans -= c.size();
count.remove(x);
}else if(t == 3){
for(int j = max; j < x; j++){
ArrayDeque<Integer> qq = get(note[j]);
if(!qq.isEmpty() && qq.getFirst() == j + 1){
ans -= 1;
qq.removeFirst();
}
if(qq.isEmpty()){
count.remove(note[j]);
}
}
max = Math.max(max, x);
}
out.println(ans);
}
}
/*
public void add(int idx){
if(count.containsKey(idx)){
count.put(idx, count.get(idx) + 1);
}else{
count.put(idx, 1);
}
}
*/
public ArrayDeque<Integer> get(int idx){
ArrayDeque<Integer> v = count.get(idx);
if(v == null){
v = new ArrayDeque<Integer>();
count.put(idx, v);
return v;
}
else return v;
}
private static PrintWriter out;
public static void main(String[] args){
out = new PrintWriter(System.out);
new Main().solve();
out.flush();
}
public static int nextInt(){
int num = 0;
String str = next();
boolean minus = false;
int i = 0;
if(str.charAt(0) == '-'){
minus = true;
i++;
}
int len = str.length();
for(;i < len; i++){
char c = str.charAt(i);
if(!('0' <= c && c <= '9')) throw new RuntimeException();
num = num * 10 + (c - '0');
}
return minus ? -num : num;
}
public static long nextLong(){
long num = 0;
String str = next();
boolean minus = false;
int i = 0;
if(str.charAt(0) == '-'){
minus = true;
i++;
}
int len = str.length();
for(;i < len; i++){
char c = str.charAt(i);
if(!('0' <= c && c <= '9')) throw new RuntimeException();
num = num * 10l + (c - '0');
}
return minus ? -num : num;
}
public static String next(){
int c;
while(!isAlNum(c = read())){}
StringBuilder build = new StringBuilder();
build.append((char)c);
while(isAlNum(c = read())){
build.append((char)c);
}
return build.toString();
}
private static byte[] inputBuffer = new byte[1024];
private static int bufferLength = 0;
private static int bufferIndex = 0;
private static int read(){
if(bufferLength < 0) throw new RuntimeException();
if(bufferIndex >= bufferLength){
try{
bufferLength = System.in.read(inputBuffer);
bufferIndex = 0;
}catch(IOException e){
throw new RuntimeException(e);
}
if(bufferLength <= 0) return (bufferLength = -1);
}
return inputBuffer[bufferIndex++];
}
private static boolean isAlNum(int c){
return '!' <= c && c <= '~';
}
} | Java | ["3 4\n1 3\n1 1\n1 2\n2 3", "4 6\n1 2\n1 4\n1 2\n3 3\n1 3\n1 3"] | 2 seconds | ["1\n2\n3\n2", "1\n2\n3\n0\n1\n2"] | NoteIn the first sample: Application 3 generates a notification (there is 1 unread notification). Application 1 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads the notification generated by application 3, there are 2 unread notifications left. In the second sample test: Application 2 generates a notification (there is 1 unread notification). Application 4 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads first three notifications and since there are only three of them so far, there will be no unread notification left. Application 3 generates a notification (there is 1 unread notification). Application 3 generates a notification (there are 2 unread notifications). | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | a5e724081ad84f88813bb4de23a8230e | The first line of input contains two integers n and q (1ββ€βn,βqββ€β300β000)Β β the number of applications and the number of events to happen. The next q lines contain the events. The i-th of these lines starts with an integer typeiΒ β type of the i-th event. If typeiβ=β1 or typeiβ=β2 then it is followed by an integer xi. Otherwise it is followed by an integer ti (1ββ€βtypeiββ€β3,β1ββ€βxiββ€βn,β1ββ€βtiββ€βq). | 1,600 | Print the number of unread notifications after each event. | standard output | |
PASSED | 50774d8fde3649fd86416d4540ef0614 | train_003.jsonl | 1470578700 | Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).q events are about to happen (in chronological order). They are of three types: Application x generates a notification (this new notification is unread). Thor reads all notifications generated so far by application x (he may re-read some notifications). Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation. Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Rene
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int queries = in.nextInt();
SegmentTree tree = new SegmentTree(n);
ArrayList<Integer> notifications = new ArrayList<>();
int[] alreadyRead = new int[n];
int lastAll = 0;
for (int i = 0; i < queries; i++) {
int type = in.nextInt();
int x = in.nextInt();
if (type <= 2) x--;
if (type == 1) {
tree.change(x, tree.get(x) + 1);
notifications.add(x);
} else if (type == 2) {
tree.change(x, 0);
alreadyRead[x] = notifications.size();
} else {
for (int j = lastAll; j < x; j++) {
int z = notifications.get(j);
if (j >= alreadyRead[z]) {
tree.change(z, tree.get(z) - 1);
}
}
lastAll = Math.max(lastAll, x);
}
int result = tree.query(0, n);
out.println(result);
}
}
public class SegmentTree {
private int[] x;
private int n;
public SegmentTree(int cap) {
n = cap;
x = new int[2 * n];
}
public SegmentTree(int[] a) {
n = a.length;
x = new int[2 * n];
System.arraycopy(a, 0, x, n, n);
for (int i = n - 1; i > 0; i--) x[i] = x[2 * i] + x[2 * i + 1];
}
public void change(int k, int v) {
k += n;
x[k] = v;
for (; k > 1; k >>= 1) x[k >> 1] = x[k] + x[k ^ 1];
}
public int query(int l, int r) {
int result = 0;
for (l += n, r += n; l < r; l >>= 1, r >>= 1) {
if (l % 2 == 1) result += x[l++];
if (r % 2 == 1) result += x[--r];
}
return result;
}
public int get(int k) {
return x[n + k];
}
}
}
static class InputReader {
public InputStream stream;
private int current;
private int size;
private byte[] buffer = new byte[10000];
public InputReader(InputStream stream) {
this.stream = stream;
current = 0;
size = 0;
}
int read() {
int result;
try {
if (current >= size) {
current = 0;
size = stream.read(buffer);
if (size < 0) return -1;
}
} catch (IOException e) {
throw new RuntimeException();
}
return buffer[current++];
}
public int nextInt() {
int sign = 1;
int result = 0;
int c = readNextValid();
if (c == '-') {
sign = -1;
c = read();
}
do {
if (c < '0' || c > '9') throw new RuntimeException();
result = 10 * result + c - '0';
c = read();
} while (!isEmpty(c));
result *= sign;
return result;
}
private int readNextValid() {
int result;
do {
result = read();
} while (isEmpty(result));
return result;
}
private boolean isEmpty(int c) {
return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == -1;
}
}
}
| Java | ["3 4\n1 3\n1 1\n1 2\n2 3", "4 6\n1 2\n1 4\n1 2\n3 3\n1 3\n1 3"] | 2 seconds | ["1\n2\n3\n2", "1\n2\n3\n0\n1\n2"] | NoteIn the first sample: Application 3 generates a notification (there is 1 unread notification). Application 1 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads the notification generated by application 3, there are 2 unread notifications left. In the second sample test: Application 2 generates a notification (there is 1 unread notification). Application 4 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads first three notifications and since there are only three of them so far, there will be no unread notification left. Application 3 generates a notification (there is 1 unread notification). Application 3 generates a notification (there are 2 unread notifications). | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | a5e724081ad84f88813bb4de23a8230e | The first line of input contains two integers n and q (1ββ€βn,βqββ€β300β000)Β β the number of applications and the number of events to happen. The next q lines contain the events. The i-th of these lines starts with an integer typeiΒ β type of the i-th event. If typeiβ=β1 or typeiβ=β2 then it is followed by an integer xi. Otherwise it is followed by an integer ti (1ββ€βtypeiββ€β3,β1ββ€βxiββ€βn,β1ββ€βtiββ€βq). | 1,600 | Print the number of unread notifications after each event. | standard output | |
PASSED | e5f586c26ddcddbf21346609d74a2288 | train_003.jsonl | 1470578700 | Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).q events are about to happen (in chronological order). They are of three types: Application x generates a notification (this new notification is unread). Thor reads all notifications generated so far by application x (he may re-read some notifications). Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation. Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone. | 256 megabytes |
import java.util.*;
import java.io.*;
@SuppressWarnings("unchecked")
public class CF_A {
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st;
static void newST() throws IOException {st = new StringTokenizer(in.readLine());}
static int stInt() {return Integer.parseInt(st.nextToken());}
static long stLong() {return Long.parseLong(st.nextToken());}
static String stStr() {return st.nextToken();}
static int[] getInts(int n) throws IOException {newST(); int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = stInt(); return arr;}
static int readInt() throws IOException {return Integer.parseInt(in.readLine());}
static long readLong() throws IOException {return Long.parseLong(in.readLine());}
static void println(Object o) {System.out.println(o);}
static void println() {System.out.println();}
static void print(Object o) {System.out.print(o);}
static void printarr(int[] a) {StringBuilder sb = new StringBuilder(); for (int i = 0; i < a.length; i++)sb.append(a[i] + (i == a.length-1 ? "\n":" "));print(sb);}
public static void main(String[] args) throws Exception {
newST();
int n = stInt()+2, q = stInt();
boolean[] red = new boolean[q];
int[] ntl = new int[q];
ArrayList<Integer>[] adat = new ArrayList[n];
for (int i = 0; i < n; i++) adat[i] = new ArrayList<Integer>();
int[] acur = new int[n];
int cur = 0;
int len = 0;
int unr = 0;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < q; i++) {
newST();
int cmd = stInt();
if (cmd == 1) {
int app = stInt();
ntl[len] = app;
adat[app].add(len);
len++;
unr++;
}
else if (cmd == 2) {
int app = stInt();
for (int j = acur[app]; j < adat[app].size(); j++) {
if (!red[adat[app].get(j)]) {
unr--;
red[adat[app].get(j)] = true;
}
acur[app] = adat[app].size();
}
}
else {
int num = stInt();
for (int j = cur; j < num; j++) {
if (!red[j]) {
unr--;
red[j] = true;
}
cur = Math.max(cur, num);
}
}
sb.append(unr+"\n");
}
System.out.println(sb);
}
}
| Java | ["3 4\n1 3\n1 1\n1 2\n2 3", "4 6\n1 2\n1 4\n1 2\n3 3\n1 3\n1 3"] | 2 seconds | ["1\n2\n3\n2", "1\n2\n3\n0\n1\n2"] | NoteIn the first sample: Application 3 generates a notification (there is 1 unread notification). Application 1 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads the notification generated by application 3, there are 2 unread notifications left. In the second sample test: Application 2 generates a notification (there is 1 unread notification). Application 4 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads first three notifications and since there are only three of them so far, there will be no unread notification left. Application 3 generates a notification (there is 1 unread notification). Application 3 generates a notification (there are 2 unread notifications). | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | a5e724081ad84f88813bb4de23a8230e | The first line of input contains two integers n and q (1ββ€βn,βqββ€β300β000)Β β the number of applications and the number of events to happen. The next q lines contain the events. The i-th of these lines starts with an integer typeiΒ β type of the i-th event. If typeiβ=β1 or typeiβ=β2 then it is followed by an integer xi. Otherwise it is followed by an integer ti (1ββ€βtypeiββ€β3,β1ββ€βxiββ€βn,β1ββ€βtiββ€βq). | 1,600 | Print the number of unread notifications after each event. | standard output | |
PASSED | f9f168045006bd6737055e5f09daa87d | train_003.jsonl | 1470578700 | Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).q events are about to happen (in chronological order). They are of three types: Application x generates a notification (this new notification is unread). Thor reads all notifications generated so far by application x (he may re-read some notifications). Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation. Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author ilyakor
*/
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);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int q = in.nextInt();
int[] a = new int[q + n + 10];
ArrayList<Integer>[] g = new ArrayList[n];
int[] seen = new int[n];
for (int i = 0; i < n; ++i)
g[i] = new ArrayList<>();
int s = 0;
int val = 0;
int P = 0;
for (int it = 0; it < q; ++it) {
int ty = in.nextInt();
if (ty == 1) {
int x = in.nextInt() - 1;
g[x].add(s);
a[s] = 1;
++s;
++val;
} else if (ty == 2) {
int x = in.nextInt() - 1;
while (seen[x] < g[x].size()) {
int t = g[x].get(seen[x]);
val -= a[t];
a[t] = 0;
++seen[x];
}
} else if (ty == 3) {
int p = in.nextInt();
while (P < p) {
val -= a[P];
a[P] = 0;
++P;
}
}
out.printLine(val);
}
}
}
static class InputReader {
private InputStream stream;
private byte[] buffer = new byte[10000];
private int cur;
private int count;
public InputReader(InputStream stream) {
this.stream = stream;
}
public static boolean isSpace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int read() {
if (count == -1) {
throw new InputMismatchException();
}
try {
if (cur >= count) {
cur = 0;
count = stream.read(buffer);
if (count <= 0)
return -1;
}
} catch (IOException e) {
throw new InputMismatchException();
}
return buffer[cur++];
}
public int readSkipSpace() {
int c;
do {
c = read();
} while (isSpace(c));
return c;
}
public int nextInt() {
int sgn = 1;
int c = readSkipSpace();
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res = res * 10 + c - '0';
c = read();
} while (!isSpace(c));
res *= sgn;
return res;
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
}
| Java | ["3 4\n1 3\n1 1\n1 2\n2 3", "4 6\n1 2\n1 4\n1 2\n3 3\n1 3\n1 3"] | 2 seconds | ["1\n2\n3\n2", "1\n2\n3\n0\n1\n2"] | NoteIn the first sample: Application 3 generates a notification (there is 1 unread notification). Application 1 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads the notification generated by application 3, there are 2 unread notifications left. In the second sample test: Application 2 generates a notification (there is 1 unread notification). Application 4 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads first three notifications and since there are only three of them so far, there will be no unread notification left. Application 3 generates a notification (there is 1 unread notification). Application 3 generates a notification (there are 2 unread notifications). | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | a5e724081ad84f88813bb4de23a8230e | The first line of input contains two integers n and q (1ββ€βn,βqββ€β300β000)Β β the number of applications and the number of events to happen. The next q lines contain the events. The i-th of these lines starts with an integer typeiΒ β type of the i-th event. If typeiβ=β1 or typeiβ=β2 then it is followed by an integer xi. Otherwise it is followed by an integer ti (1ββ€βtypeiββ€β3,β1ββ€βxiββ€βn,β1ββ€βtiββ€βq). | 1,600 | Print the number of unread notifications after each event. | standard output | |
PASSED | e70a9e2e8f2fef25f1dc132b8b239afc | train_003.jsonl | 1470578700 | Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).q events are about to happen (in chronological order). They are of three types: Application x generates a notification (this new notification is unread). Thor reads all notifications generated so far by application x (he may re-read some notifications). Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation. Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone. | 256 megabytes | import java.awt.Point;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
public class Flab {
// author AlexFetisov implementation
// forgot to credit on first submission
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
List<Set<Integer>> apps = new ArrayList<>();
int n= in.nextInt();
int q = in.nextInt();
for(int i=0; i<n; i++) {
apps.add(new HashSet<>());
}
TreeSet<Point> set = new TreeSet<>(new Comparator<Point>() {
@Override
public int compare(Point o1, Point o2) {
return o1.x - o2.x;
}
});
int tot = 0;
int mId = 0;
boolean[] take = new boolean[q];
for(int i=0; i<q; i++) {
int t = in.nextInt();
int m = in.nextInt()-1;
if(t == 1) {
apps.get(m).add(mId);
set.add(new Point(mId++, m));
tot++;
}
else if(t == 2) {
Iterator<Integer> it = apps.get(m).iterator();
while(it.hasNext()) {
int cur = it.next();
if(!take[cur]) {
it.remove();
take[cur] = true;
tot--;
}
else {
it.remove();
}
}
}
else {
Iterator<Point> it = set.iterator();
while(it.hasNext()) {
Point cur = it.next();
if(cur.x > m) {
break;
}
else if(!take[cur.x]) {
it.remove();
take[cur.x] = true;
tot--;
}
else {
it.remove();
}
}
}
out.println(tot);
}
out.close();
}
} | Java | ["3 4\n1 3\n1 1\n1 2\n2 3", "4 6\n1 2\n1 4\n1 2\n3 3\n1 3\n1 3"] | 2 seconds | ["1\n2\n3\n2", "1\n2\n3\n0\n1\n2"] | NoteIn the first sample: Application 3 generates a notification (there is 1 unread notification). Application 1 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads the notification generated by application 3, there are 2 unread notifications left. In the second sample test: Application 2 generates a notification (there is 1 unread notification). Application 4 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads first three notifications and since there are only three of them so far, there will be no unread notification left. Application 3 generates a notification (there is 1 unread notification). Application 3 generates a notification (there are 2 unread notifications). | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | a5e724081ad84f88813bb4de23a8230e | The first line of input contains two integers n and q (1ββ€βn,βqββ€β300β000)Β β the number of applications and the number of events to happen. The next q lines contain the events. The i-th of these lines starts with an integer typeiΒ β type of the i-th event. If typeiβ=β1 or typeiβ=β2 then it is followed by an integer xi. Otherwise it is followed by an integer ti (1ββ€βtypeiββ€β3,β1ββ€βxiββ€βn,β1ββ€βtiββ€βq). | 1,600 | Print the number of unread notifications after each event. | standard output | |
PASSED | 850c232cf19e1da0304dde161914e236 | train_003.jsonl | 1470578700 | Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).q events are about to happen (in chronological order). They are of three types: Application x generates a notification (this new notification is unread). Thor reads all notifications generated so far by application x (he may re-read some notifications). Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation. Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashSet;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
InputReader inputReader = new InputReader(in);
PrintWriter out = new PrintWriter(System.out);
int n = inputReader.getNextInt();
int q = inputReader.getNextInt();
LinkedHashSet<Integer> linkedHashSet = new LinkedHashSet<>();
ArrayList<ArrayList<Integer>> positions = new ArrayList<>();
for(int i = 0; i < n+1; i++) {
positions.add(new ArrayList<>());
}
int cnt = 1;
for(int i = 0; i < q; i++) {
int t = inputReader.getNextInt();
int x = inputReader.getNextInt();
switch(t) {
case 1:
linkedHashSet.add(cnt);
positions.get(x).add(cnt);
cnt++;
break;
case 2:
for(int y: positions.get(x)) {
linkedHashSet.remove(y);
}
positions.get(x).clear();
break;
case 3:
Iterator<Integer> iterator = linkedHashSet.iterator();
while(iterator.hasNext()) {
int y = iterator.next();
if(y > x) {
break;
} else {
iterator.remove();
}
}
break;
}
out.println(linkedHashSet.size());
}
in.close();
out.close();
}
public static class InputReader {
static final String SEPARATOR = " ";
String[] split;
int head = 0;
BufferedReader in;
public InputReader(BufferedReader in) {
this.in = in;
}
private void fillBuffer() throws IOException {
if(split == null || head >= split.length) {
head = 0;
split = in.readLine().split(SEPARATOR);
}
}
public String getNextToken() throws IOException {
fillBuffer();
return split[head++];
}
public int getNextInt() throws IOException {
return Integer.parseInt(getNextToken());
}
public long getNextLong() throws IOException {
return Long.parseLong(getNextToken());
}
}
} | Java | ["3 4\n1 3\n1 1\n1 2\n2 3", "4 6\n1 2\n1 4\n1 2\n3 3\n1 3\n1 3"] | 2 seconds | ["1\n2\n3\n2", "1\n2\n3\n0\n1\n2"] | NoteIn the first sample: Application 3 generates a notification (there is 1 unread notification). Application 1 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads the notification generated by application 3, there are 2 unread notifications left. In the second sample test: Application 2 generates a notification (there is 1 unread notification). Application 4 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads first three notifications and since there are only three of them so far, there will be no unread notification left. Application 3 generates a notification (there is 1 unread notification). Application 3 generates a notification (there are 2 unread notifications). | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | a5e724081ad84f88813bb4de23a8230e | The first line of input contains two integers n and q (1ββ€βn,βqββ€β300β000)Β β the number of applications and the number of events to happen. The next q lines contain the events. The i-th of these lines starts with an integer typeiΒ β type of the i-th event. If typeiβ=β1 or typeiβ=β2 then it is followed by an integer xi. Otherwise it is followed by an integer ti (1ββ€βtypeiββ€β3,β1ββ€βxiββ€βn,β1ββ€βtiββ€βq). | 1,600 | Print the number of unread notifications after each event. | standard output | |
PASSED | 7b8a213998eb842401a078de1eea6d6a | train_003.jsonl | 1470578700 | Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).q events are about to happen (in chronological order). They are of three types: Application x generates a notification (this new notification is unread). Thor reads all notifications generated so far by application x (he may re-read some notifications). Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation. Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Hieu Le
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int q = in.nextInt();
int[] total = new int[n];
int[] read = new int[n];
int totalUnread = 0;
List<Pair<Integer, Integer>> notifications = new ArrayList<>();
int last = -1;
while (q-- > 0) {
int mode = in.nextInt();
if (mode == 1) {
int app = in.nextInt() - 1;
++total[app];
notifications.add(new Pair<>(app, total[app]));
++totalUnread;
} else if (mode == 2) {
int app = in.nextInt() - 1;
totalUnread -= (total[app] - read[app]);
read[app] = total[app];
} else {
int nextLast = in.nextInt() - 1;
if (nextLast > last) {
for (int i = last + 1; i <= nextLast; ++i) {
int app = notifications.get(i).first;
int rank = notifications.get(i).second;
if (read[app] < rank) {
++read[app];
--totalUnread;
}
}
last = nextLast;
}
}
out.println(totalUnread);
}
}
}
static class Pair<U extends Comparable<U>, V extends Comparable<V>> implements Comparable<Pair<U, V>> {
public final U first;
public final V second;
public Pair(U first, V second) {
this.first = first;
this.second = second;
}
public int hashCode() {
return (first == null ? 0 : first.hashCode() * 31) + (second == null ? 0 : second.hashCode());
}
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Pair<U, V> p = (Pair<U, V>) o;
return (first == null ? p.first == null : first.equals(p.first)) && (second == null ? p.second == null : second.equals(p.second));
}
public int compareTo(Pair<U, V> b) {
int cmpU = first.compareTo(b.first);
return cmpU != 0 ? cmpU : second.compareTo(b.second);
}
}
static class InputReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
private static final int BUFFER_SIZE = 32768;
public InputReader(InputStream stream) {
reader = new BufferedReader(
new InputStreamReader(stream), BUFFER_SIZE);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["3 4\n1 3\n1 1\n1 2\n2 3", "4 6\n1 2\n1 4\n1 2\n3 3\n1 3\n1 3"] | 2 seconds | ["1\n2\n3\n2", "1\n2\n3\n0\n1\n2"] | NoteIn the first sample: Application 3 generates a notification (there is 1 unread notification). Application 1 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads the notification generated by application 3, there are 2 unread notifications left. In the second sample test: Application 2 generates a notification (there is 1 unread notification). Application 4 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads first three notifications and since there are only three of them so far, there will be no unread notification left. Application 3 generates a notification (there is 1 unread notification). Application 3 generates a notification (there are 2 unread notifications). | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | a5e724081ad84f88813bb4de23a8230e | The first line of input contains two integers n and q (1ββ€βn,βqββ€β300β000)Β β the number of applications and the number of events to happen. The next q lines contain the events. The i-th of these lines starts with an integer typeiΒ β type of the i-th event. If typeiβ=β1 or typeiβ=β2 then it is followed by an integer xi. Otherwise it is followed by an integer ti (1ββ€βtypeiββ€β3,β1ββ€βxiββ€βn,β1ββ€βtiββ€βq). | 1,600 | Print the number of unread notifications after each event. | standard output | |
PASSED | 25b533329ba36bdabcd09cdc6a49c094 | train_003.jsonl | 1470578700 | Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).q events are about to happen (in chronological order). They are of three types: Application x generates a notification (this new notification is unread). Thor reads all notifications generated so far by application x (he may re-read some notifications). Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation. Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
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);
AThor solver = new AThor();
solver.solve(1, in, out);
out.close();
}
}
static class AThor {
public void solve(int testNumber, FastInput in, FastOutput out) {
int n = in.readInt();
int q = in.readInt();
int read = 0;
int total = 0;
boolean[] readed = new boolean[q];
IntegerDeque dq = new IntegerDequeImpl(q);
IntegerMultiWayDeque mdq = new IntegerMultiWayDeque(n, q);
for (int i = 0; i < q; i++) {
int t = in.readInt();
if (t == 1) {
int x = in.readInt() - 1;
dq.addLast(i);
mdq.addLast(x, i);
total++;
} else if (t == 2) {
int x = in.readInt() - 1;
while (!mdq.isEmpty(x)) {
int head = mdq.removeFirst(x);
if (!readed[head]) {
readed[head] = true;
total--;
}
}
} else {
int x = in.readInt();
while (read < x) {
int head = dq.removeFirst();
if (!readed[head]) {
readed[head] = true;
total--;
}
read++;
}
}
out.println(total);
}
}
}
static interface IntegerStack {
void addLast(int x);
}
static class IntegerDequeImpl implements IntegerDeque {
private int[] data;
private int bpos;
private int epos;
private static final int[] EMPTY = new int[0];
private int n;
public IntegerDequeImpl(int cap) {
if (cap == 0) {
data = EMPTY;
} else {
data = new int[cap];
}
bpos = 0;
epos = 0;
n = cap;
}
private void expandSpace(int len) {
while (n < len) {
n = Math.max(n + 10, n * 2);
}
int[] newData = new int[n];
if (bpos <= epos) {
if (bpos < epos) {
System.arraycopy(data, bpos, newData, 0, epos - bpos);
}
} else {
System.arraycopy(data, bpos, newData, 0, data.length - bpos);
System.arraycopy(data, 0, newData, data.length - bpos, epos);
}
epos = size();
bpos = 0;
data = newData;
}
public IntegerIterator iterator() {
return new IntegerIterator() {
int index = bpos;
public boolean hasNext() {
return index != epos;
}
public int next() {
int ans = data[index];
index = IntegerDequeImpl.this.next(index);
return ans;
}
};
}
public int removeFirst() {
int ans = data[bpos];
bpos = next(bpos);
return ans;
}
public void addLast(int x) {
ensureMore();
data[epos] = x;
epos = next(epos);
}
private int next(int x) {
return x + 1 >= n ? 0 : x + 1;
}
private void ensureMore() {
if (next(epos) == bpos) {
expandSpace(n + 1);
}
}
public int size() {
int ans = epos - bpos;
if (ans < 0) {
ans += data.length;
}
return ans;
}
public String toString() {
StringBuilder builder = new StringBuilder();
for (IntegerIterator iterator = iterator(); iterator.hasNext(); ) {
builder.append(iterator.next()).append(' ');
}
return builder.toString();
}
}
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();
}
}
static interface IntegerDeque extends IntegerStack {
int removeFirst();
}
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 interface IntegerIterator {
boolean hasNext();
int next();
}
static class IntegerMultiWayDeque {
private int[] values;
private int[] next;
private int[] prev;
private int[] heads;
private int[] tails;
private int alloc;
private int queueNum;
public IntegerIterator iterator(final int queue) {
return new IntegerIterator() {
int ele = heads[queue];
public boolean hasNext() {
return ele != 0;
}
public int next() {
int ans = values[ele];
ele = next[ele];
return ans;
}
};
}
private void doubleCapacity() {
int newSize = Math.max(next.length + 10, next.length * 2);
next = Arrays.copyOf(next, newSize);
prev = Arrays.copyOf(prev, newSize);
values = Arrays.copyOf(values, newSize);
}
public void alloc() {
alloc++;
if (alloc >= next.length) {
doubleCapacity();
}
next[alloc] = 0;
}
public boolean isEmpty(int qId) {
return heads[qId] == 0;
}
public IntegerMultiWayDeque(int qNum, int totalCapacity) {
values = new int[totalCapacity + 1];
next = new int[totalCapacity + 1];
prev = new int[totalCapacity + 1];
heads = new int[qNum];
tails = new int[qNum];
queueNum = qNum;
}
public void addLast(int qId, int x) {
alloc();
values[alloc] = x;
if (heads[qId] == 0) {
heads[qId] = tails[qId] = alloc;
return;
}
next[tails[qId]] = alloc;
prev[alloc] = tails[qId];
tails[qId] = alloc;
}
public int removeFirst(int qId) {
int ans = values[heads[qId]];
if (heads[qId] == tails[qId]) {
heads[qId] = tails[qId] = 0;
} else {
heads[qId] = next[heads[qId]];
prev[tails[qId]] = 0;
}
return ans;
}
public String toString() {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < queueNum; i++) {
if (isEmpty(i)) {
continue;
}
builder.append(i).append(": ");
for (IntegerIterator iterator = iterator(i); iterator.hasNext(); ) {
builder.append(iterator.next()).append(",");
}
if (builder.charAt(builder.length() - 1) == ',') {
builder.setLength(builder.length() - 1);
}
builder.append('\n');
}
return builder.toString();
}
}
}
| Java | ["3 4\n1 3\n1 1\n1 2\n2 3", "4 6\n1 2\n1 4\n1 2\n3 3\n1 3\n1 3"] | 2 seconds | ["1\n2\n3\n2", "1\n2\n3\n0\n1\n2"] | NoteIn the first sample: Application 3 generates a notification (there is 1 unread notification). Application 1 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads the notification generated by application 3, there are 2 unread notifications left. In the second sample test: Application 2 generates a notification (there is 1 unread notification). Application 4 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads first three notifications and since there are only three of them so far, there will be no unread notification left. Application 3 generates a notification (there is 1 unread notification). Application 3 generates a notification (there are 2 unread notifications). | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | a5e724081ad84f88813bb4de23a8230e | The first line of input contains two integers n and q (1ββ€βn,βqββ€β300β000)Β β the number of applications and the number of events to happen. The next q lines contain the events. The i-th of these lines starts with an integer typeiΒ β type of the i-th event. If typeiβ=β1 or typeiβ=β2 then it is followed by an integer xi. Otherwise it is followed by an integer ti (1ββ€βtypeiββ€β3,β1ββ€βxiββ€βn,β1ββ€βtiββ€βq). | 1,600 | Print the number of unread notifications after each event. | standard output | |
PASSED | 96a22c4417519f4fc1503e80145032a8 | train_003.jsonl | 1470578700 | Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).q events are about to happen (in chronological order). They are of three types: Application x generates a notification (this new notification is unread). Thor reads all notifications generated so far by application x (he may re-read some notifications). Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation. Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone. | 256 megabytes |
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map.Entry;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;
import java.util.Scanner;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
public class SuffixArray {
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;
private static long max = Long.MIN_VALUE;
private static int mod = 1000000000+7;
private static long mod1=(long) Math.pow(2,63);
private static void soln() {
int n=nextInt();
int q=nextInt();
Queue<Integer>[] qs=new LinkedList[n+1];
Queue <Pair> qm=new LinkedList();
for(int i=1;i<=n;i++)
qs[i]=new LinkedList();
int j=1;
int ans=0;
for(int i=1;i<=q;i++){
int x=nextInt();
int y=nextInt();
if(x==1){
qs[y].add(j);
qm.add(new Pair(j,y));
j++;
ans++;
}else if(x==2){
ans-=qs[y].size();
qs[y].clear();
}else{
while(!qm.isEmpty() && qm.peek().x<=y){
Pair x1=qm.poll();
int f=x1.x;
int s=x1.y;
//System.out.println(f+" "+s);
if(!qs[s].isEmpty() && qs[s].peek()==f){
qs[s].poll();
ans--;
}
}
}
pw.println(ans);
}
}
private static class Pair{
int x,y;
public Pair(int x,int y){
this.x=x;
this.y=y;
}
}
public static class Segment {
private int[] tree;
//private int[] lazy;
private int size;
private int n;
private int[] arr;
private int ans;
private class node{
private int a;
private int b;
private int c;
public node(int x,int y,int z){
a=x;
b=y;
c=z;
}
}
public Segment(int n){
//this.base=arr;
int x = (int) (Math.ceil(Math.log(n) / Math.log(2)));
size = 2 * (int) Math.pow(2, x) - 1;
tree=new int[size];
//lazy=new int[size];
this.n=n;
//this.arr=arr;
build(0,0,n-1);
}
private void build(int id,int l,int r){
//pw.println(1);
if(r==l){
tree[id]=0;
//System.out.println(id+" "+tree[id]);
return;
}
int mid=l+(r-l)/2;
//System.out.println(2*id+1+" "+l+" "+mid);
build(2*id+1,l,mid);
//System.out.println(2*id+2+" "+(mid+1)+" "+r);
build(2*id+2,mid+1,r);
tree[id]=tree[2*id+1]+tree[2*id+2];
//System.out.println(id+" "+tree[id]);
}
public int query(int l,int r){
return queryUtil(0,0,n-1,l,r);
}
private int queryUtil(int id,int l,int r,int x,int y){
if(x<=l && y>=r){
//System.out.println(id+" "+l+" "+r+" "+x+" "+y+" "+tree[id]);
return tree[id];
}
//System.out.println(1111);
if(r<x || l>y)
return 0;
int mid=l+(r-l)/2;
int ans= queryUtil(2*id+1,l,mid,x,y)+queryUtil(2*id+2,mid+1,r,x,y);
// System.out.println(id+" "+l+" "+r+" "+x+" "+y+" "+ans);
return ans;
}
/*private void cnt(int id,int l,int r,HashSet<Integer> set){
if(tree[id]!=0){
set.add(tree[id]);
return;
}
if(r==l)
return;
int mid=l+(r-l)/2;
cnt(2*id+1,l,mid,set);
cnt(2*id+2,mid+1,r,set);
}*/
public void update(int x,int id,int l,int r,int flag){
//System.out.println(x);
/*if(x>r || l>y)
return;
if(x<=l && r<=y){
lazy[id]=lazy[id]^xor;
for(int i=0;i<32;i++){
if(xor%2!=0){
tree[id][i]=r-l+1-tree[id][i];
}
xor/=2;
}
return;
}*/
if(x<l || x>r)
return;
if(flag==0)
tree[id]--;
else
tree[id]++;
//System.out.println(id+" "+tree[id]);
if(l!=r){
int mid=l+(r-l)/2;
//lazy[id]=lazy[id]^xor;
//shift(id,l,mid,r);
update(x,2*id+1,l,mid,flag);
update(x,2*id+2,mid+1,r,flag);
}
//tree[id][i]=tree[2*id+1][i]+tree[2*id+2][i];
}
/*private void shift(int id,int l,int mid,int r){
if(lazy[id]!=0){
int xor=lazy[id];
lazy[2*id+1]^=lazy[id];
lazy[2*id+2]^=lazy[id];
for(int i=0;i<32;i++){
if(xor%2!=0){
tree[2*id+1][i]=mid-l+1-tree[2*id+1][i];
tree[2*id+2][i]=r-mid-tree[2*id+2][i];
}
xor/=2;
}
}
lazy[id]=0;
}*/
}
public static int fun(Node root,int xor){
Node tmp=root;
int temp=xor;
int[] arr=new int[28];
for(int i=0;i<=27;i++){
arr[i]=temp%2;
temp=temp/2;
}
for(int i=27;i>=0;i--){
int val= arr[i];
if(tmp.arr[1-val]!=null)
tmp=tmp.arr[1-val];
else if(tmp.arr[val]!=null)
tmp=tmp.arr[val];
}
return xor^(tmp.val);
}
public static void insert(Node root,int xor){
Node temp=root;
int tmp=xor;
int[] arr=new int[28];
for(int i=0;i<=27;i++){
arr[i]=tmp%2;
tmp=tmp/2;
}
for(int i=27;i>=0;i--){
int val= arr[i];
if(temp.arr[val]==null){
temp.arr[val]=new Node();
}
temp=temp.arr[val];
}
temp.val=xor;
}
public static class Node{
int val;
Node[] arr;
public Node(){
arr=new Node[2];
val=0;
arr[1]=null;
arr[0]=null;
}
}
public static boolean isPrime(int n) {
// Corner cases
if (n <= 1)
return false;
if (n <= 3)
return true;
// This is checked so that we can skip
// middle five numbers in below loop
if (n % 2 == 0 || n % 3 == 0)
return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
/*public static long dijsktra(LinkedList<Pair>[] l,LinkedList<Pair>[] l1,int n){
long ans=0;
PriorityQueue<Pair> q = new PriorityQueue<>();
int[] arr=new int[n];
Arrays.fill(arr,Integer.MAX_VALUE);
arr[0]=0;
q.add(new Pair(0, 0));
while(!q.isEmpty()){
Pair p = q.poll();
for(Pair x:l[p.x]){
if(arr[x.x]>(arr[p.x]+x.w)){
arr[x.x] = (arr[p.x]+x.w);
q.add(new Pair(x.x,arr[x.x]));
}
}
}
boolean[] visited=new boolean[n];
visited[0] = true;
PriorityQueue<Integer> q1=new PriorityQueue();
q1.add(0);
while(!q1.isEmpty()){
int y = q1.poll();
for(Pair g:l1[y]){
if(!visited[g.x]){
ans+=Math.max(0, Math.min(arr[y]+g.w-arr[g.x],arr[g.x]+g.w-arr[y]));
visited[g.x] = true;
q1.add(g.x);
}else{
ans+=Math.max(0, Math.min(arr[y]+g.w-arr[g.x],arr[g.x]+g.w-arr[y]));
}
}
}
//System.out.println(ans);
return ans;
}*/
private static void DFS(int cur,int prev,boolean[] visited,LinkedList<Integer>[] l){
Iterator<Integer> i=l[cur].listIterator();
visited[cur]=true;
while(i.hasNext()){
int x=i.next();
if(!visited[x] && x!=prev){
DFS(x,cur,visited,l);
}
}
}
private static long mat_power(long n){
long[][] matrix={{1,1},{1,0}};
long[][] temp={{1,0},{0,1}};
while(n!=0){
if(n%2!=0){
matrix_multiplication(temp,matrix);
}
matrix_multiplication(matrix,matrix);
n>>=1;
}
return temp[0][1];
}
private static void matrix_multiplication(long[][] a,long[][] b){
long[][] result=new long[2][2];
for(int i = 0 ; i < 2 ; i ++)
for(int j = 0 ; j < 2 ; j++)
for(int k = 0 ; k < 2 ; k++)
result[i][j] = (result[i][j] + a[i][k]*b[k][j]) % mod;
for(int i = 0 ; i < 2 ; i++)
for(int j = 0 ; j < 2 ; j++)
a[i][j] = result[i][j];
}
private static long power(long x,long y,long mod){
long ans = 1;
while(y>0){
if(y%2==1){
if(ans>mod/x) return -1;
ans*=x;
y-=1;
}
else{
if(x>mod/x) return -1;
x*=x;
y/=2;
}
}
return ans;
}
public static class Suffix implements Comparable<Suffix>{
int index;
int[] rank=new int[2];
@Override
public int compareTo(Suffix arg0){
return (this.rank[0]==arg0.rank[0])?(this.rank[1]<arg0.rank[1]?-1:1):(this.rank[0]<arg0.rank[0]?-1:1);
}
}
private static int[] buildSuffix(String s,int n){
Suffix[] arr=new Suffix[n];
for(int i=0;i<n;i++)
arr[i]=new Suffix();
for(int i=0;i<n;i++){
arr[i].index=i;
arr[i].rank[0]=s.charAt(i)-'a';
arr[i].rank[1]=((i+1)<n)?(s.charAt(i+1)-'a'):-1;
}
Arrays.sort(arr);
//for(int i=0;i<n;i++)
//System.out.print(arr[i].index);
int[] ind=new int[n];
for(int k=4;k<2*n;k=k*2){
int rank=0;
int p_rank=arr[0].rank[0];
arr[0].rank[0]=rank;
ind[arr[0].index]=0;
for(int i=1;i<n;i++){
if (arr[i].rank[0] == p_rank && arr[i].rank[1] == arr[i-1].rank[1]) {
p_rank = arr[i].rank[0];
arr[i].rank[0] = rank;
}
else{
p_rank = arr[i].rank[0];
arr[i].rank[0] = ++rank;
}
ind[arr[i].index] = i;
}
for(int i=0;i<n;i++){
int n_index=arr[i].index + k/2;
arr[i].rank[1]=(n_index<n)?arr[ind[n_index]].rank[0] : -1;
}
Arrays.sort(arr);
}
int[] suffixArr=new int[n];
for(int i=0;i<n;i++)
suffixArr[i]=arr[i].index;
return suffixArr;
}
private static long pow(long a, long b) {
if (b == 0)
return 1;
long p = pow(a, b / 2);
p = (p * p);
return (b % 2 == 0) ? p : (a * p);
}
private static long gcd(long x, long y) {
if (y == 0)
return x;
return gcd(y, x % y);
}
private static long max(long a, long b) {
if (a > b)
return a;
return b;
}
private static long min(long a, long b) {
if (a < b)
return a;
return b;
}
public static void main(String[] args) throws Exception {
new Thread(null, new Runnable() {
public void run() {
try {
InputReader(System.in);
pw = new PrintWriter(System.out);
soln();
pw.close();
soln();
} catch (Exception e) {
e.printStackTrace();
}
}
}, "1", 1 << 26).start();
}
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 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;
}
private static 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;
}
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 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();
}
private static int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
private static long[] nextLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
private static void pArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
return;
}
private static void pArray(long[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
return;
}
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 | ["3 4\n1 3\n1 1\n1 2\n2 3", "4 6\n1 2\n1 4\n1 2\n3 3\n1 3\n1 3"] | 2 seconds | ["1\n2\n3\n2", "1\n2\n3\n0\n1\n2"] | NoteIn the first sample: Application 3 generates a notification (there is 1 unread notification). Application 1 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads the notification generated by application 3, there are 2 unread notifications left. In the second sample test: Application 2 generates a notification (there is 1 unread notification). Application 4 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads first three notifications and since there are only three of them so far, there will be no unread notification left. Application 3 generates a notification (there is 1 unread notification). Application 3 generates a notification (there are 2 unread notifications). | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | a5e724081ad84f88813bb4de23a8230e | The first line of input contains two integers n and q (1ββ€βn,βqββ€β300β000)Β β the number of applications and the number of events to happen. The next q lines contain the events. The i-th of these lines starts with an integer typeiΒ β type of the i-th event. If typeiβ=β1 or typeiβ=β2 then it is followed by an integer xi. Otherwise it is followed by an integer ti (1ββ€βtypeiββ€β3,β1ββ€βxiββ€βn,β1ββ€βtiββ€βq). | 1,600 | Print the number of unread notifications after each event. | standard output | |
PASSED | e8f0e26b92ed506b7ba753fa8d6d5a76 | train_003.jsonl | 1470578700 | Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).q events are about to happen (in chronological order). They are of three types: Application x generates a notification (this new notification is unread). Thor reads all notifications generated so far by application x (he may re-read some notifications). Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation. Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone. | 256 megabytes | import java.awt.geom.*;
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;
/*
br = new BufferedReader(new FileReader("input.txt"));
pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
*/
public class Main {
private static BufferedReader br;
private static StringTokenizer st;
private static PrintWriter pw;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
//int qq = 1;
int qq = Integer.MAX_VALUE;
//int qq = readInt();
for(int casenum = 1; casenum <= qq; casenum++) {
int n = readInt();
int qqq = readInt();
ArrayList<Integer>[] dp = new ArrayList[n];
for(int i = 0; i < n; i++) {
dp[i] = new ArrayList<Integer>();
}
int num = 0;
TreeSet<Integer> unread = new TreeSet<>();
while(qqq-- > 0) {
int type = readInt();
if(type == 1) {
int id = readInt()-1;
dp[id].add(++num);
unread.add(num);
}
else if(type == 2) {
int id = readInt()-1;
for(int out: dp[id]) {
unread.remove(out);
}
dp[id].clear();
}
else {
int thresh = readInt();
while(!unread.isEmpty() && unread.first() <= thresh) {
unread.remove(unread.first());
}
}
pw.println(unread.size());
}
}
exitImmediately();
}
private static void exitImmediately() {
pw.close();
System.exit(0);
}
private static long readLong() throws IOException {
return Long.parseLong(nextToken());
}
private static double readDouble() throws IOException {
return Double.parseDouble(nextToken());
}
private static int readInt() throws IOException {
return Integer.parseInt(nextToken());
}
private static String nextLine() throws IOException {
String s = br.readLine();
if(s == null) {
exitImmediately();
}
st = null;
return s;
}
private static String nextToken() throws IOException {
while(st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(nextLine().trim());
}
return st.nextToken();
}
} | Java | ["3 4\n1 3\n1 1\n1 2\n2 3", "4 6\n1 2\n1 4\n1 2\n3 3\n1 3\n1 3"] | 2 seconds | ["1\n2\n3\n2", "1\n2\n3\n0\n1\n2"] | NoteIn the first sample: Application 3 generates a notification (there is 1 unread notification). Application 1 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads the notification generated by application 3, there are 2 unread notifications left. In the second sample test: Application 2 generates a notification (there is 1 unread notification). Application 4 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads first three notifications and since there are only three of them so far, there will be no unread notification left. Application 3 generates a notification (there is 1 unread notification). Application 3 generates a notification (there are 2 unread notifications). | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | a5e724081ad84f88813bb4de23a8230e | The first line of input contains two integers n and q (1ββ€βn,βqββ€β300β000)Β β the number of applications and the number of events to happen. The next q lines contain the events. The i-th of these lines starts with an integer typeiΒ β type of the i-th event. If typeiβ=β1 or typeiβ=β2 then it is followed by an integer xi. Otherwise it is followed by an integer ti (1ββ€βtypeiββ€β3,β1ββ€βxiββ€βn,β1ββ€βtiββ€βq). | 1,600 | Print the number of unread notifications after each event. | standard output | |
PASSED | 24a647148cee6a5041e64dbf497c3c6f | train_003.jsonl | 1470578700 | Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).q events are about to happen (in chronological order). They are of three types: Application x generates a notification (this new notification is unread). Thor reads all notifications generated so far by application x (he may re-read some notifications). Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation. Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone. | 256 megabytes | import java.awt.geom.*;
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;
/*
br = new BufferedReader(new FileReader("input.txt"));
pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
*/
public class Main {
private static BufferedReader br;
private static StringTokenizer st;
private static PrintWriter pw;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
//int qq = 1;
int qq = Integer.MAX_VALUE;
//int qq = readInt();
for(int casenum = 1; casenum <= qq; casenum++) {
int n = readInt();
int qqq = readInt();
ArrayList<Integer>[] dp = new ArrayList[n];
for(int i = 0; i < n; i++) {
dp[i] = new ArrayList<Integer>();
}
int num = 0;
int orig = qqq;
int ret = 0;
boolean[] seen = new boolean[qqq+1];
int last = 0;
while(qqq-- > 0) {
int type = readInt();
if(type == 1) {
int id = readInt()-1;
dp[id].add(++num);
ret++;
}
else if(type == 2) {
int id = readInt()-1;
for(int out: dp[id]) {
if(!seen[out]) {
seen[out] = true;
ret--;
}
}
dp[id].clear();
}
else {
int thresh = readInt();
while(last+1 <= num && last+1 <= thresh) {
last++;
if(!seen[last]) {
seen[last] = true;
ret--;
}
}
}
pw.println(ret);
}
}
exitImmediately();
}
private static void exitImmediately() {
pw.close();
System.exit(0);
}
private static long readLong() throws IOException {
return Long.parseLong(nextToken());
}
private static double readDouble() throws IOException {
return Double.parseDouble(nextToken());
}
private static int readInt() throws IOException {
return Integer.parseInt(nextToken());
}
private static String nextLine() throws IOException {
String s = br.readLine();
if(s == null) {
exitImmediately();
}
st = null;
return s;
}
private static String nextToken() throws IOException {
while(st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(nextLine().trim());
}
return st.nextToken();
}
} | Java | ["3 4\n1 3\n1 1\n1 2\n2 3", "4 6\n1 2\n1 4\n1 2\n3 3\n1 3\n1 3"] | 2 seconds | ["1\n2\n3\n2", "1\n2\n3\n0\n1\n2"] | NoteIn the first sample: Application 3 generates a notification (there is 1 unread notification). Application 1 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads the notification generated by application 3, there are 2 unread notifications left. In the second sample test: Application 2 generates a notification (there is 1 unread notification). Application 4 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads first three notifications and since there are only three of them so far, there will be no unread notification left. Application 3 generates a notification (there is 1 unread notification). Application 3 generates a notification (there are 2 unread notifications). | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | a5e724081ad84f88813bb4de23a8230e | The first line of input contains two integers n and q (1ββ€βn,βqββ€β300β000)Β β the number of applications and the number of events to happen. The next q lines contain the events. The i-th of these lines starts with an integer typeiΒ β type of the i-th event. If typeiβ=β1 or typeiβ=β2 then it is followed by an integer xi. Otherwise it is followed by an integer ti (1ββ€βtypeiββ€β3,β1ββ€βxiββ€βn,β1ββ€βtiββ€βq). | 1,600 | Print the number of unread notifications after each event. | standard output | |
PASSED | 4e0c86fe7c45fd685e7d64736e00cc4a | train_003.jsonl | 1314633600 | Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.One day Petya encountered a tree with n vertexes. Besides, the tree was weighted, i. e. each edge of the tree has weight (a positive integer). An edge is lucky if its weight is a lucky number. Note that a tree with n vertexes is an undirected connected graph that has exactly nβ-β1 edges.Petya wondered how many vertex triples (i,βj,βk) exists that on the way from i to j, as well as on the way from i to k there must be at least one lucky edge (all three vertexes are pairwise distinct). The order of numbers in the triple matters, that is, the triple (1,β2,β3) is not equal to the triple (2,β1,β3) and is not equal to the triple (1,β3,β2). Find how many such triples of vertexes exist. | 256 megabytes | import java.util.Arrays;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.StringTokenizer;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskE solver = new TaskE();
solver.solve(1, in, out);
out.close();
}
}
class TaskE {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int[] p = createSets(n + 1);
for (int i = 1; i < n; i++) {
int x = in.nextInt();
int y = in.nextInt();
String s = in.next();
if (!checkLucky(s)) {
if (root(p, x) != root(p, y)) {
unite(p, x, y);
}
}
}
for (int i = 1; i <= n; i++) {
root(p, i);
}
int count[] = new int[n + 1];
Arrays.fill(count, 0);
for (int i = 1; i <= n; i++) {
count[p[i]]++;
}
long result = 0;
for (int i = 1; i <= n; i++) {
long x = (long) n - count[p[i]];
result += x * (x - 1);
}
out.println(result);
}
private boolean checkLucky(String s) {
int n = s.length();
char c[] = s.toCharArray();
for (int i = 0; i < n; i++) {
if (c[i] != '4' && c[i] != '7') {
return false;
}
}
return true;
}
public static int[] createSets(int size) {
int[] p = new int[size];
for (int i = 0; i < size; i++)
p[i] = i;
return p;
}
public static int root(int[] p, int x) {
return x == p[x] ? x : (p[x] = root(p, p[x]));
}
public static void unite(int[] p, int a, int b) {
a = root(p, a);
b = root(p, b);
if (a != b)
p[a] = b;
}
}
class InputReader {
StringTokenizer tokenizer;
BufferedReader reader;
public InputReader(InputStream stream) {
tokenizer = null;
reader = new BufferedReader(new InputStreamReader(stream), 32768);
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
| Java | ["4\n1 2 4\n3 1 2\n1 4 7", "4\n1 2 4\n1 3 47\n1 4 7447"] | 2 seconds | ["16", "24"] | NoteThe 16 triples of vertexes from the first sample are: (1,β2,β4),β(1,β4,β2),β(2,β1,β3),β(2,β1,β4),β(2,β3,β1),β(2,β3,β4),β(2,β4,β1),β(2,β4,β3),β(3,β2,β4),β(3,β4,β2),β(4,β1,β2),β(4,β1,β3),β(4,β2,β1),β(4,β2,β3),β(4,β3,β1),β(4,β3,β2).In the second sample all the triples should be counted: 4Β·3Β·2β=β24. | Java 8 | standard input | [
"combinatorics",
"dfs and similar",
"trees"
] | 6992db71923a01211b5073ee0f8a193a | The first line contains the single integer n (1ββ€βnββ€β105) β the number of tree vertexes. Next nβ-β1 lines contain three integers each: ui vi wi (1ββ€βui,βviββ€βn,β1ββ€βwiββ€β109) β the pair of vertexes connected by the edge and the edge's weight. | 1,900 | On the single line print the single number β the answer. Please do not use the %lld specificator to read or write 64-bit numbers in Π‘++. It is recommended to use the cin, cout streams or the %I64d specificator. | standard output | |
PASSED | c050e2f319044250c6e7d14a4642a288 | train_003.jsonl | 1314633600 | Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.One day Petya encountered a tree with n vertexes. Besides, the tree was weighted, i. e. each edge of the tree has weight (a positive integer). An edge is lucky if its weight is a lucky number. Note that a tree with n vertexes is an undirected connected graph that has exactly nβ-β1 edges.Petya wondered how many vertex triples (i,βj,βk) exists that on the way from i to j, as well as on the way from i to k there must be at least one lucky edge (all three vertexes are pairwise distinct). The order of numbers in the triple matters, that is, the triple (1,β2,β3) is not equal to the triple (2,β1,β3) and is not equal to the triple (1,β3,β2). Find how many such triples of vertexes exist. | 256 megabytes | import java.util.ArrayList;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.StringTokenizer;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskE solver = new TaskE();
solver.solve(1, in, out);
out.close();
}
}
class TaskE {
boolean[] visited;
ArrayList<Integer>[] p;
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
p = new ArrayList[n + 1];
for (int i = 0; i < n + 1; i++) {
p[i] = new ArrayList<Integer>();
}
for (int i = 1; i < n; i++) {
int x = in.nextInt();
int y = in.nextInt();
String s = in.next();
if (!checkLucky(s)) {
p[x].add(y);
p[y].add(x);
}
}
long result = 0;
visited = new boolean[n + 1];
visited[0] = true;
for (int i = 0; i <= n; i++) {
if (!visited[i]) {
long count = visit(i);
result += (n - count) * (n - 1 - count) * count;
}
}
out.println(result);
}
private long visit(int i) {
long count = 1;
visited[i] = true;
for (Integer x : p[i]) {
if (!visited[x]) {
count += visit(x);
}
}
return count;
}
private boolean checkLucky(String s) {
int n = s.length();
char c[] = s.toCharArray();
for (int i = 0; i < n; i++) {
if (c[i] != '4' && c[i] != '7') {
return false;
}
}
return true;
}
}
class InputReader {
StringTokenizer tokenizer;
BufferedReader reader;
public InputReader(InputStream stream) {
tokenizer = null;
reader = new BufferedReader(new InputStreamReader(stream), 32768);
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
| Java | ["4\n1 2 4\n3 1 2\n1 4 7", "4\n1 2 4\n1 3 47\n1 4 7447"] | 2 seconds | ["16", "24"] | NoteThe 16 triples of vertexes from the first sample are: (1,β2,β4),β(1,β4,β2),β(2,β1,β3),β(2,β1,β4),β(2,β3,β1),β(2,β3,β4),β(2,β4,β1),β(2,β4,β3),β(3,β2,β4),β(3,β4,β2),β(4,β1,β2),β(4,β1,β3),β(4,β2,β1),β(4,β2,β3),β(4,β3,β1),β(4,β3,β2).In the second sample all the triples should be counted: 4Β·3Β·2β=β24. | Java 8 | standard input | [
"combinatorics",
"dfs and similar",
"trees"
] | 6992db71923a01211b5073ee0f8a193a | The first line contains the single integer n (1ββ€βnββ€β105) β the number of tree vertexes. Next nβ-β1 lines contain three integers each: ui vi wi (1ββ€βui,βviββ€βn,β1ββ€βwiββ€β109) β the pair of vertexes connected by the edge and the edge's weight. | 1,900 | On the single line print the single number β the answer. Please do not use the %lld specificator to read or write 64-bit numbers in Π‘++. It is recommended to use the cin, cout streams or the %I64d specificator. | standard output | |
PASSED | 4ee55875547a1f603ab388ee2433c64d | train_003.jsonl | 1314633600 | Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.One day Petya encountered a tree with n vertexes. Besides, the tree was weighted, i. e. each edge of the tree has weight (a positive integer). An edge is lucky if its weight is a lucky number. Note that a tree with n vertexes is an undirected connected graph that has exactly nβ-β1 edges.Petya wondered how many vertex triples (i,βj,βk) exists that on the way from i to j, as well as on the way from i to k there must be at least one lucky edge (all three vertexes are pairwise distinct). The order of numbers in the triple matters, that is, the triple (1,β2,β3) is not equal to the triple (2,β1,β3) and is not equal to the triple (1,β3,β2). Find how many such triples of vertexes exist. | 256 megabytes | import java.awt.Point;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class Main {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
StringTokenizer st;
st = new StringTokenizer(br.readLine());
int n,m;
m = n = Integer.parseInt(st.nextToken());
long total = 1l*n*(n-1)*(n-2);
DSU dsu = new DSU(n);
n--;
while(n-->0) {
st = new StringTokenizer(br.readLine());
int u = Integer.parseInt(st.nextToken());
int v = Integer.parseInt(st.nextToken());
int w = Integer.parseInt(st.nextToken());
if(!isLucky(w)) {
dsu.union(u-1, v-1);
}
}
for(int i=0;i<dsu.size.length;i++) {
if(dsu.find(i) == i) {
int e = dsu.size[i];
total -= 1l*e*(e-1)*(e-2);
total -= 1l*e*(e-1)*(m-e)*2;
}
}
out.println(total);
out.flush();
}
static boolean isLucky(int n) {
while(n>0) {
if(n%10 != 4 && n%10 != 7) {
return false;
}
n/=10;
}
return true;
}
static long pow(long a,int n) {
long res=1;
while (n>0) {
if ((n-n/2*2)==1) {
res=res*a;
}
a=a*a;
n>>=1;
}
return res;
}
static class DSU{
int[] parents,size;
public DSU(int n) {
parents = new int[n];
size = new int[n];
for(int i=0;i<n;i++) {
parents[i] = i;
size[i] = 1;
}
}
int find(int u) {
if(parents[u] == u) {
return u;
}else {
parents[u] = find(parents[u]);
return parents[u];
}
}
void union(int u,int v) {
u = find(u);
v = find(v);
if(size[u] > size[v]) {
parents[v] = u;
size[u] += size[v];
}else {
parents[u] = v;
size[v] += size[u];
}
}
boolean isCycle(int u, int v) {
return find(u) == find(v);
}
}
}
| Java | ["4\n1 2 4\n3 1 2\n1 4 7", "4\n1 2 4\n1 3 47\n1 4 7447"] | 2 seconds | ["16", "24"] | NoteThe 16 triples of vertexes from the first sample are: (1,β2,β4),β(1,β4,β2),β(2,β1,β3),β(2,β1,β4),β(2,β3,β1),β(2,β3,β4),β(2,β4,β1),β(2,β4,β3),β(3,β2,β4),β(3,β4,β2),β(4,β1,β2),β(4,β1,β3),β(4,β2,β1),β(4,β2,β3),β(4,β3,β1),β(4,β3,β2).In the second sample all the triples should be counted: 4Β·3Β·2β=β24. | Java 8 | standard input | [
"combinatorics",
"dfs and similar",
"trees"
] | 6992db71923a01211b5073ee0f8a193a | The first line contains the single integer n (1ββ€βnββ€β105) β the number of tree vertexes. Next nβ-β1 lines contain three integers each: ui vi wi (1ββ€βui,βviββ€βn,β1ββ€βwiββ€β109) β the pair of vertexes connected by the edge and the edge's weight. | 1,900 | On the single line print the single number β the answer. Please do not use the %lld specificator to read or write 64-bit numbers in Π‘++. It is recommended to use the cin, cout streams or the %I64d specificator. | standard output | |
PASSED | 54be9f9580206a74e7de6ba271343953 | train_003.jsonl | 1314633600 | Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.One day Petya encountered a tree with n vertexes. Besides, the tree was weighted, i. e. each edge of the tree has weight (a positive integer). An edge is lucky if its weight is a lucky number. Note that a tree with n vertexes is an undirected connected graph that has exactly nβ-β1 edges.Petya wondered how many vertex triples (i,βj,βk) exists that on the way from i to j, as well as on the way from i to k there must be at least one lucky edge (all three vertexes are pairwise distinct). The order of numbers in the triple matters, that is, the triple (1,β2,β3) is not equal to the triple (2,β1,β3) and is not equal to the triple (1,β3,β2). Find how many such triples of vertexes exist. | 256 megabytes | import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class P110E {
public static void main(String[] args) {
Scanner inScanner = new Scanner(System.in);
int n = inScanner.nextInt();
Node[] nodes = new Node[n];
for (int i = 0; i < n; i++)
nodes[i] = new Node();
for (int i = 0; i < n - 1; i++) {
Node start = nodes[inScanner.nextInt() - 1];
Node end = nodes[inScanner.nextInt() - 1];
int weight = inScanner.nextInt();
if (!Integer.toString(weight).matches("[47]*")) {
start.neighbors.add(end);
end.neighbors.add(start);
}
}
long result = 0;
for (Node node : nodes) {
long size = node.connectedGraphSize();
if (size == 0)
continue;
result += size * (n - size) * (n - size - 1);
}
System.out.println(result);
}
private static class Node {
Set<Node> neighbors;
boolean visited;
Node() {
neighbors = new HashSet<Node>();
visited = false;
}
int connectedGraphSize() {
if (visited)
return 0;
visited = true;
int sum = 1;
for (Node neighbor : neighbors)
sum += neighbor.connectedGraphSize();
return sum;
}
}
}
| Java | ["4\n1 2 4\n3 1 2\n1 4 7", "4\n1 2 4\n1 3 47\n1 4 7447"] | 2 seconds | ["16", "24"] | NoteThe 16 triples of vertexes from the first sample are: (1,β2,β4),β(1,β4,β2),β(2,β1,β3),β(2,β1,β4),β(2,β3,β1),β(2,β3,β4),β(2,β4,β1),β(2,β4,β3),β(3,β2,β4),β(3,β4,β2),β(4,β1,β2),β(4,β1,β3),β(4,β2,β1),β(4,β2,β3),β(4,β3,β1),β(4,β3,β2).In the second sample all the triples should be counted: 4Β·3Β·2β=β24. | Java 6 | standard input | [
"combinatorics",
"dfs and similar",
"trees"
] | 6992db71923a01211b5073ee0f8a193a | The first line contains the single integer n (1ββ€βnββ€β105) β the number of tree vertexes. Next nβ-β1 lines contain three integers each: ui vi wi (1ββ€βui,βviββ€βn,β1ββ€βwiββ€β109) β the pair of vertexes connected by the edge and the edge's weight. | 1,900 | On the single line print the single number β the answer. Please do not use the %lld specificator to read or write 64-bit numbers in Π‘++. It is recommended to use the cin, cout streams or the %I64d specificator. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.