exec_outcome
stringclasses 1
value | code_uid
stringlengths 32
32
| file_name
stringclasses 111
values | prob_desc_created_at
stringlengths 10
10
| prob_desc_description
stringlengths 63
3.8k
| prob_desc_memory_limit
stringclasses 18
values | source_code
stringlengths 117
65.5k
| lang_cluster
stringclasses 1
value | prob_desc_sample_inputs
stringlengths 2
802
| prob_desc_time_limit
stringclasses 27
values | prob_desc_sample_outputs
stringlengths 2
796
| prob_desc_notes
stringlengths 4
3k
⌀ | lang
stringclasses 5
values | prob_desc_input_from
stringclasses 3
values | tags
sequencelengths 0
11
| src_uid
stringlengths 32
32
| prob_desc_input_spec
stringlengths 28
2.37k
⌀ | difficulty
int64 -1
3.5k
⌀ | prob_desc_output_spec
stringlengths 17
1.47k
⌀ | prob_desc_output_to
stringclasses 3
values | hidden_unit_tests
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PASSED | 12d655c6133ebda590fbb69f4ad06218 | train_110.jsonl | 1618839300 | Now you get Baby Ehab's first words: "Given an integer $$$n$$$, find the longest subsequence of $$$[1,2, \ldots, n-1]$$$ whose product is $$$1$$$ modulo $$$n$$$." Please solve the problem.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly all) elements. The product of an empty subsequence is equal to $$$1$$$. | 256 megabytes |
import java.util.*;
import java.lang.*;
import java.io.*;
public class C {
// *** ++
// +=-==+ +++=-
// +-:---==+ *+=----=
// +-:------==+ ++=------==
// =-----------=++=========================
// +--:::::---:-----============-=======+++====
// +---:..:----::-===============-======+++++++++
// =---:...---:-===================---===++++++++++
// +----:...:-=======================--==+++++++++++
// +-:------====================++===---==++++===+++++
// +=-----======================+++++==---==+==-::=++**+
// +=-----================---=======++=========::.:-+*****
// +==::-====================--: --:-====++=+===:..-=+*****
// +=---=====================-... :=..:-=+++++++++===++*****
// +=---=====+=++++++++++++++++=-:::::-====+++++++++++++*****+
// +=======++++++++++++=+++++++============++++++=======+******
// +=====+++++++++++++++++++++++++==++++==++++++=:... . .+****
// ++====++++++++++++++++++++++++++++++++++++++++-. ..-+****
// +======++++++++++++++++++++++++++++++++===+====:. ..:=++++
// +===--=====+++++++++++++++++++++++++++=========-::....::-=++*
// ====--==========+++++++==+++===++++===========--:::....:=++*
// ====---===++++=====++++++==+++=======-::--===-:. ....:-+++
// ==--=--====++++++++==+++++++++++======--::::...::::::-=+++
// ===----===++++++++++++++++++++============--=-==----==+++
// =--------====++++++++++++++++=====================+++++++
// =---------=======++++++++====+++=================++++++++
// -----------========+++++++++++++++=================+++++++
// =----------==========++++++++++=====================++++++++
// =====------==============+++++++===================+++==+++++
// =======------==========================================++++++
// created by : Nitesh Gupta
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
String[] scn = (br.readLine()).trim().split(" ");
long n = Integer.parseInt(scn[0]);
// int len = 1;
// HashSet<Integer> set = new HashSet<>();
// int temp = n;
// for (int i = 2; i <= Math.sqrt(n); i++) {
// while (n % i == 0) {
// set.add(i);
// n /= i;
// }
//
// }
// n = temp;
// sb.append("1 ");
// boolean pos = false;
// long prod = 1;
// for (int i = 2; i < n; i++) {
// if (fact(i, set)) {
// len += 1;
// sb.append(i + " ");
// prod *= i;
// prod %= n;
// if (prod == 1) {
// pos = true;
// break;
// }
// }
// }
// if (pos) {
// System.out.println(len);
// System.out.println(sb);
// } else {
// System.out.println("1\n1");
// }
long prod = 1;
ArrayList<Long> list = new ArrayList<>();
for (long i = n - 2; i >= 1; i--) {
if (gcd(i, n) == 1) {
list.add(i);
prod *= i;
prod %= n;
}
}
prod *= n - 1;
prod %= n;
if (prod == 1) {
list.add(n - 1);
}
Collections.sort(list);
System.out.println(list.size());
for (long ele : list)
sb.append(ele + " ");
System.out.println(sb);
return;
}
public static long gcd(long a, long b) {
if (a < b) {
return gcd(b, a);
}
if (b == 0)
return a;
return gcd(b, a % b);
}
public static boolean fact(int n, HashSet<Integer> set) {
for (int i = 2; i <= Math.sqrt(n); i++) {
while (n % i == 0) {
if (set.contains(i)) {
return false;
} else {
n /= i;
}
}
}
if (!set.contains(n))
return true;
return false;
}
public static ArrayList<Long> soe() {
int size = (int) (1e6);
ArrayList<Long> list = new ArrayList<>();
boolean[] arr = new boolean[size + 10];
for (int i = 2; i * i <= size; i++) {
if (arr[i])
continue;
for (int j = 2; j * i <= size; j++) {
arr[j * i] = true;
}
}
for (int i = 2; i <= size; i++) {
if (!arr[i])
list.add((long) i);
}
return list;
}
public static void sort(long[] arr) {
int n = arr.length;
for (int i = 0; i < n; i++) {
int idx = (int) Math.random() * n;
long temp = arr[i];
arr[i] = arr[idx];
arr[idx] = temp;
}
Arrays.sort(arr);
}
public static void sort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n; i++) {
int idx = (int) Math.random() * n;
int temp = arr[i];
arr[i] = arr[idx];
arr[idx] = temp;
}
Arrays.sort(arr);
}
public static void print(long[][] dp) {
for (long[] a : dp) {
for (long ele : a) {
System.out.print(ele + " ");
}
System.out.println();
}
}
public static void print(int[][] dp) {
for (int[] a : dp) {
for (int ele : a) {
System.out.print(ele + " ");
}
System.out.println();
}
}
public static void print(int[] dp) {
for (int ele : dp) {
System.out.print(ele + " ");
}
System.out.println();
}
public static void print(long[] dp) {
for (long ele : dp) {
System.out.print(ele + " ");
}
System.out.println();
}
}
| Java | ["5", "8"] | 1 second | ["3\n1 2 3", "4\n1 3 5 7"] | NoteIn the first example, the product of the elements is $$$6$$$ which is congruent to $$$1$$$ modulo $$$5$$$. The only longer subsequence is $$$[1,2,3,4]$$$. Its product is $$$24$$$ which is congruent to $$$4$$$ modulo $$$5$$$. Hence, the answer is $$$[1,2,3]$$$. | Java 8 | standard input | [
"greedy",
"number theory"
] | d55afdb4a83aebdfce5a62e4ec934adb | The only line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$). | 1,600 | The first line should contain a single integer, the length of the longest subsequence. The second line should contain the elements of the subsequence, in increasing order. If there are multiple solutions, you can print any. | standard output | |
PASSED | 7833f7f51baff767725948bc8be6ef84 | train_110.jsonl | 1618839300 | Now you get Baby Ehab's first words: "Given an integer $$$n$$$, find the longest subsequence of $$$[1,2, \ldots, n-1]$$$ whose product is $$$1$$$ modulo $$$n$$$." Please solve the problem.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly all) elements. The product of an empty subsequence is equal to $$$1$$$. | 256 megabytes | /*
bts songs to dance to:
ON
*/
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import static java.lang.System.out;
import java.util.*;
import java.io.*;
import java.math.*;
public class x1514C
{
public static void main(String hi[]) throws Exception
{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int N = Integer.parseInt(st.nextToken());
ArrayList<Integer> ls = new ArrayList<Integer>();
int cnt = 0;
long mod = 1L;
for(int v=1; v < N; v++)
if(gcd(v, N) == 1)
{
cnt++;
ls.add(v);
mod = (mod*v)%N;
}
if(mod > 1)
cnt--;
System.out.println(cnt);
StringBuilder sb = new StringBuilder();
for(int x: ls)
if(x != mod || x == 1)
sb.append(x+" ");
System.out.println(sb);
}
public static long gcd(long a, long b)
{
if(a > b)
{
long t = a;
a = b;
b = t;
}
if(a == 0L)
return b;
return gcd(b%a, a);
}
}
/*
split into N is even or odd case?
N is even:
product of all numbers MUST be odd
N is odd:
product of all numbers MUST be even
NECESSARY CONDITION: gcd(v, N) == 1
*/ | Java | ["5", "8"] | 1 second | ["3\n1 2 3", "4\n1 3 5 7"] | NoteIn the first example, the product of the elements is $$$6$$$ which is congruent to $$$1$$$ modulo $$$5$$$. The only longer subsequence is $$$[1,2,3,4]$$$. Its product is $$$24$$$ which is congruent to $$$4$$$ modulo $$$5$$$. Hence, the answer is $$$[1,2,3]$$$. | Java 8 | standard input | [
"greedy",
"number theory"
] | d55afdb4a83aebdfce5a62e4ec934adb | The only line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$). | 1,600 | The first line should contain a single integer, the length of the longest subsequence. The second line should contain the elements of the subsequence, in increasing order. If there are multiple solutions, you can print any. | standard output | |
PASSED | 97234107f487a38d4eb781e44f1b5a40 | train_110.jsonl | 1618839300 | Now you get Baby Ehab's first words: "Given an integer $$$n$$$, find the longest subsequence of $$$[1,2, \ldots, n-1]$$$ whose product is $$$1$$$ modulo $$$n$$$." Please solve the problem.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly all) elements. The product of an empty subsequence is equal to $$$1$$$. | 256 megabytes | import java.util.*;
import java.io.*;
public class C {
public static void main(String[] args) {
FastScanner sc = new FastScanner();
int n = sc.nextInt();
TreeSet<Long> list = new TreeSet<>();
long res = 1;
for(long i = 1; i < n; i++) {
if(gcd(i, n) == 1) {
res *= i; res %= n;
list.add(i);
}
}
if(res != 1) list.remove(res);
StringBuilder sb = new StringBuilder();
sb.append(list.size()+"\n");
for(long v: list) {
sb.append(v+" ");
}
sb.replace(sb.length()-1, sb.length(), "\n");
PrintWriter pw = new PrintWriter(System.out);
pw.println(sb.toString().trim());
pw.flush();
}
static long gcd(long a, long b) {
if(b > a) return gcd(b, a);
else if(b == 0) return a;
else return gcd(b, a % b);
}
static class FastScanner {
public BufferedReader reader;
public StringTokenizer tokenizer;
public FastScanner() {
reader = new BufferedReader(new InputStreamReader(System.in), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
try {
return reader.readLine();
} catch(IOException e) {
throw new RuntimeException(e);
}
}
}
}
| Java | ["5", "8"] | 1 second | ["3\n1 2 3", "4\n1 3 5 7"] | NoteIn the first example, the product of the elements is $$$6$$$ which is congruent to $$$1$$$ modulo $$$5$$$. The only longer subsequence is $$$[1,2,3,4]$$$. Its product is $$$24$$$ which is congruent to $$$4$$$ modulo $$$5$$$. Hence, the answer is $$$[1,2,3]$$$. | Java 8 | standard input | [
"greedy",
"number theory"
] | d55afdb4a83aebdfce5a62e4ec934adb | The only line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$). | 1,600 | The first line should contain a single integer, the length of the longest subsequence. The second line should contain the elements of the subsequence, in increasing order. If there are multiple solutions, you can print any. | standard output | |
PASSED | e60cea67c27b336ba4f02f60594ef20b | train_110.jsonl | 1618839300 | Now you get Baby Ehab's first words: "Given an integer $$$n$$$, find the longest subsequence of $$$[1,2, \ldots, n-1]$$$ whose product is $$$1$$$ modulo $$$n$$$." Please solve the problem.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly all) elements. The product of an empty subsequence is equal to $$$1$$$. | 256 megabytes | import java.util.Scanner;
public class C1514 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int N = in.nextInt();
boolean[] include = new boolean[N+1];
long product = 1;
for (int n=1; n<N; n++) {
if (gcd(n, N) == 1) {
include[n] = true;
product *= n;
product %= N;
}
}
if (product != 1) {
include[(int) product] = false;
}
StringBuilder out = new StringBuilder();
int count = 0;
for (int n=1; n<N; n++) {
if (include[n]) {
out.append(n).append(' ');
count++;
}
}
System.out.println(count);
System.out.println(out);
}
static int gcd(int a, int b) {
return (b == 0) ? a : gcd(b, a%b);
}
}
| Java | ["5", "8"] | 1 second | ["3\n1 2 3", "4\n1 3 5 7"] | NoteIn the first example, the product of the elements is $$$6$$$ which is congruent to $$$1$$$ modulo $$$5$$$. The only longer subsequence is $$$[1,2,3,4]$$$. Its product is $$$24$$$ which is congruent to $$$4$$$ modulo $$$5$$$. Hence, the answer is $$$[1,2,3]$$$. | Java 8 | standard input | [
"greedy",
"number theory"
] | d55afdb4a83aebdfce5a62e4ec934adb | The only line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$). | 1,600 | The first line should contain a single integer, the length of the longest subsequence. The second line should contain the elements of the subsequence, in increasing order. If there are multiple solutions, you can print any. | standard output | |
PASSED | 64c70b3e918e92f060243f02f7d5f9c1 | train_110.jsonl | 1618839300 | Now you get Baby Ehab's first words: "Given an integer $$$n$$$, find the longest subsequence of $$$[1,2, \ldots, n-1]$$$ whose product is $$$1$$$ modulo $$$n$$$." Please solve the problem.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly all) elements. The product of an empty subsequence is equal to $$$1$$$. | 256 megabytes | import java.io.*;
import java.util.*;
import java.util.function.*;
public class Product1ModuloN {
public static void solve(FastIO io) {
final int N = io.nextInt();
IntList coprimes = new IntList();
long currMod = 1;
for (int i = 2; i < N; ++i) {
if (gcd(i, N) == 1) {
coprimes.add(i);
currMod = (currMod * i) % N;
}
}
coprimes.remove(Math.toIntExact(currMod));
coprimes.insert(0, 1);
io.println(coprimes.size());
io.printlnArray(coprimes.toArray());
}
/**
* Computes the GCD (greatest common denominator) between two numbers.
*/
public static int gcd(int a, int b) {
if (a < b)
return gcd(b, a);
int r = a % b;
if (r == 0)
return b;
return gcd(b, r);
}
public static class IntList {
public int[] arr;
public int pos;
public IntList(int capacity) {
this.arr = new int[capacity];
}
public IntList() {
this(10);
}
public IntList(IntList other) {
this.arr = Arrays.copyOfRange(other.arr, 0, other.pos);
this.pos = other.pos;
}
public void add(int x) {
if (pos >= arr.length) {
resize(arr.length << 1);
}
arr[pos++] = x;
}
public void insert(int i, int x) {
if (pos >= arr.length) {
resize(arr.length << 1);
}
System.arraycopy(arr, i, arr, i + 1, pos++ - i);
arr[i] = x;
}
public int get(int i) {
return arr[i];
}
public void set(int i, int x) {
arr[i] = x;
}
public void clear() {
pos = 0;
}
public int size() {
return pos;
}
public int last() {
return arr[pos - 1];
}
public int removeLast() {
return arr[--pos];
}
public boolean remove(int x) {
for (int i = 0; i < pos; ++i) {
if (arr[i] == x) {
System.arraycopy(arr, i + 1, arr, i, --pos - i);
return true;
}
}
return false;
}
public void removeAt(int i) {
System.arraycopy(arr, i + 1, arr, i, --pos - i);
}
public IntList subList(int fromIndex, int toIndexExclusive) {
IntList lst = new IntList();
lst.arr = Arrays.copyOfRange(arr, fromIndex, toIndexExclusive);
lst.pos = toIndexExclusive - fromIndex;
return lst;
}
public void forEach(IntConsumer consumer) {
for (int i = 0; i < pos; ++i) {
consumer.accept(arr[i]);
}
}
public int[] toArray() {
return Arrays.copyOf(arr, pos);
}
private void resize(int newCapacity) {
arr = Arrays.copyOf(arr, newCapacity);
}
public static IntList of(int... items) {
IntList lst = new IntList(items.length);
System.arraycopy(items, 0, lst.arr, 0, items.length);
lst.pos = items.length;
return lst;
}
}
public static class FastIO {
private InputStream reader;
private PrintWriter writer;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastIO(InputStream r, OutputStream w) {
reader = r;
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w)));
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = reader.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
// TODO: read this byte-by-byte like the other read functions.
public double nextDouble() {
return Double.parseDouble(nextString());
}
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;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printArray(long[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printlnArray(int[] arr) {
printArray(arr);
writer.println();
}
public void printlnArray(long[] arr) {
printArray(arr);
writer.println();
}
public void printf(String format, Object... args) {
print(String.format(format, args));
}
public void flush() {
writer.flush();
}
}
public static void main(String[] args) {
FastIO io = new FastIO(System.in, System.out);
solve(io);
io.flush();
}
} | Java | ["5", "8"] | 1 second | ["3\n1 2 3", "4\n1 3 5 7"] | NoteIn the first example, the product of the elements is $$$6$$$ which is congruent to $$$1$$$ modulo $$$5$$$. The only longer subsequence is $$$[1,2,3,4]$$$. Its product is $$$24$$$ which is congruent to $$$4$$$ modulo $$$5$$$. Hence, the answer is $$$[1,2,3]$$$. | Java 8 | standard input | [
"greedy",
"number theory"
] | d55afdb4a83aebdfce5a62e4ec934adb | The only line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$). | 1,600 | The first line should contain a single integer, the length of the longest subsequence. The second line should contain the elements of the subsequence, in increasing order. If there are multiple solutions, you can print any. | standard output | |
PASSED | 13d5641206c686320314f817e2ba21e3 | train_110.jsonl | 1618839300 | Now you get Baby Ehab's first words: "Given an integer $$$n$$$, find the longest subsequence of $$$[1,2, \ldots, n-1]$$$ whose product is $$$1$$$ modulo $$$n$$$." Please solve the problem.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly all) elements. The product of an empty subsequence is equal to $$$1$$$. | 256 megabytes | import java.util.*;
import java.io.*;
public class C{
static FastScanner fs = null;
public static void main(String[] args) {
fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int t = 1;
while (t-->0) {
long pr = (long)1;
int n = fs.nextInt();
ArrayList<Integer> list = new ArrayList<>();
for(int i=1;i<n;i++){
if(gcd(i,n)==1){
list.add(i);
pr*=(long)i;
pr%=n;
}
}
if(pr==(long)1){
out.println(list.size());
for(Integer p : list){
out.print(p+" ");
}
}
else{
out.println(list.size()-1);
for(Integer p : list){
if((long)p==pr)
continue;
out.print(p+" ");
}
}
out.println();
}
out.close();
}
static int gcd(int a,int b){
if(b==0)
return a;
return gcd(b,a%b);
}
static void sort(int[] a) {
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static 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[] readArray(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());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
} | Java | ["5", "8"] | 1 second | ["3\n1 2 3", "4\n1 3 5 7"] | NoteIn the first example, the product of the elements is $$$6$$$ which is congruent to $$$1$$$ modulo $$$5$$$. The only longer subsequence is $$$[1,2,3,4]$$$. Its product is $$$24$$$ which is congruent to $$$4$$$ modulo $$$5$$$. Hence, the answer is $$$[1,2,3]$$$. | Java 8 | standard input | [
"greedy",
"number theory"
] | d55afdb4a83aebdfce5a62e4ec934adb | The only line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$). | 1,600 | The first line should contain a single integer, the length of the longest subsequence. The second line should contain the elements of the subsequence, in increasing order. If there are multiple solutions, you can print any. | standard output | |
PASSED | 6c9d01754a5cc004b62a7a77c6960f75 | train_110.jsonl | 1618839300 | Now you get Baby Ehab's first words: "Given an integer $$$n$$$, find the longest subsequence of $$$[1,2, \ldots, n-1]$$$ whose product is $$$1$$$ modulo $$$n$$$." Please solve the problem.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly all) elements. The product of an empty subsequence is equal to $$$1$$$. | 256 megabytes | import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class JaiShreeRam{
static Scanner in=new Scanner();
static long systemTime;
static long mod = 1000000007;
static ArrayList<ArrayList<Integer>> adj;
static int seive[]=new int[1000001];
static long C[][];
static int fen[]=new int[4*100005];
static long nt=0;
static ArrayList<Integer> ans=new ArrayList<>();
public static void main(String[] args) throws Exception{
int z=1;
for(int test=1;test<=z;test++) {
//setTime();
solve();
//printTime();
//printMemory();
}
}
static void solve() {
int n=in.readInt();
TreeSet<Integer> st=new TreeSet<>();
long p=1;
for(int i=1;i<n;i++) {
if(gcd(n,i)==1) {
st.add(i);
p*=i;
p%=n;
}
}
if(p!=1) {
st.remove(new Integer((int)p));
}
print(st.size());
for(int i:st){
System.out.print(i+" ");
}
print("");
}
static long pow(long n, long m) {
if(m==0)
return 1;
else if(m==1)
return n;
else {
long r=pow(n,m/2);
if(m%2==0)
return (r*r);
else
return (r*r*n);
}
}
static long maxsumsub(ArrayList<Long> al) {
long max=0;
long sum=0;
for(int i=0;i<al.size();i++) {
sum+=al.get(i);
if(sum<0) {
sum=0;
}
max=Math.max(max,sum);
}
return max;
}
static long abs(long a) {
return Math.abs(a);
}
static void ncr(int n, int k){
C= new long[n + 1][k + 1];
int i, j;
for (i = 0; i <= n; i++) {
for (j = 0; j <= Math.min(i, k); j++) {
if (j == 0 || j == i)
C[i][j] = 1;
else
C[i][j] = C[i - 1][j - 1] + C[i - 1][j];
}
}
}
static boolean isPalin(String s) {
int i=0,j=s.length()-1;
while(i<=j) {
if(s.charAt(i)!=s.charAt(j)) {
return false;
}
i++;
j--;
}
return true;
}
static int knapsack(int W, int wt[],int val[], int n){
int []dp = new int[W + 1];
for (int i = 1; i < n + 1; i++) {
for (int w = W; w >= 0; w--) {
if (wt[i - 1] <= w) {
dp[w] = Math.max(dp[w],dp[w - wt[i - 1]] + val[i - 1]);
}
}
}
return dp[W];
}
static void seive() {
Arrays.fill(seive, 1);
seive[0]=0;
seive[1]=0;
for(int i=2;i*i<1000001;i++) {
if(seive[i]==1) {
for(int j=i*i;j<1000001;j+=i) {
if(seive[j]==1) {
seive[j]=0;
}
}
}
}
}
static void sort(int[] a) {
ArrayList<Integer> l=new ArrayList<>();
for (int i:a)
l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++)
a[i]=l.get(i);
}
static void sort(long[] a) {
ArrayList<Long> l=new ArrayList<>();
for (long i:a)
l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++)
a[i]=l.get(i);
}
static int[] nia(int n){
int[] arr= new int[n];
int i=0;
while(i<n){
arr[i++]=in.readInt();
}
return arr;
}
static long[] nla(int n){
long[] arr= new long[n];
int i=0;
while(i<n){
arr[i++]=in.readLong();
}
return arr;
}
static int[] nia1(int n){
int[] arr= new int[n+1];
int i=1;
while(i<=n){
arr[i++]=in.readInt();
}
return arr;
}
static Integer[] nIa(int n){
Integer[] arr= new Integer[n];
int i=0;
while(i<n){
arr[i++]=in.readInt();
}
return arr;
}
static Long[] nLa(int n){
Long[] arr= new Long[n];
int i=0;
while(i<n){
arr[i++]=in.readLong();
}
return arr;
}
static long gcd(long a, long b) {
if (b==0) return a;
return gcd(b, a%b);
}
static void print(long i) {
System.out.println(i);
}
static void print(Object o) {
System.out.println(o);
}
static void print(int a[]) {
for(int i:a) {
System.out.print(i+" ");
}
System.out.println();
}
static void print(long a[]) {
for(long i:a) {
System.out.print(i+" ");
}
System.out.println();
}
static void print(ArrayList<Long> a) {
for(long i:a) {
System.out.print(i+" ");
}
System.out.println();
}
static void print(Object a[]) {
for(Object i:a) {
System.out.print(i+" ");
}
System.out.println();
}
static void setTime() {
systemTime = System.currentTimeMillis();
}
static void printTime() {
System.err.println("Time consumed: " + (System.currentTimeMillis() - systemTime));
}
static void printMemory() {
System.err.println("Memory consumed: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1000 + "kb");
}
static class Scanner{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String readString() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
double readDouble() {
return Double.parseDouble(readString());
}
int readInt() {
return Integer.parseInt(readString());
}
long readLong() {
return Long.parseLong(readString());
}
}
} | Java | ["5", "8"] | 1 second | ["3\n1 2 3", "4\n1 3 5 7"] | NoteIn the first example, the product of the elements is $$$6$$$ which is congruent to $$$1$$$ modulo $$$5$$$. The only longer subsequence is $$$[1,2,3,4]$$$. Its product is $$$24$$$ which is congruent to $$$4$$$ modulo $$$5$$$. Hence, the answer is $$$[1,2,3]$$$. | Java 8 | standard input | [
"greedy",
"number theory"
] | d55afdb4a83aebdfce5a62e4ec934adb | The only line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$). | 1,600 | The first line should contain a single integer, the length of the longest subsequence. The second line should contain the elements of the subsequence, in increasing order. If there are multiple solutions, you can print any. | standard output | |
PASSED | b7d3e3805b19ad54cb8f1bf2e77ecd61 | train_110.jsonl | 1618839300 | Now you get Baby Ehab's first words: "Given an integer $$$n$$$, find the longest subsequence of $$$[1,2, \ldots, n-1]$$$ whose product is $$$1$$$ modulo $$$n$$$." Please solve the problem.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly all) elements. The product of an empty subsequence is equal to $$$1$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static int i, j, k, n, m, t, y, x, sum = 0;
static long mod = 1000000007;
static FastScanner fs = new FastScanner();
static PrintWriter out = new PrintWriter(System.out);
static String str;
static long ans;
public static void main(String[] args) {
t =1;
while(t-- >0){
n = fs.nextInt();
long p = 1;
long ans=0;
List<Integer> ansList = new ArrayList<>();
for(i=0;i<n;i++){
if(gcd(n,i)==1) {
p *= i;
ans++;
ansList.add(i);
p%=n;
}
}
if(p%n!=1) {
ans--;
for(i=0;i<ansList.size();i++){
if(ansList.get(i)==p%n)
ansList.remove(i);
}
}
out.println(ans);
for(i=0;i<ansList.size();i++)
out.print(ansList.get(i)+" ");
}
out.close();
}
/**
* Returns the gretaest index of closest element less than x in arr
* returns -1 if all elemets are greater
*
*/
public static int lowerBound(int x, List<Integer> arr, int l, int r){
if(arr.get(l)>=x)
return -1;
if(arr.get(r)<x)
return r;
int mid = (l+r)/2;
if(arr.get(mid)<x && arr.get(mid+1)>x)
return mid;
if(arr.get(mid)>=x)
return lowerBound(x,arr,l,mid-1);
return lowerBound(x,arr,mid+1,r);
}
/**
* Returns the lowest index of closest element greater than or equal to x in arr
* returns -1 if all elements are lesser
*
*/
public static int upperBound(int x, List<Integer> arr, int l, int r){
if(arr.get(r) <=x)
return -1;
if(arr.get(l)>x)
return l;
int mid = (l+r)/2;
if(arr.get(mid)>x && arr.get(mid-1)<=x)
return mid;
if(arr.get(mid)<=x)
return upperBound(x,arr,mid+1,r);
return upperBound(x,arr,l,mid-1);
}
/**
* Returns the index of element if present else -1.
*
*/
public static int binSearch(int x, List<Integer> arr){
int y = Collections.binarySearch(arr, x);
if(y<0)
return -1;
return y;
}
/**
* Gets prime factorisation of a number in list of pairs.
* x is the factor and y is the occurrence.
*
*/
public static List<Pair> primeFactorization(int num){
List<Pair> ans = new ArrayList<>();
for(int i=2;i*i<=num;i++){
if(num % i ==0){
int count = 0;
while(num%i==0){
count++;
num=num/i;
}
ans.add(new Pair(i,count));
}
}
if(num!=1)
ans.add(new Pair(num, 1));
return ans;
}
/*static long nck(int n , int k){
long a = fact[n];
long b = modInv(fact[k]);
b*= modInv(fact[n-k]);
b%=mod;
return (a*b)%mod;
}
static void populateFact(){
fact[0]=1;
fact[1] = 1;
for(i=2;i<300005;i++){
fact[i]=i*fact[i-1];
fact[i]%=mod;
}
}
*/
static int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static long exp(long base, long pow) {
if (pow == 0) return 1;
long half = exp(base, pow / 2);
if (pow % 2 == 0) return mul(half, half);
return mul(half, mul(half, base));
}
static long mul(long a, long b) {
return ((a % mod) * (b % mod)) % mod;
}
static long add(long a, long b) {
return ((a % mod) + (b % mod)) % mod;
}
static long modInv(long x) {
return exp(x, mod - 2);
}
static void ruffleSort(int[] a) {
//ruffle
int n = a.length;
Random r = new Random();
for (int i = 0; i < a.length; i++) {
int oi = r.nextInt(n), temp = a[i];
a[i] = a[oi];
a[oi] = temp;
}
//then sort
Arrays.sort(a);
}
static void ruffleSort(long[] a) {
//ruffle
int n = a.length;
Random r = new Random();
for (int i = 0; i < a.length; i++) {
int oi = r.nextInt(n);
long temp = a[i];
a[i] = a[oi];
a[oi] = temp;
}
Arrays.sort(a);
}
static 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[] readArray(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());
}
}
static class Pair implements Comparable<Pair> {
public int x, y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Pair o) {
if (x == o.x)
return Integer.compare(y, o.y);
return Integer.compare(x, o.x);
}
}
} | Java | ["5", "8"] | 1 second | ["3\n1 2 3", "4\n1 3 5 7"] | NoteIn the first example, the product of the elements is $$$6$$$ which is congruent to $$$1$$$ modulo $$$5$$$. The only longer subsequence is $$$[1,2,3,4]$$$. Its product is $$$24$$$ which is congruent to $$$4$$$ modulo $$$5$$$. Hence, the answer is $$$[1,2,3]$$$. | Java 8 | standard input | [
"greedy",
"number theory"
] | d55afdb4a83aebdfce5a62e4ec934adb | The only line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$). | 1,600 | The first line should contain a single integer, the length of the longest subsequence. The second line should contain the elements of the subsequence, in increasing order. If there are multiple solutions, you can print any. | standard output | |
PASSED | 86bc2a8e4d09e7b096f83fa73fb53284 | train_110.jsonl | 1618839300 | Now you get Baby Ehab's first words: "Given an integer $$$n$$$, find the longest subsequence of $$$[1,2, \ldots, n-1]$$$ whose product is $$$1$$$ modulo $$$n$$$." Please solve the problem.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly all) elements. The product of an empty subsequence is equal to $$$1$$$. | 256 megabytes | //package com.company;
import java.util.*;
import java.io.*;
public class Product1ModuloN {
private static int gcd(int a, int b) {
return b== 0 ? a : gcd(b, a % b);
}
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
long prod = 1; int count = 0;
ArrayList<Integer> nums = new ArrayList<>();
for(int i = 1; i <= n; i++) {
if(gcd(i, n) == 1) {
prod *= i; prod %= n; count++;
nums.add(i);
}
}
if(prod != 1) count--;
System.out.println(count);
StringBuilder ans = new StringBuilder("");
for(int i : nums) {
if(prod != 1 && i != prod) {
ans.append(i);
if(i != nums.get(nums.size()-1)) ans.append(" ");
}
else if(prod == 1) {
ans.append(i);
if(i != nums.get(nums.size()-1)) ans.append(" ");
}
}
System.out.println(ans);
br.close();
}
} | Java | ["5", "8"] | 1 second | ["3\n1 2 3", "4\n1 3 5 7"] | NoteIn the first example, the product of the elements is $$$6$$$ which is congruent to $$$1$$$ modulo $$$5$$$. The only longer subsequence is $$$[1,2,3,4]$$$. Its product is $$$24$$$ which is congruent to $$$4$$$ modulo $$$5$$$. Hence, the answer is $$$[1,2,3]$$$. | Java 8 | standard input | [
"greedy",
"number theory"
] | d55afdb4a83aebdfce5a62e4ec934adb | The only line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$). | 1,600 | The first line should contain a single integer, the length of the longest subsequence. The second line should contain the elements of the subsequence, in increasing order. If there are multiple solutions, you can print any. | standard output | |
PASSED | c3c0824735d45913e237122619f693b3 | train_110.jsonl | 1618839300 | Now you get Baby Ehab's first words: "Given an integer $$$n$$$, find the longest subsequence of $$$[1,2, \ldots, n-1]$$$ whose product is $$$1$$$ modulo $$$n$$$." Please solve the problem.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly all) elements. The product of an empty subsequence is equal to $$$1$$$. | 256 megabytes | import java.util.Scanner;
import java.util.TreeSet;
public class Product1ModN {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
long N = scan.nextLong();
TreeSet<Long> ans = new TreeSet<>();
long p = 1;
for(long i = 1; i < N; i++)
if(gcd(i, N) == 1) {
ans.add(i);
p = (p%N * i%N)%N;
}
if(p!=1)
ans.remove(p);
System.out.println(ans.size());
for(long k : ans)
System.out.print(k + " ");
System.out.println();
}
static long gcd(long a, long b) {
if(b==0)
return a;
return gcd(b, a%b);
}
}
| Java | ["5", "8"] | 1 second | ["3\n1 2 3", "4\n1 3 5 7"] | NoteIn the first example, the product of the elements is $$$6$$$ which is congruent to $$$1$$$ modulo $$$5$$$. The only longer subsequence is $$$[1,2,3,4]$$$. Its product is $$$24$$$ which is congruent to $$$4$$$ modulo $$$5$$$. Hence, the answer is $$$[1,2,3]$$$. | Java 8 | standard input | [
"greedy",
"number theory"
] | d55afdb4a83aebdfce5a62e4ec934adb | The only line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$). | 1,600 | The first line should contain a single integer, the length of the longest subsequence. The second line should contain the elements of the subsequence, in increasing order. If there are multiple solutions, you can print any. | standard output | |
PASSED | 070239b5a6a51b2340d90e511c3ef628 | train_110.jsonl | 1618839300 | Now you get Baby Ehab's first words: "Given an integer $$$n$$$, find the longest subsequence of $$$[1,2, \ldots, n-1]$$$ whose product is $$$1$$$ modulo $$$n$$$." Please solve the problem.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly all) elements. The product of an empty subsequence is equal to $$$1$$$. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author cpp
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
CProduct1ModuloN solver = new CProduct1ModuloN();
solver.solve(1, in, out);
out.close();
}
static class CProduct1ModuloN {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int n = in.nextInt();
Set<Integer> set = new TreeSet<>();
set.add(1);
int runningProduct = 1;
for (int i = 2; i < n; i++) {
if (gcd(n, i) == 1) {
runningProduct = mul(runningProduct, i, n);
set.add(i);
}
}
if (runningProduct != 1) {
set.remove(runningProduct);
}
out.println(set.size());
set.forEach(i -> out.print(i + " "));
out.print("\n");
}
public int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
public int mul(int a, int b, int mod) {
return (int) ((1L * a * b) % mod);
}
}
}
| Java | ["5", "8"] | 1 second | ["3\n1 2 3", "4\n1 3 5 7"] | NoteIn the first example, the product of the elements is $$$6$$$ which is congruent to $$$1$$$ modulo $$$5$$$. The only longer subsequence is $$$[1,2,3,4]$$$. Its product is $$$24$$$ which is congruent to $$$4$$$ modulo $$$5$$$. Hence, the answer is $$$[1,2,3]$$$. | Java 8 | standard input | [
"greedy",
"number theory"
] | d55afdb4a83aebdfce5a62e4ec934adb | The only line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$). | 1,600 | The first line should contain a single integer, the length of the longest subsequence. The second line should contain the elements of the subsequence, in increasing order. If there are multiple solutions, you can print any. | standard output | |
PASSED | 9741a8bb1830427e69c40c727f990ca0 | train_110.jsonl | 1618839300 | Now you get Baby Ehab's first words: "Given an integer $$$n$$$, find the longest subsequence of $$$[1,2, \ldots, n-1]$$$ whose product is $$$1$$$ modulo $$$n$$$." Please solve the problem.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly all) elements. The product of an empty subsequence is equal to $$$1$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class productmodulon {
public static void main (String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
long n = Long.parseLong(st.nextToken());
int seq = 1;
long prod = 1;
for (int i = 2; i <= n - 1; i++) {
if (gcd(n,i) == 1) {
seq++;
prod *= i;
prod %= n;
}
}
long modn = prod;
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1);
for (int i = 2; i <= n; i++) {
if (gcd(n,i) == 1) {
if (i != modn) {
list.add(i);
}
}
}
System.out.println(list.size());
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i) + " ");
}
System.out.println();
}
static long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
}
| Java | ["5", "8"] | 1 second | ["3\n1 2 3", "4\n1 3 5 7"] | NoteIn the first example, the product of the elements is $$$6$$$ which is congruent to $$$1$$$ modulo $$$5$$$. The only longer subsequence is $$$[1,2,3,4]$$$. Its product is $$$24$$$ which is congruent to $$$4$$$ modulo $$$5$$$. Hence, the answer is $$$[1,2,3]$$$. | Java 8 | standard input | [
"greedy",
"number theory"
] | d55afdb4a83aebdfce5a62e4ec934adb | The only line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$). | 1,600 | The first line should contain a single integer, the length of the longest subsequence. The second line should contain the elements of the subsequence, in increasing order. If there are multiple solutions, you can print any. | standard output | |
PASSED | 9423b816aa3d9839822337c87851c9a4 | train_110.jsonl | 1618839300 | Now you get Baby Ehab's first words: "Given an integer $$$n$$$, find the longest subsequence of $$$[1,2, \ldots, n-1]$$$ whose product is $$$1$$$ modulo $$$n$$$." Please solve the problem.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly all) elements. The product of an empty subsequence is equal to $$$1$$$. | 256 megabytes | import java.util.*;
import java.io.*;
public class Omar {
static Scanner sc=new Scanner(System.in);
static PrintWriter pw=new PrintWriter(System.out);
public static long GCD(long a, long b) {
if (b == 0)
return a;
if (a == 0)
return b;
return (a > b) ? GCD(a % b, b) : GCD(a, b % a);
}
public static void main(String[] args) throws IOException, InterruptedException {
int n=sc.nextInt();
TreeSet<Integer> ans=new TreeSet<>();
long mul=1;
ans.add(1);
for(int i=2;i<n;i++) {
if(GCD(n, i)==1) {
ans.add(i);
mul=(mul*i)%n;
}
}
if(mul!=1) {
ans.remove((int)mul);
}
pw.println(ans.size());
while(!ans.isEmpty())
pw.print(ans.pollFirst()+" ");
pw.flush();
}
static class pair implements Comparable<pair> {
long x;
long y;
public pair(long x, long 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 Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public String readAllLines(BufferedReader reader) throws IOException {
StringBuilder content = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
content.append(line);
content.append(System.lineSeparator());
}
return content.toString();
}
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 long[] nextlongArray(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public Long[] nextLongArray(int n) throws IOException {
Long[] a = new Long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public int[] nextIntArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public Integer[] nextIntegerArray(int n) throws IOException {
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
| Java | ["5", "8"] | 1 second | ["3\n1 2 3", "4\n1 3 5 7"] | NoteIn the first example, the product of the elements is $$$6$$$ which is congruent to $$$1$$$ modulo $$$5$$$. The only longer subsequence is $$$[1,2,3,4]$$$. Its product is $$$24$$$ which is congruent to $$$4$$$ modulo $$$5$$$. Hence, the answer is $$$[1,2,3]$$$. | Java 8 | standard input | [
"greedy",
"number theory"
] | d55afdb4a83aebdfce5a62e4ec934adb | The only line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$). | 1,600 | The first line should contain a single integer, the length of the longest subsequence. The second line should contain the elements of the subsequence, in increasing order. If there are multiple solutions, you can print any. | standard output | |
PASSED | b71667cff05d16b0793dbb2423c49558 | train_110.jsonl | 1618839300 | Now you get Baby Ehab's first words: "Given an integer $$$n$$$, find the longest subsequence of $$$[1,2, \ldots, n-1]$$$ whose product is $$$1$$$ modulo $$$n$$$." Please solve the problem.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly all) elements. The product of an empty subsequence is equal to $$$1$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class new1{
static int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
public static void main(String[] args) throws IOException{
FastReader s = new FastReader();
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));
int t = 1;//s.nextInt();
for(int i = 0; i < t; i++) {
int n = s.nextInt();
long ans = 1; int prev = 1;
ArrayList<Integer> a1 = new ArrayList<Integer>();
for(int j = 1; j < n; j++) {
if(gcd(n, j) == 1) {
ans = (ans * j) % n;
prev = j;
a1.add(j);
}
}
//System.out.println(a1.toString());
if(ans != 1) {
a1.remove(a1.size() - 1);
}
System.out.println(a1.size());
for(int j = 0; j < a1.size(); j++ ) {
System.out.print(a1.get(j) + " ");
}
System.out.println();
}
output.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();
}
public int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}} | Java | ["5", "8"] | 1 second | ["3\n1 2 3", "4\n1 3 5 7"] | NoteIn the first example, the product of the elements is $$$6$$$ which is congruent to $$$1$$$ modulo $$$5$$$. The only longer subsequence is $$$[1,2,3,4]$$$. Its product is $$$24$$$ which is congruent to $$$4$$$ modulo $$$5$$$. Hence, the answer is $$$[1,2,3]$$$. | Java 8 | standard input | [
"greedy",
"number theory"
] | d55afdb4a83aebdfce5a62e4ec934adb | The only line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$). | 1,600 | The first line should contain a single integer, the length of the longest subsequence. The second line should contain the elements of the subsequence, in increasing order. If there are multiple solutions, you can print any. | standard output | |
PASSED | c945480fdeff08be0332e16e4fbe36dc | train_110.jsonl | 1618839300 | Now you get Baby Ehab's first words: "Given an integer $$$n$$$, find the longest subsequence of $$$[1,2, \ldots, n-1]$$$ whose product is $$$1$$$ modulo $$$n$$$." Please solve the problem.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly all) elements. The product of an empty subsequence is equal to $$$1$$$. | 256 megabytes | import java.util.*;
import java.io.*;
// import java.lang.*;
// import java.math.*;
public class Codeforces {
static FastReader sc=new FastReader();
static PrintWriter out=new PrintWriter(System.out);
static long mod=1000000007;
// static long mod=998244353;
static int MAX=Integer.MAX_VALUE;
static int MIN=Integer.MIN_VALUE;
static long MAXL=Long.MAX_VALUE;
static long MINL=Long.MIN_VALUE;
static ArrayList<Integer> graph[];
public static void main (String[] args) throws java.lang.Exception
{
// code goes here
// int t=I();
// outer:while(t-->0)
// {
// }
int n=I();
int ans=0;
ArrayList<Integer> arr=new ArrayList<>();
for(int i=1;i<n;i++){
if(gcd(i,n)==1){
arr.add(i);
ans++;
}
}
long prod=1;
mod=n;
for(int i=0;i<arr.size();i++){
prod=mul(prod,arr.get(i));
}
if(prod==1){
out.println(ans);
for(int i:arr){
out.print(i+" ");
}out.println();
}else{
out.println(ans-1);
for(int i:arr){
if(i==prod)continue;
out.print(i+" ");
}out.println();
}
out.close();
}
public static class pair
{
long a;
long b;
public pair(long val,long index)
{
a=val;
b=index;
}
}
public static class myComp implements Comparator<pair>
{
//sort in ascending order.
public int compare(pair p1,pair p2)
{
if(p1.a==p2.a)
return 0;
else if(p1.a<p2.a)
return -1;
else
return 1;
}
//sort in descending order.
// public int compare(pair p1,pair p2)
// {
// if(p1.a==p2.a)
// return 0;
// else if(p1.a<p2.a)
// return 1;
// else
// return -1;
// }
}
public static long kadane(long a[],int n)
{
long max_sum=Long.MIN_VALUE,max_end=0;
for(int i=0;i<n;i++){
max_end+=a[i];
if(max_sum<max_end){max_sum=max_end;}
if(max_end<0){max_end=0;}
}
return max_sum;
}
public static void DFS(int s,boolean visited[])
{
visited[s]=true;
for(int i:graph[s]){
if(!visited[i]){
DFS(i,visited);
}
}
}
public static void setGraph(int n,int m)
{
graph=new ArrayList[n+1];
for(int i=0;i<=n;i++){
graph[i]=new ArrayList<>();
}
for(int i=0;i<m;i++){
int u=I(),v=I();
graph[u].add(v);
graph[v].add(u);
}
}
public static int BS(long a[],long x,int ii,int jj)
{
// int n=a.length;
int mid=0;
int i=ii,j=jj;
while(i<=j)
{
mid=(i+j)/2;
if(a[mid]<x){
i=mid+1;
}else if(a[mid]>x){
j=mid-1;
}else{
return mid;
}
}
return -1;
}
public static int lower_bound(int arr[],int s, int N, int X)
{
if(arr[N]<X)return N;
if(arr[0]>X)return -1;
int left=s,right=N;
while(left<right){
int mid=(left+right)/2;
if(arr[mid]==X)
return mid;
else if(arr[mid]>X){
if(mid>0 && arr[mid]>X && arr[mid-1]<=X){
return mid-1;
}else{
right=mid-1;
}
}else{
if(mid<N && arr[mid+1]>X && arr[mid]<=X){
return mid;
}else{
left=mid+1;
}
}
}
return left;
}
public static ArrayList<Integer> primeSieve(int n)
{
ArrayList<Integer> arr=new ArrayList<>();
boolean prime[] = new boolean[n + 1];
for (int i = 0; i <= n; i++)
prime[i] = true;
for (int p = 2; p * p <= n; p++)
{
if (prime[p] == true)
{
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
for (int i = 2; i <= n; i++)
{
if (prime[i] == true)
arr.add(i);
}
return arr;
}
// Fenwick / BinaryIndexed Tree USE IT - FenwickTree ft1=new FenwickTree(n);
public static class FenwickTree
{
int farr[];
int n;
public FenwickTree(int c)
{
n=c+1;
farr=new int[n];
}
// public void update_range(int l,int r,long p)
// {
// update(l,p);
// update(r+1,(-1)*p);
// }
public void update(int x,int p)
{
for(;x<=n;x+=x&(-x))
{
farr[x]+=p;
}
}
public long get(int x)
{
long ans=0;
for(;x>0;x-=x&(-x))
{
ans=ans+farr[x];
}
return ans;
}
}
//Disjoint Set Union
public static class DSU
{
int par[],rank[];
public DSU(int c)
{
par=new int[c+1];
rank=new int[c+1];
for(int i=0;i<=c;i++)
{
par[i]=i;
rank[i]=0;
}
}
public int find(int a)
{
if(a==par[a])
return a;
return par[a]=find(par[a]);
}
public void union(int a,int b)
{
int a_rep=find(a),b_rep=find(b);
if(a_rep==b_rep)
return;
if(rank[a_rep]<rank[b_rep])
par[a_rep]=b_rep;
else if(rank[a_rep]>rank[b_rep])
par[b_rep]=a_rep;
else
{
par[b_rep]=a_rep;
rank[a_rep]++;
}
}
}
//SEGMENT TREE CODE
// public static void segmentUpdate(int si,int ss,int se,int qs,int qe,long x)
// {
// if(ss>qe || se<qs)return;
// if(qs<=ss && qe>=se)
// {
// seg[si][0]+=1L;
// seg[si][1]+=x*x;
// seg[si][2]+=2*x;
// return;
// }
// int mid=(ss+se)/2;
// segmentUpdate(2*si+1,ss,mid,qs,qe,x);
// segmentUpdate(2*si+2,mid+1,se,qs,qe,x);
// }
// public static long segmentGet(int si,int ss,int se,int x,long f,long s,long t,long a[])
// {
// if(ss==se && ss==x)
// {
// f+=seg[si][0];
// s+=seg[si][1];
// t+=seg[si][2];
// long ans=a[x]+(f*((long)x+1L)*((long)x+1L))+s+(t*((long)x+1L));
// return ans;
// }
// int mid=(ss+se)/2;
// if(x>mid){
// return segmentGet(2*si+2,mid+1,se,x,f+seg[si][0],s+seg[si][1],t+seg[si][2],a);
// }else{
// return segmentGet(2*si+1,ss,mid,x,f+seg[si][0],s+seg[si][1],t+seg[si][2],a);
// }
// }
public static class myComp1 implements Comparator<pair1>
{
//sort in ascending order.
public int compare(pair1 p1,pair1 p2)
{
if(p1.a==p2.a)
return 0;
else if(p1.a<p2.a)
return -1;
else
return 1;
}
//sort in descending order.
// public int compare(pair p1,pair p2)
// {
// if(p1.a==p2.a)
// return 0;
// else if(p1.a<p2.a)
// return 1;
// else
// return -1;
// }
}
public static class pair1
{
long a;
long b;
public pair1(long val,long index)
{
a=val;
b=index;
}
}
public static ArrayList<pair1> mergeIntervals(ArrayList<pair1> arr)
{
//****************use this in main function-Collections.sort(arr,new myComp1());
ArrayList<pair1> a1=new ArrayList<>();
if(arr.size()<=1)
return arr;
a1.add(arr.get(0));
int i=1,j=0;
while(i<arr.size())
{
if(a1.get(j).b<arr.get(i).a)
{
a1.add(arr.get(i));
i++;
j++;
}
else if(a1.get(j).b>arr.get(i).a && a1.get(j).b>=arr.get(i).b)
{
i++;
}
else if(a1.get(j).b>=arr.get(i).a)
{
long a=a1.get(j).a;
long b=arr.get(i).b;
a1.remove(j);
a1.add(new pair1(a,b));
i++;
}
}
return a1;
}
public static boolean isPalindrome(String s,int n)
{
for(int i=0;i<=n/2;i++){
if(s.charAt(i)!=s.charAt(n-i-1)){
return false;
}
}
return true;
}
public static int gcd(int a,int b)
{
if(b==0)
return a;
else
return gcd(b,a%b);
}
public static long gcd(long a,long b)
{
if(b==0)
return a;
else
return gcd(b,a%b);
}
public static long fact(long n)
{
long fact=1;
for(long i=2;i<=n;i++){
fact=((fact%mod)*(i%mod))%mod;
}
return fact;
}
public static long fact(int n)
{
long fact=1;
for(int i=2;i<=n;i++){
fact=((fact%mod)*(i%mod))%mod;
}
return fact;
}
public static boolean isPrime(int n)
{
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
double sq=Math.sqrt(n);
for (int i = 5; i <= sq; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
public static boolean isPrime(long n)
{
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
double sq=Math.sqrt(n);
for (int i = 5; i <= sq; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
public static void printArray(long a[])
{
for(int i=0;i<a.length;i++){
out.print(a[i]+" ");
}
out.println();
}
public static void printArray(int a[])
{
for(int i=0;i<a.length;i++){
out.print(a[i]+" ");
}
out.println();
}
public static void printArray(pair a[])
{
for(int i=0;i<a.length;i++){
out.print(a[i].a+"->"+a[i].b+" ");
}
out.println();
}
public static void printArray(char a[])
{
for(int i=0;i<a.length;i++){
out.print(a[i]);
}
out.println();
}
public static void printArray(String a[])
{
for(int i=0;i<a.length;i++){
out.print(a[i]+" ");
}
out.println();
}
public static void printArray(boolean a[])
{
for(int i=0;i<a.length;i++){
out.print(a[i]+" ");
}
out.println();
}
public static void printArray(int a[][])
{
for(int i=0;i<a.length;i++){
for(int j=0;j<a[i].length;j++){
out.print(a[i][j]+" ");
}out.println();
}
}
public static void printArray(long a[][])
{
for(int i=0;i<a.length;i++){
for(int j=0;j<a[i].length;j++){
out.print(a[i][j]+" ");
}out.println();
}
}
public static void printArray(char a[][])
{
for(int i=0;i<a.length;i++){
for(int j=0;j<a[i].length;j++){
out.print(a[i][j]+" ");
}out.println();
}
}
public static void printArrayL(ArrayList<Long> arr)
{
for(int i=0;i<arr.size();i++){
out.print(arr.get(i)+" ");
}
out.println();
}
public static void printArrayI(ArrayList<Integer> arr)
{
for(int i=0;i<arr.size();i++){
out.print(arr.get(i)+" ");
}
out.println();
}
public static void printArrayS(ArrayList<String> arr)
{
for(int i=0;i<arr.size();i++){
out.print(arr.get(i)+" ");
}
out.println();
}
public static void printMapInt(HashMap<Integer,Integer> hm){
for(Map.Entry<Integer,Integer> e:hm.entrySet()){
out.println(e.getKey()+"->"+e.getValue());
}out.println();
}
public static void printMapLong(HashMap<Long,Long> hm){
for(Map.Entry<Long,Long> e:hm.entrySet()){
out.println(e.getKey()+"->"+e.getValue());
}out.println();
}
//Modular Arithmetic
public static long add(long a,long b)
{
a+=b;
if(a>=mod)a-=mod;
return a;
}
public static long sub(long a,long b)
{
a-=b;
if(a<0)a+=mod;
return a;
}
public static long mul(long a,long b)
{
return ((a%mod)*(b%mod))%mod;
}
public static long divide(long a,long b,long m)
{
a=mul(a,modInverse(b,m));
return a;
}
public static long modInverse(long a,long m)
{
int x=0,y=0;
own p=new own(x,y);
long g=gcdExt(a,m,p);
if(g!=1){
out.println("inverse does not exists");
return -1;
}else{
long res=((p.a%m)+m)%m;
return res;
}
}
public static long gcdExt(long a,long b,own p)
{
if(b==0){
p.a=1;
p.b=0;
return a;
}
int x1=0,y1=0;
own p1=new own(x1,y1);
long gcd=gcdExt(b,a%b,p1);
p.b=p1.a - (a/b) * p1.b;
p.a=p1.b;
return gcd;
}
public static long pwr(long m,long n)
{
long res=1;
m=m%mod;
if(m==0)
return 0;
while(n>0)
{
if((n&1)!=0)
{
res=(res*m)%mod;
}
n=n>>1;
m=(m*m)%mod;
}
return res;
}
public static class own
{
long a;
long b;
public own(long val,long index)
{
a=val;
b=index;
}
}
//Modular Airthmetic
public static void sort(int[] A)
{
int n = A.length;
Random rnd = new Random();
for(int i=0; i<n; ++i)
{
int tmp = A[i];
int randomPos = i + rnd.nextInt(n-i);
A[i] = A[randomPos];
A[randomPos] = tmp;
}
Arrays.sort(A);
}
public static void sort(char[] A)
{
int n = A.length;
Random rnd = new Random();
for(int i=0; i<n; ++i)
{
char tmp = A[i];
int randomPos = i + rnd.nextInt(n-i);
A[i] = A[randomPos];
A[randomPos] = tmp;
}
Arrays.sort(A);
}
public static void sort(long[] A)
{
int n = A.length;
Random rnd = new Random();
for(int i=0; i<n; ++i)
{
long tmp = A[i];
int randomPos = i + rnd.nextInt(n-i);
A[i] = A[randomPos];
A[randomPos] = tmp;
}
Arrays.sort(A);
}
public static int i(char ch){return Integer.parseInt(String.valueOf(ch));}
public static int I(){return sc.I();}
public static long L(){return sc.L();}
public static String S(){return sc.S();}
public static double D(){return sc.D();}
}
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 I(){
return Integer.parseInt(next());
}
long L(){
return Long.parseLong(next());
}
double D(){
return Double.parseDouble(next());
}
String S(){
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
| Java | ["5", "8"] | 1 second | ["3\n1 2 3", "4\n1 3 5 7"] | NoteIn the first example, the product of the elements is $$$6$$$ which is congruent to $$$1$$$ modulo $$$5$$$. The only longer subsequence is $$$[1,2,3,4]$$$. Its product is $$$24$$$ which is congruent to $$$4$$$ modulo $$$5$$$. Hence, the answer is $$$[1,2,3]$$$. | Java 8 | standard input | [
"greedy",
"number theory"
] | d55afdb4a83aebdfce5a62e4ec934adb | The only line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$). | 1,600 | The first line should contain a single integer, the length of the longest subsequence. The second line should contain the elements of the subsequence, in increasing order. If there are multiple solutions, you can print any. | standard output | |
PASSED | 6a6b6457c449d2d0e1077e205f82e446 | train_110.jsonl | 1618839300 | Now you get Baby Ehab's first words: "Given an integer $$$n$$$, find the longest subsequence of $$$[1,2, \ldots, n-1]$$$ whose product is $$$1$$$ modulo $$$n$$$." Please solve the problem.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly all) elements. The product of an empty subsequence is equal to $$$1$$$. | 256 megabytes |
import java.util.*;
//import com.sun.management.internal.GcInfoCompositeData;
import java.io.*;
public class Solution {
static FastScanner scr=new FastScanner();
// static Scanner scr=new Scanner(System.in);
static PrintStream out=new PrintStream(System.out);
static StringBuilder sb=new StringBuilder();
static class pair{
long x;int y;
pair(long x,int y){
this.x=x;this.y=y;
}
}
static class triplet{
long x;
long y;
long z;
triplet(long x,long y,long z){
this.x=x;
this.y=y;
this.z=z;
}
} static class DSU{
int []a=new int[26];
int []rank=new int[26];
void start() {
for(int i=0;i<26;i++) {
a[i]=i;
}
}
int find(int x) {
if(a[x]==x) {
return x;
}
return find(a[x]);
}
void union(int x,int y) {
int xx=find(x);
int yy=find(y);
a[xx]=yy;
}
}
static 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();
} long gcd(long a,long b){
if(b==0) {
return a;
}
return gcd(b,a%b);
}
int[] sort(int a[]) {
int multiplier = 1, len = a.length, max = Integer.MIN_VALUE;
int b[] = new int[len];
int bucket[];
for (int i = 0; i < len; i++) if (max < a[i]) max = a[i];
while (max / multiplier > 0) {
bucket = new int[10];
for (int i = 0; i < len; i++) bucket[(a[i] / multiplier) % 10]++;
for (int i = 1; i < 10; i++) bucket[i] += (bucket[i - 1]);
for (int i = len - 1; i >= 0; i--) b[--bucket[(a[i] / multiplier) % 10]] = a[i];
for (int i = 0; i < len; i++) a[i] = b[i];
multiplier *= 10;
}
return a;
}
long modPow(long base,long exp) {
if(exp==0) {
return 1;
}
if(exp%2==0) {
long res=(modPow(base,exp/2));
return (res*res);
}
return (base*modPow(base,exp-1));
}
long []reverse(long[] count){
long b[]=new long[count.length];
int index=0;
for(int i=count.length-1;i>=0;i--) {
b[index++]=count[i];
}
return b;
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long[] readLongArray(int n) {
long [] a=new long [n];
for (int i=0; i<n; i++) a[i]=nextLong();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
static long dp[][];
static void solve() {
long n=scr.nextLong();
long product=1;
boolean good[]=new boolean[(int)n+1];
for(long i=1;i<=n;i++) {
if(scr.gcd(i, n)<=1) {
good[(int)i]=true;
product=product*i;
product%=n;
}
}
if(product>1) {
good[(int)product]=false;
}
ArrayList<Long>a=new ArrayList<>();
for(long i=1;i<=n;i++){
if(good[(int)i]) {
a.add(i);
}
}
out.println(a.size());
for(Long i:a) {
out.print(i+" ");
}
}
int MAX = Integer.MAX_VALUE;
int MIN = Integer.MIN_VALUE;
static int mod=(int)1e9+7;
public static void main(String []args) {
// while(t-->0) {
solve();
// }
out.println(sb);
}
}
| Java | ["5", "8"] | 1 second | ["3\n1 2 3", "4\n1 3 5 7"] | NoteIn the first example, the product of the elements is $$$6$$$ which is congruent to $$$1$$$ modulo $$$5$$$. The only longer subsequence is $$$[1,2,3,4]$$$. Its product is $$$24$$$ which is congruent to $$$4$$$ modulo $$$5$$$. Hence, the answer is $$$[1,2,3]$$$. | Java 8 | standard input | [
"greedy",
"number theory"
] | d55afdb4a83aebdfce5a62e4ec934adb | The only line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$). | 1,600 | The first line should contain a single integer, the length of the longest subsequence. The second line should contain the elements of the subsequence, in increasing order. If there are multiple solutions, you can print any. | standard output | |
PASSED | 55c7cd65b0fdbc54d1ca6bda596aed49 | train_110.jsonl | 1618839300 | Now you get Baby Ehab's first words: "Given an integer $$$n$$$, find the longest subsequence of $$$[1,2, \ldots, n-1]$$$ whose product is $$$1$$$ modulo $$$n$$$." Please solve the problem.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly all) elements. The product of an empty subsequence is equal to $$$1$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class C {
public static void main(String[] args) {
FastReader f = new FastReader();
StringBuffer sb=new StringBuffer();
int n=f.nextInt();
int a[]=new int[n-1];
for(int i=0;i<n-1;i++)
a[i]=i+1;
TreeSet<Integer> list=new TreeSet<>();
long prod=1L;
for(int i:a)
{
if(gcd(i,n)==1)
{
list.add(i);
prod*=i;
prod%=n;
}
}
if(prod!=1)
list.remove((int)prod);
System.out.println(list.size());
for(int i:list)
System.out.print(i+" ");
System.out.println();
}
static int gcd(int a,int b)
{
if(b==0)
return a;
return gcd(b,a%b);
}
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 | ["5", "8"] | 1 second | ["3\n1 2 3", "4\n1 3 5 7"] | NoteIn the first example, the product of the elements is $$$6$$$ which is congruent to $$$1$$$ modulo $$$5$$$. The only longer subsequence is $$$[1,2,3,4]$$$. Its product is $$$24$$$ which is congruent to $$$4$$$ modulo $$$5$$$. Hence, the answer is $$$[1,2,3]$$$. | Java 8 | standard input | [
"greedy",
"number theory"
] | d55afdb4a83aebdfce5a62e4ec934adb | The only line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$). | 1,600 | The first line should contain a single integer, the length of the longest subsequence. The second line should contain the elements of the subsequence, in increasing order. If there are multiple solutions, you can print any. | standard output | |
PASSED | f50df11505ef1d95be116f91db01258f | train_110.jsonl | 1618839300 | Now you get Baby Ehab's first words: "Given an integer $$$n$$$, find the longest subsequence of $$$[1,2, \ldots, n-1]$$$ whose product is $$$1$$$ modulo $$$n$$$." Please solve the problem.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly all) elements. The product of an empty subsequence is equal to $$$1$$$. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.Arrays;
import java.io.UncheckedIOException;
import java.io.Closeable;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.util.PriorityQueue;
/*
@author : sanskarXrawat
@date : 8/1/2021
@time : 3:36 PM
*/
@SuppressWarnings("ALL")
public class Product1Modulo {
public static void main(String[] args) throws Throwable {
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);
Solution solver = new Solution ();
solver.solve (1, in, out);
in.close ();
out.close ();
}
}
@SuppressWarnings("unused")
static class Solution {
static final Debug debug = new Debug (true);
static boolean[] numbers=new boolean[1_000_01];
public void solve(int testNumber, FastInput in, FastOutput out) {
long a=in.rl ();
long product=1;
for (long i = 1; i <a; i++) {
if(gcd (i,a)==1){
product=(product*i)%a;
numbers[(int)i]=true;
}
}
if(product!=1) numbers[(int) product]=false;
int count=0;
for (int i = 1; i <a; i++) {
if(numbers[i]) count++;
}
out.prtl (count);
for (int i = 1; i <a; i++) {
if(numbers[i]) out.prt (i);
}
}
public static long gcd(long a,long b){
return b==0?a:gcd (b,a%b);
}
}
static class FastOutput implements AutoCloseable, Closeable, Appendable {
private final StringBuilder cache = new StringBuilder (THRESHOLD * 2);
private static final int THRESHOLD = 32 << 10;
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;
}
private void afterWrite() {
if (cache.length () < THRESHOLD) {
return;
}
flush ();
}
public FastOutput(Writer os) {
this.os = os;
}
public FastOutput(OutputStream os) {
this (new OutputStreamWriter (os));
}
public FastOutput append(char c) {
cache.append (c);
afterWrite ();
return this;
}
public FastOutput append(String c) {
cache.append (c);
afterWrite ();
return this;
}
public FastOutput println(String c) {
return append (c).println ();
}
public FastOutput println() {
return append ('\n');
}
final <T> void prt(T a) {
append (a + " ");
}
final <T> void prtl(T a) {
append (a + "\n");
}
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 ();
}
public FastOutput printf(String format, Object... args) {
return append (String.format (format, args));
}
private static int countDigits(long l) {
if (l >= 1000000000000000000L) return 19;
if (l >= 100000000000000000L) return 18;
if (l >= 10000000000000000L) return 17;
if (l >= 1000000000000000L) return 16;
if (l >= 100000000000000L) return 15;
if (l >= 10000000000000L) return 14;
if (l >= 1000000000000L) return 13;
if (l >= 100000000000L) return 12;
if (l >= 10000000000L) return 11;
if (l >= 1000000000L) return 10;
if (l >= 100000000L) return 9;
if (l >= 10000000L) return 8;
if (l >= 1000000L) return 7;
if (l >= 100000L) return 6;
if (l >= 10000L) return 5;
if (l >= 1000L) return 4;
if (l >= 100L) return 3;
if (l >= 10L) return 2;
return 1;
}
private static int countDigits(int l) {
if (l >= 1000000000) return 10;
if (l >= 100000000) return 9;
if (l >= 10000000) return 8;
if (l >= 1000000) return 7;
if (l >= 100000) return 6;
if (l >= 10000) return 5;
if (l >= 1000) return 4;
if (l >= 100) return 3;
if (l >= 10) return 2;
return 1;
}
}
static class FastInput {
private final StringBuilder defaultStringBuf = new StringBuilder (1 << 13);
private final ByteBuffer tokenBuf = new ByteBuffer ();
private final byte[] buf = new byte[1 << 13];
private SpaceCharFilter filter;
private final InputStream is;
private int bufOffset;
private int bufLen;
private int next;
private int ptr;
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 String next() {
return readString ();
}
public int ri() {
return readInt ();
}
public int readInt() {
boolean rev = false;
skipBlank ();
if (next == '+' || next == '-') {
rev = next == '-';
next = read ();
}
int val = 0;
while (next >= '0' && next <= '9') {
val = val * 10 - next + '0';
next = read ();
}
return rev ? val : -val;
}
public long readLong() {
boolean rev = false;
skipBlank ();
if (next == '+' || next == '-') {
rev = next == '-';
next = read ();
}
long val = 0L;
while (next >= '0' && next <= '9') {
val = val * 10 - next + '0';
next = read ();
}
return rev ? val : -val;
}
public long rl() {
return readLong ();
}
public String readString(StringBuilder builder) {
skipBlank ();
while (next > 32) {
builder.append ((char) next);
next = read ();
}
return builder.toString ();
}
public String readString() {
defaultStringBuf.setLength (0);
return readString (defaultStringBuf);
}
public int rs(char[] data, int offset) {
return readString (data, offset);
}
public char[] rsc() {
return readString ().toCharArray ();
}
public int rs(char[] data) {
return rs (data, 0);
}
public int readString(char[] data, int offset) {
skipBlank ();
int originalOffset = offset;
while (next > 32) {
data[offset++] = (char) next;
next = read ();
}
return offset - originalOffset;
}
public char rc() {
return readChar ();
}
public char readChar() {
skipBlank ();
char c = (char) next;
next = read ();
return c;
}
public double rd() {
return nextDouble ();
}
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, readInt ());
if (c < '0' || c > '9')
throw new InputMismatchException ();
res *= 10;
res += c - '0';
c = read ();
}
if (c == '.') {
c = read ();
double m = 1;
while (!isSpaceChar (c)) {
if (c == 'e' || c == 'E')
return res * Math.pow (10, readInt ());
if (c < '0' || c > '9')
throw new InputMismatchException ();
m /= 10;
res += (c - '0') * m;
c = read ();
}
}
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar (c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
public final int readByteUnsafe() {
if (ptr < bufLen) return buf[ptr++];
ptr = 0;
try {
bufLen = is.read (buf);
if (bufLen > 0) {
return buf[ptr++];
} else {
return -1;
}
} catch (IOException e) {
throw new UncheckedIOException (e);
}
}
public final int readByte() {
if (ptr < bufLen) return buf[ptr++];
ptr = 0;
try {
bufLen = is.read (buf);
if (bufLen > 0) {
return buf[ptr++];
} else {
throw new java.io.EOFException ();
}
} catch (IOException e) {
throw new UncheckedIOException (e);
}
}
public final String nextLine() {
tokenBuf.clear ();
for (int b = readByte (); b != '\n'; b = readByteUnsafe ()) {
if (b == -1) break;
tokenBuf.append (b);
}
return new String (tokenBuf.getRawBuf (), 0, tokenBuf.size ());
}
public final String nl() {
return nextLine ();
}
public final boolean hasNext() {
for (int b = readByteUnsafe (); b <= 32 || b >= 127; b = readByteUnsafe ()) {
if (b == -1) return false;
}
--ptr;
return true;
}
public void readArray(Object T) {
if (T instanceof int[]) {
int[] arr = (int[]) T;
for (int i = 0; i < arr.length; i++) {
arr[i] = ri ();
}
}
if (T instanceof long[]) {
long[] arr = (long[]) T;
for (int i = 0; i < arr.length; i++) {
arr[i] = rl ();
}
}
if (T instanceof double[]) {
double[] arr = (double[]) T;
for (int i = 0; i < arr.length; i++) {
arr[i] = rd ();
}
}
if (T instanceof char[]) {
char[] arr = (char[]) T;
for (int i = 0; i < arr.length; i++) {
arr[i] = readChar ();
}
}
if (T instanceof String[]) {
String[] arr = (String[]) T;
for (int i = 0; i < arr.length; i++) {
arr[i] = next ();
}
}
if (T instanceof int[][]) {
int[][] arr = (int[][]) T;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[0].length; j++) {
arr[i][j] = ri ();
}
}
}
if (T instanceof char[][]) {
char[][] arr = (char[][]) T;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[0].length; j++) {
arr[i][j] = readChar ();
}
}
}
if (T instanceof long[][]) {
long[][] arr = (long[][]) T;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[0].length; j++) {
arr[i][j] = rl ();
}
}
}
}
public final void close() {
try {
is.close ();
} catch (IOException e) {
throw new UncheckedIOException (e);
}
}
private static final class ByteBuffer {
private static final int DEFAULT_BUF_SIZE = 1 << 12;
private byte[] buf;
private int ptr = 0;
private ByteBuffer(int capacity) {
this.buf = new byte[capacity];
}
private ByteBuffer() {
this (DEFAULT_BUF_SIZE);
}
private ByteBuffer append(int b) {
if (ptr == buf.length) {
int newLength = buf.length << 1;
byte[] newBuf = new byte[newLength];
System.arraycopy (buf, 0, newBuf, 0, buf.length);
buf = newBuf;
}
buf[ptr++] = (byte) b;
return this;
}
private char[] toCharArray() {
char[] chs = new char[ptr];
for (int i = 0; i < ptr; i++) {
chs[i] = (char) buf[i];
}
return chs;
}
private byte[] getRawBuf() {
return buf;
}
private int size() {
return ptr;
}
private void clear() {
ptr = 0;
}
}
}
static class Debug {
private final boolean offline;
private final PrintStream out = System.err;
static int[] empty = new int[0];
public Debug(boolean enable) {
offline = enable && System.getSecurityManager () == null;
}
public Debug debug(String name, Object x) {
return debug (name, x, empty);
}
public Debug debug(String name, long x) {
if (offline) {
debug (name, "" + x);
}
return this;
}
public Debug debug(String name, String x) {
if (offline) {
out.printf ("%s=%s", name, x);
out.println ();
}
return this;
}
public Debug debug(String name, Object x, int... indexes) {
if (offline) {
if (x == null || !x.getClass ().isArray ()) {
out.append (name);
for (int i : indexes) {
out.printf ("[%d]", i);
}
out.append ("=").append ("" + x);
out.println ();
} else {
indexes = Arrays.copyOf (indexes, indexes.length + 1);
if (x instanceof byte[]) {
byte[] arr = (byte[]) x;
for (int i = 0; i < arr.length; i++) {
indexes[indexes.length - 1] = i;
debug (name, arr[i], indexes);
}
} else if (x instanceof short[]) {
short[] arr = (short[]) x;
for (int i = 0; i < arr.length; i++) {
indexes[indexes.length - 1] = i;
debug (name, arr[i], indexes);
}
} else if (x instanceof boolean[]) {
boolean[] arr = (boolean[]) x;
for (int i = 0; i < arr.length; i++) {
indexes[indexes.length - 1] = i;
debug (name, arr[i], indexes);
}
} else if (x instanceof char[]) {
char[] arr = (char[]) x;
for (int i = 0; i < arr.length; i++) {
indexes[indexes.length - 1] = i;
debug (name, arr[i], indexes);
}
} else if (x instanceof int[]) {
int[] arr = (int[]) x;
for (int i = 0; i < arr.length; i++) {
indexes[indexes.length - 1] = i;
debug (name, arr[i], indexes);
}
} else if (x instanceof float[]) {
float[] arr = (float[]) x;
for (int i = 0; i < arr.length; i++) {
indexes[indexes.length - 1] = i;
debug (name, arr[i], indexes);
}
} else if (x instanceof double[]) {
double[] arr = (double[]) x;
for (int i = 0; i < arr.length; i++) {
indexes[indexes.length - 1] = i;
debug (name, arr[i], indexes);
}
} else if (x instanceof long[]) {
long[] arr = (long[]) x;
for (int i = 0; i < arr.length; i++) {
indexes[indexes.length - 1] = i;
debug (name, arr[i], indexes);
}
} else {
Object[] arr = (Object[]) x;
for (int i = 0; i < arr.length; i++) {
indexes[indexes.length - 1] = i;
debug (name, arr[i], indexes);
}
}
}
}
return this;
}
}
} | Java | ["5", "8"] | 1 second | ["3\n1 2 3", "4\n1 3 5 7"] | NoteIn the first example, the product of the elements is $$$6$$$ which is congruent to $$$1$$$ modulo $$$5$$$. The only longer subsequence is $$$[1,2,3,4]$$$. Its product is $$$24$$$ which is congruent to $$$4$$$ modulo $$$5$$$. Hence, the answer is $$$[1,2,3]$$$. | Java 8 | standard input | [
"greedy",
"number theory"
] | d55afdb4a83aebdfce5a62e4ec934adb | The only line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$). | 1,600 | The first line should contain a single integer, the length of the longest subsequence. The second line should contain the elements of the subsequence, in increasing order. If there are multiple solutions, you can print any. | standard output | |
PASSED | 30b3ba46d12c566330879d9ff88cbc9a | train_110.jsonl | 1618839300 | Now you get Baby Ehab's first words: "Given an integer $$$n$$$, find the longest subsequence of $$$[1,2, \ldots, n-1]$$$ whose product is $$$1$$$ modulo $$$n$$$." Please solve the problem.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly all) elements. The product of an empty subsequence is equal to $$$1$$$. | 256 megabytes | import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
StringBuffer out=new StringBuffer();
int t=1;
outer:
while(t--!=0) {
int n=in.nextInt();
boolean coprime[]=new boolean[n];
int cnt=0, rem=1;
for(int i=1; i<n; i++) {
if(gcd(i, n)==1) {
cnt+=1;
coprime[i]=true;
rem=(int)((1L*rem*i)%n);
}
}
if(rem!=1) {
coprime[rem]=false;
cnt-=1;
}
out.append(cnt+"\n");
for(int i=1; i<n; i++) if(coprime[i]) {
out.append(i+" ");
}
out.append("\n");
}
System.out.println(out);
}
private static int gcd(int a, int b) {
if(a==0)
return b;
return gcd(b%a, a);
}
} | Java | ["5", "8"] | 1 second | ["3\n1 2 3", "4\n1 3 5 7"] | NoteIn the first example, the product of the elements is $$$6$$$ which is congruent to $$$1$$$ modulo $$$5$$$. The only longer subsequence is $$$[1,2,3,4]$$$. Its product is $$$24$$$ which is congruent to $$$4$$$ modulo $$$5$$$. Hence, the answer is $$$[1,2,3]$$$. | Java 8 | standard input | [
"greedy",
"number theory"
] | d55afdb4a83aebdfce5a62e4ec934adb | The only line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$). | 1,600 | The first line should contain a single integer, the length of the longest subsequence. The second line should contain the elements of the subsequence, in increasing order. If there are multiple solutions, you can print any. | standard output | |
PASSED | a587a3d8237a45f9cadc0f971a64a69e | train_110.jsonl | 1618839300 | Now you get Baby Ehab's first words: "Given an integer $$$n$$$, find the longest subsequence of $$$[1,2, \ldots, n-1]$$$ whose product is $$$1$$$ modulo $$$n$$$." Please solve the problem.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly all) elements. The product of an empty subsequence is equal to $$$1$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
private static int gcd(int a, int b) {
if(b == 0) {
return a;
}
return gcd(b, a%b);
}
public static void main(String[] args) throws IOException {
//BufferedReader f = new BufferedReader(new FileReader("uva.in"));
//BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
//Scanner f = new Scanner(new File("uva.in"));
Scanner f = new Scanner(System.in);
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int n = f.nextInt();
ArrayList<Integer> coprime = new ArrayList<>();
long p = 1;
for(int i = 1; i < n; i++) {
if(gcd(i, n) == 1) {
coprime.add(i);
p = (p*i)%n;
}
}
if(p != 1) {
coprime.remove(coprime.indexOf((int) p));
}
out.println(coprime.size());
out.print(coprime.get(0));
for(int i = 1; i < coprime.size(); i++) {
out.print(" " + coprime.get(i));
}
out.println();
f.close();
out.close();
}
}
| Java | ["5", "8"] | 1 second | ["3\n1 2 3", "4\n1 3 5 7"] | NoteIn the first example, the product of the elements is $$$6$$$ which is congruent to $$$1$$$ modulo $$$5$$$. The only longer subsequence is $$$[1,2,3,4]$$$. Its product is $$$24$$$ which is congruent to $$$4$$$ modulo $$$5$$$. Hence, the answer is $$$[1,2,3]$$$. | Java 8 | standard input | [
"greedy",
"number theory"
] | d55afdb4a83aebdfce5a62e4ec934adb | The only line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$). | 1,600 | The first line should contain a single integer, the length of the longest subsequence. The second line should contain the elements of the subsequence, in increasing order. If there are multiple solutions, you can print any. | standard output | |
PASSED | 635c85366761a1b090ca9efbeb2e93c2 | train_110.jsonl | 1618839300 | Now you get Baby Ehab's first words: "Given an integer $$$n$$$, find the longest subsequence of $$$[1,2, \ldots, n-1]$$$ whose product is $$$1$$$ modulo $$$n$$$." Please solve the problem.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly all) elements. The product of an empty subsequence is equal to $$$1$$$. | 256 megabytes | import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
StringBuffer out=new StringBuffer();
int t=1;
outer:
while(t--!=0) {
int n=in.nextInt();
boolean coprime[]=new boolean[n];
int cnt=0, rem=1;
for(int i=1; i<n; i++) {
if(gcd(i, n)==1) {
cnt+=1;
coprime[i]=true;
rem=(int)((1L*rem*i)%n);
}
}
if(rem!=1) {
coprime[rem]=false;
cnt-=1;
}
out.append(cnt+"\n");
for(int i=1; i<n; i++) if(coprime[i]) {
out.append(i+" ");
}
out.append("\n");
}
System.out.println(out);
}
private static int gcd(int a, int b) {
if(a==0)
return b;
return gcd(b%a, a);
}
} | Java | ["5", "8"] | 1 second | ["3\n1 2 3", "4\n1 3 5 7"] | NoteIn the first example, the product of the elements is $$$6$$$ which is congruent to $$$1$$$ modulo $$$5$$$. The only longer subsequence is $$$[1,2,3,4]$$$. Its product is $$$24$$$ which is congruent to $$$4$$$ modulo $$$5$$$. Hence, the answer is $$$[1,2,3]$$$. | Java 8 | standard input | [
"greedy",
"number theory"
] | d55afdb4a83aebdfce5a62e4ec934adb | The only line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$). | 1,600 | The first line should contain a single integer, the length of the longest subsequence. The second line should contain the elements of the subsequence, in increasing order. If there are multiple solutions, you can print any. | standard output | |
PASSED | 04afa118f25fdd185f350d142e2bb059 | train_110.jsonl | 1618839300 | Now you get Baby Ehab's first words: "Given an integer $$$n$$$, find the longest subsequence of $$$[1,2, \ldots, n-1]$$$ whose product is $$$1$$$ modulo $$$n$$$." Please solve the problem.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly all) elements. The product of an empty subsequence is equal to $$$1$$$. | 256 megabytes | import java.util.*;import java.io.*;import java.math.*;
public class CF1514C
{
static final Random random=new Random();
static boolean memory = true;
static void ruffleSort(int[] a) {
int n = a.length;
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
ArrayList<Integer> lst = new ArrayList<>();
for(int i : a)
lst.add(i);
Collections.sort(lst);
for(int i = 0; i < n; i++)
a[i] = lst.get(i);
}
static void ruffleSort(long[] a) {
int n = a.length;
for (int i=0; i<n; i++) {
int oi=random.nextInt(n);
long temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
ArrayList<Long> lst = new ArrayList<>();
for(long i : a)
lst.add(i);
Collections.sort(lst);
for(int i = 0; i < n; i++)
a[i] = lst.get(i);
}
public static void process()throws IOException
{
int n = ni();
TreeSet<Integer> set = new TreeSet<>();
long prod = 1;
for(int i = 1; i < n; i++){
if(gcd(i, n) == 1){
set.add(i);
prod = prod*i%n;
}
}
set.remove((int)prod);
set.add(1);
pn(set.size());
for(int i : set)
p(i+" ");
pn("");
}
static AnotherReader sc;
static PrintWriter out;
public static void main(String[] args) throws Exception{
if(memory)new Thread(null, new Runnable() {public void run(){try{new CF1514C().run();}catch(Exception e){e.printStackTrace();System.exit(1);}}}, "1", 1 << 28).start();
else new CF1514C().run();
}
void run()throws Exception
{
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
if(oj){sc=new AnotherReader();out=new PrintWriter(System.out);}
else{sc=new AnotherReader(100);out=new PrintWriter("output.txt");}
long s = System.currentTimeMillis();
int t=1;
//t=ni();
//int k = t;
while(t-->0) {/*p("Case #"+ (k-t) + ": ")*/;process();}
out.flush();
System.err.println(System.currentTimeMillis()-s+"ms");
out.close();
}
static long power(long k, long c, long mod){
long y = 1;
while(c > 0){
if(c%2 == 1)
y = y * k % mod;
c = c/2;
k = k * k % mod;
}
return y;
}
static int power(int x, int y, int p){
int res = 1;
x = x % p;
while (y > 0) {
if (y % 2 == 1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
static int log2(int N)
{
int result = (int)(Math.log(N) / Math.log(2));
return result;
}
static void pn(Object o){out.println(o);}
static void p(Object o){out.print(o);}
static void pni(Object o){out.println(o);out.flush();}
static int ni()throws IOException{return sc.nextInt();}
static long nl()throws IOException{return sc.nextLong();}
static double nd()throws IOException{return sc.nextDouble();}
static String nln()throws IOException{return sc.nextLine();}
static int[] nai(int N)throws IOException{int[]A=new int[N];for(int i=0;i!=N;i++){A[i]=ni();}return A;}
static long[] nal(int N)throws IOException{long[]A=new long[N];for(int i=0;i!=N;i++){A[i]=nl();}return A;}
static long gcd(long a, long b)throws IOException{return (b==0)?a:gcd(b,a%b);}
static int gcd(int a, int b)throws IOException{return (b==0)?a:gcd(b,a%b);}
static int bit(long n)throws IOException{return (n==0)?0:(1+bit(n&(n-1)));}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
static class AnotherReader{BufferedReader br; StringTokenizer st;
AnotherReader()throws FileNotFoundException{
br=new BufferedReader(new InputStreamReader(System.in));}
AnotherReader(int a)throws FileNotFoundException{
br = new BufferedReader(new FileReader("input.txt"));}
String next()throws IOException{
while (st == null || !st.hasMoreElements()) {try{
st = new StringTokenizer(br.readLine());}
catch (IOException e){ e.printStackTrace(); }}
return st.nextToken(); } int nextInt() throws IOException{
return Integer.parseInt(next());}
long nextLong() throws IOException
{return Long.parseLong(next());}
double nextDouble()throws IOException { return Double.parseDouble(next()); }
String nextLine() throws IOException{ String str = ""; try{
str = br.readLine();} catch (IOException e){
e.printStackTrace();} return str;}}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
} | Java | ["5", "8"] | 1 second | ["3\n1 2 3", "4\n1 3 5 7"] | NoteIn the first example, the product of the elements is $$$6$$$ which is congruent to $$$1$$$ modulo $$$5$$$. The only longer subsequence is $$$[1,2,3,4]$$$. Its product is $$$24$$$ which is congruent to $$$4$$$ modulo $$$5$$$. Hence, the answer is $$$[1,2,3]$$$. | Java 8 | standard input | [
"greedy",
"number theory"
] | d55afdb4a83aebdfce5a62e4ec934adb | The only line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$). | 1,600 | The first line should contain a single integer, the length of the longest subsequence. The second line should contain the elements of the subsequence, in increasing order. If there are multiple solutions, you can print any. | standard output | |
PASSED | 4b4ae6d9e3c51d7b8944df6ea3b1b159 | train_110.jsonl | 1618839300 | Now you get Baby Ehab's first words: "Given an integer $$$n$$$, find the longest subsequence of $$$[1,2, \ldots, n-1]$$$ whose product is $$$1$$$ modulo $$$n$$$." Please solve the problem.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly all) elements. The product of an empty subsequence is equal to $$$1$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Main {
static int MAX_N = 100010;
public static void main(String[] args) throws IOException {
initReader(System.in);
solve();
printWriter.flush();
}
/***********************************************************************************************/
static boolean[] a = new boolean[MAX_N];
public static void solve() throws IOException {
int n = nextInt();
long pre = 1;
for (int i = 1; i < n; i++) {
if (gcd(i, n) == 1) {
a[i] = true;
pre = (pre * i) % n;
}
}
if (pre % n != 1) {
a[(int) pre] = false;
}
int cnt = 0;
for (int i = 1; i < n; i++) {
if (a[i]) {
cnt++;
}
}
printWriter.println(cnt);
for (int i = 1; i < n; i++) {
if (a[i]) {
printWriter.print(i + " ");
}
}
}
public static void init() {
}
public static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
/***********************************************************************************************/
static BufferedReader reader;
static StringTokenizer tokenizer;
static PrintWriter printWriter;
static void initReader(InputStream input) {
reader = new BufferedReader(new InputStreamReader(input));
tokenizer = new StringTokenizer("");
printWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
}
static boolean hasNext() {
try {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
} catch (Exception e) {
return false;
// TODO: handle exception
}
return true;
}
static String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
static String nextLine() throws IOException {
try {
return reader.readLine();
} catch (Exception e) {
return null;
// TODO: handle exception
}
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
static char nextChar() throws IOException {
return next().charAt(0);
}
}
class Node implements Comparable {
int x, y, t;
Node(int x, int y, int t) {
this.x = x;
this.y = y;
this.t = t;
}
@Override
public int compareTo(Object o) {
// TODO Auto-generated method stub
Node rhs = (Node) o;
return this.t - rhs.t;
}
} | Java | ["5", "8"] | 1 second | ["3\n1 2 3", "4\n1 3 5 7"] | NoteIn the first example, the product of the elements is $$$6$$$ which is congruent to $$$1$$$ modulo $$$5$$$. The only longer subsequence is $$$[1,2,3,4]$$$. Its product is $$$24$$$ which is congruent to $$$4$$$ modulo $$$5$$$. Hence, the answer is $$$[1,2,3]$$$. | Java 8 | standard input | [
"greedy",
"number theory"
] | d55afdb4a83aebdfce5a62e4ec934adb | The only line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$). | 1,600 | The first line should contain a single integer, the length of the longest subsequence. The second line should contain the elements of the subsequence, in increasing order. If there are multiple solutions, you can print any. | standard output | |
PASSED | a89dbc8650f383d99c515644f77aef28 | train_110.jsonl | 1618839300 | Now you get Baby Ehab's first words: "Given an integer $$$n$$$, find the longest subsequence of $$$[1,2, \ldots, n-1]$$$ whose product is $$$1$$$ modulo $$$n$$$." Please solve the problem.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly all) elements. The product of an empty subsequence is equal to $$$1$$$. | 256 megabytes | import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
static Scanner scan = new Scanner(System.in);
public static int gcd(int a,int b){
return b==0 ? a:gcd(b,a%b);
}
public static void slove(){
int n = scan.nextInt();
int cnt = 0;
long sum = 1;
List<Integer> res = new ArrayList<>();
for(int i=1;i<n;i++){
if(gcd(i,n)==1){
sum = sum * i % n;
res.add(i);
cnt++;
}
}
if(sum!=1){
cnt--;
}
System.out.println(cnt);
for(int i=0;i<cnt;i++){
System.out.print(res.get(i)+" ");
}
System.out.println();
}
public static void main(String[] args) {
//int T = scan.nextInt();
//while(T-- >0){
slove();
//}
}
}
| Java | ["5", "8"] | 1 second | ["3\n1 2 3", "4\n1 3 5 7"] | NoteIn the first example, the product of the elements is $$$6$$$ which is congruent to $$$1$$$ modulo $$$5$$$. The only longer subsequence is $$$[1,2,3,4]$$$. Its product is $$$24$$$ which is congruent to $$$4$$$ modulo $$$5$$$. Hence, the answer is $$$[1,2,3]$$$. | Java 8 | standard input | [
"greedy",
"number theory"
] | d55afdb4a83aebdfce5a62e4ec934adb | The only line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$). | 1,600 | The first line should contain a single integer, the length of the longest subsequence. The second line should contain the elements of the subsequence, in increasing order. If there are multiple solutions, you can print any. | standard output | |
PASSED | 7ac9f8318bc6899007696cd97609a427 | train_110.jsonl | 1618839300 | Now you get Baby Ehab's first words: "Given an integer $$$n$$$, find the longest subsequence of $$$[1,2, \ldots, n-1]$$$ whose product is $$$1$$$ modulo $$$n$$$." Please solve the problem.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly all) elements. The product of an empty subsequence is equal to $$$1$$$. | 256 megabytes | /*----------- ---------------*
Author : Ryan Ranaut
__Hope is a big word, never lose it__
------------- --------------*/
import java.io.*;
import java.util.*;
public class Codeforces2 {
static PrintWriter out = new PrintWriter(System.out);
static final int mod = 1_000_000_007;
static final long max = (long)1e14;
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());
}
int[] readIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
long[] readLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
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();
int t = 1;
while(t-->0)
{
int n = s.nextInt();
long prod = 1;
List<Integer> ls = new ArrayList<>();
for(int i=1;i<n;i++) {
if(gcd(i, n) == 1) {
ls.add(i);
prod = (prod*i)%n;
}
}
int size = ls.size();
if(prod != 1)
size--;
out.println(size);
for(int i=0;i<size;i++)
out.print(ls.get(i)+" ");
out.println();
}
out.close();
}
public static void find()
{
}
/*----------------------------------End of the road--------------------------------------*/
static class DSU {
int[] parent;
int[] ranks;
int[] groupSize;
int size;
public DSU(int n) {
size = n;
parent = new int[n];//0 based
ranks = new int[n];
groupSize = new int[n];//Size of each component
for (int i = 0; i < n; i++) {
parent[i] = i;
ranks[i] = 1;
groupSize[i] = 1;
}
}
public int find(int x)//Path Compression
{
if (parent[x] == x)
return x;
else
return parent[x] = find(parent[x]);
}
public void union(int x, int y)//Union by rank
{
int x_rep = find(x);
int y_rep = find(y);
if (x_rep == y_rep)
return;
if (ranks[x_rep] < ranks[y_rep]) {
parent[x_rep] = y_rep;
groupSize[y_rep] += groupSize[x_rep];
} else if (ranks[x_rep] > ranks[y_rep]) {
parent[y_rep] = x_rep;
groupSize[x_rep] += groupSize[y_rep];
} else {
parent[y_rep] = x_rep;
ranks[x_rep]++;
groupSize[x_rep] += groupSize[y_rep];
}
size--;//Total connected components
}
}
public static int gcd(int x, int y) {
return y == 0 ? x : gcd(y, x % y);
}
public static long gcd(long x, long y) {
return y == 0L ? x : gcd(y, x % y);
}
public static int lcm(int a, int b) {
return (a * b) / gcd(a, b);
}
public static long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
public static long pow(long a, long b) {
if (b == 0L)
return 1L;
long tmp = 1;
while (b > 1L) {
if ((b & 1L) == 1)
tmp *= a;
a *= a;
b >>= 1;
}
return (tmp * a);
}
public static long modPow(long a, long b, long mod) {
if (b == 0L)
return 1L;
long tmp = 1;
while (b > 1L) {
if ((b & 1L) == 1L)
tmp *= a;
a *= a;
a %= mod;
tmp %= mod;
b >>= 1;
}
return (tmp * a) % mod;
}
static long mul(long a, long b) {
return a * b;
}
static long fact(int n) {
long ans = 1;
for (int i = 2; i <= n; i++) ans = mul(ans, i);
return ans;
}
static long fastPow(long base, long exp) {
if (exp==0) return 1;
long half=fastPow(base, exp/2);
if (exp%2==0) return mul(half, half);
return mul(half, mul(half, base));
}
static void debug(int... a) {
for (int x : a)
out.print(x + " ");
out.println();
}
static void debug(long... a) {
for (long x : a)
out.print(x + " ");
out.println();
}
static void debugMatrix(int[][] a) {
for (int[] x : a)
out.println(Arrays.toString(x));
}
static void debugMatrix(long[][] a) {
for (long[] x : a)
out.println(Arrays.toString(x));
}
static void reverseArray(int[] a) {
int n = a.length;
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = a[n - i - 1];
for (int i = 0; i < n; i++)
a[i] = arr[i];
}
static void reverseArray(long[] a) {
int n = a.length;
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = a[n - i - 1];
for (int i = 0; i < n; i++)
a[i] = arr[i];
}
static void sort(int[] a) {
ArrayList<Integer> ls = new ArrayList<>();
for (int x : a) ls.add(x);
Collections.sort(ls);
for (int i = 0; i < a.length; i++)
a[i] = ls.get(i);
}
static void sort(long[] a) {
ArrayList<Long> ls = new ArrayList<>();
for (long x : a) ls.add(x);
Collections.sort(ls);
for (int i = 0; i < a.length; i++)
a[i] = ls.get(i);
}
static class Pair {
int x, y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
} | Java | ["5", "8"] | 1 second | ["3\n1 2 3", "4\n1 3 5 7"] | NoteIn the first example, the product of the elements is $$$6$$$ which is congruent to $$$1$$$ modulo $$$5$$$. The only longer subsequence is $$$[1,2,3,4]$$$. Its product is $$$24$$$ which is congruent to $$$4$$$ modulo $$$5$$$. Hence, the answer is $$$[1,2,3]$$$. | Java 17 | standard input | [
"greedy",
"number theory"
] | d55afdb4a83aebdfce5a62e4ec934adb | The only line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$). | 1,600 | The first line should contain a single integer, the length of the longest subsequence. The second line should contain the elements of the subsequence, in increasing order. If there are multiple solutions, you can print any. | standard output | |
PASSED | 60616b87f052db86b22c20008d8578a2 | train_110.jsonl | 1618839300 | Now you get Baby Ehab's first words: "Given an integer $$$n$$$, find the longest subsequence of $$$[1,2, \ldots, n-1]$$$ whose product is $$$1$$$ modulo $$$n$$$." Please solve the problem.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly all) elements. The product of an empty subsequence is equal to $$$1$$$. | 256 megabytes | //https://codeforces.com/problemset/problem/1514/C
import java.util.*;
import java.io.*;
public class onemodn {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
long N = Integer.parseInt(br.readLine());
long prod = 1;
List<Integer> coprime = new ArrayList<>();
for (int i = 1; i < N; i++) {
if (gcd(i, N) == 1) {
coprime.add(i);
prod = prod * i % N;
}
}
if (prod == 1) pw.println(coprime.size());
else pw.println(coprime.size() - 1);
for (int i = 0; i < coprime.size(); i++) {
if (prod != 1 && coprime.get(i) == prod) continue;
pw.print(coprime.get(i));
if (i != coprime.size() - 1) pw.print(" ");
}
pw.println();
pw.flush();
}
static long gcd(long a, long b) { //euclid algo
return b == 0 ? a : gcd(b, a % b);
}
}
| Java | ["5", "8"] | 1 second | ["3\n1 2 3", "4\n1 3 5 7"] | NoteIn the first example, the product of the elements is $$$6$$$ which is congruent to $$$1$$$ modulo $$$5$$$. The only longer subsequence is $$$[1,2,3,4]$$$. Its product is $$$24$$$ which is congruent to $$$4$$$ modulo $$$5$$$. Hence, the answer is $$$[1,2,3]$$$. | Java 17 | standard input | [
"greedy",
"number theory"
] | d55afdb4a83aebdfce5a62e4ec934adb | The only line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$). | 1,600 | The first line should contain a single integer, the length of the longest subsequence. The second line should contain the elements of the subsequence, in increasing order. If there are multiple solutions, you can print any. | standard output | |
PASSED | 7f9c45fd88dfe2cfbc0e13ba2a8deb92 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 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 First {
static int bl;
static int[] arr;
static int[] cnt;
static int[] freq;
static int max = 0;
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
int n, q;
n = in.nextInt();
q = in.nextInt();
bl = (int) Math.sqrt(n);
arr = new int[n];
cnt = new int[n+10];
freq= new int[n+10];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
answer1[] queries = new answer1[q];
for (int i = 0; i < q; i++) {
queries[i] = new answer1(in.nextInt(), in.nextInt(), i);
}
Arrays.sort(queries);
int l = 0, r =-1 , a = 0;
int[] ans = new int[q];
for (int i = 0; i < q; i++) {
int L, R, index;
L = queries[i].a -1;
R = queries[i].b -1;
index = queries[i].c;
while (R > r) {
++r;
freq[cnt[arr[r]]]--;
cnt[arr[r]]++;
freq[cnt[arr[r]]]++;
if (cnt[arr[r]] > max) {
max = cnt[arr[r]];
}
}
while (L > l){
freq[cnt[arr[l]]]--;
cnt[arr[l]]--;
freq[cnt[arr[l]]]++;
if (max != 0 && freq[max] == 0) {
max--;
}
l++;
}
while (R < r) {
freq[cnt[arr[r]]]--;
cnt[arr[r]]--;
freq[cnt[arr[r]]]++;
if (max != 0 && freq[max] == 0) {
max--;
}
r--;
}
while (L < l) {
--l;
freq[cnt[arr[l]]]--;
cnt[arr[l]]++;
freq[cnt[arr[l]]]++;
if (cnt[arr[l]] > max) {
max = cnt[arr[l]];
}
}
int size = r-l+1;
if (size >= max*2-1) {
ans[index] = 1;
} else {
size = (r-l+1-max)*2+1;
a = 1+r-l+1-size;
ans[index] = a;
}
}
for (int i = 0; i < q; i++) {
out.println(ans[i]);
}
out.close();
}
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 / gcd(a, b)) * b;
}
static class answer implements Comparable<answer>{
int a;
int b;
public answer(int a, int b) {
this.a = a;
this.b = b;
}
@Override
public int compareTo(answer o) {
return this.a - o.a;
}
}
static class answer1 implements Comparable<answer1>{
int a, b, c;
public answer1(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
@Override
public int compareTo(answer1 o) {
if (this.a/bl != o.a/bl)
return this.a-o.a;
return this.b - o.b;
}
}
static long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static void sort(long[] a) {
ArrayList<Long> l=new ArrayList<>();
for (long i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static final Random random=new Random();
static void shuffleSort(int[] a) {
int n=a.length;
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong(){
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
} | Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 8 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | 089669ae403552531debfe4cbe31d2f2 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 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;
// --------------------------------- Always Check AM PM -------------------------------
public class First {
static int bl;
static int[] arr;
static int[] cnt;
static int[] freq;
static int max = 0;
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
int n, q;
n = in.nextInt();
q = in.nextInt();
bl = (int) Math.sqrt(n);
arr = new int[n];
cnt = new int[n+10];
freq= new int[n+10];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
answer1[] queries = new answer1[q];
for (int i = 0; i < q; i++) {
queries[i] = new answer1(in.nextInt(), in.nextInt(), i);
}
Arrays.sort(queries);
int l = 0, r =-1 , a = 0;
int[] ans = new int[q];
for (int i = 0; i < q; i++) {
int L, R, index;
L = queries[i].a -1;
R = queries[i].b -1;
index = queries[i].c;
while (R > r) {
++r;
freq[cnt[arr[r]]]--;
cnt[arr[r]]++;
freq[cnt[arr[r]]]++;
if (cnt[arr[r]] > max) {
max = cnt[arr[r]];
}
}
while (L > l){
freq[cnt[arr[l]]]--;
cnt[arr[l]]--;
freq[cnt[arr[l]]]++;
if (max != 0 && freq[max] == 0) {
max--;
}
l++;
}
while (R < r) {
freq[cnt[arr[r]]]--;
cnt[arr[r]]--;
freq[cnt[arr[r]]]++;
if (max != 0 && freq[max] == 0) {
max--;
}
r--;
}
while (L < l) {
--l;
freq[cnt[arr[l]]]--;
cnt[arr[l]]++;
freq[cnt[arr[l]]]++;
if (cnt[arr[l]] > max) {
max = cnt[arr[l]];
}
}
int size = r-l+1;
if (size >= max*2-1) {
ans[index] = 1;
} else {
size = (r-l+1-max)*2+1;
a = 1+r-l+1-size;
ans[index] = a;
}
}
for (int i = 0; i < q; i++) {
out.println(ans[i]);
}
out.close();
}
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 / gcd(a, b)) * b;
}
static class answer implements Comparable<answer>{
int a;
int b;
public answer(int a, int b) {
this.a = a;
this.b = b;
}
@Override
public int compareTo(answer o) {
return this.a - o.a;
}
}
static class answer1 implements Comparable<answer1>{
int a, b, c;
public answer1(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
@Override
public int compareTo(answer1 o) {
if (this.a/bl != o.a/bl)
return this.a-o.a;
return this.b - o.b;
}
}
static long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static void sort(long[] a) {
ArrayList<Long> l=new ArrayList<>();
for (long i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static final Random random=new Random();
static void shuffleSort(int[] a) {
int n=a.length;
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong(){
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
} | Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 8 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | 8eeb6983ed96022eb2889cad2c160a70 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | import java.io.*;
import java.util.*;
// --------------------------------- Always Check AM PM -------------------------------
public class First {
static int bl;
static class answer1 implements Comparable<answer1> {
int a, b, c;
public answer1(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
@Override
public int compareTo(answer1 o) {
if (this.a / bl != o.a / bl)
return this.a - o.a;
return this.b - o.b;
}
}
public static void main(String[] args) throws IOException {
v in = new v();
int n, q, max = 0;
n = in.nextInt();
q = in.nextInt();
bl = (int) Math.sqrt(n);
int[] arr = new int[n];
int[] ans = new int[q];
int[] cnt = new int[n + 10];
int[] freq = new int[n + 10];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
answer1[] queries = new answer1[q];
for (int i = 0; i < q; i++) {
queries[i] = new answer1(in.nextInt(), in.nextInt(), i);
}
Arrays.sort(queries);
int l = 0, r = -1, a;
for (int i = 0; i < q; i++) {
int L, R, index;
L = queries[i].a - 1;
R = queries[i].b - 1;
index = queries[i].c;
while (R > r) {
++r;
freq[cnt[arr[r]]]--;
cnt[arr[r]]++;
freq[cnt[arr[r]]]++;
if (cnt[arr[r]] > max) {
max = cnt[arr[r]];
}
}
while (L > l){
freq[cnt[arr[l]]]--;
cnt[arr[l]]--;
freq[cnt[arr[l]]]++;
if (max != 0 && freq[max] == 0) {
max--;
}
l++;
}
while (R < r) {
freq[cnt[arr[r]]]--;
cnt[arr[r]]--;
freq[cnt[arr[r]]]++;
if (max != 0 && freq[max] == 0) {
max--;
}
r--;
}
while (L < l) {
--l;
freq[cnt[arr[l]]]--;
cnt[arr[l]]++;
freq[cnt[arr[l]]]++;
if (cnt[arr[l]] > max) {
max = cnt[arr[l]];
}
}
int size = r - l + 1;
if (size >= max * 2 - 1) {
ans[index] = 1;
} else {
size = (r - l + 1 - max) * 2 + 1;
a = 1 + r - l + 1 - size;
ans[index] = a;
}
}
StringBuilder sb = new StringBuilder();
for(int i: ans){
sb.append(i).append("\n");
}
System.out.println(sb);
in.close();
}
static class v {
final private int BUFFER_SIZE = 1 << 18;
final private DataInputStream din;
final private byte[] buffer;
private PrintWriter pw;
private int bufferPointer, bytesRead;
StringTokenizer st;
public v() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public v(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public void streamOutput(String file) throws IOException {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
pw = new PrintWriter(bw);
}
public void println(String a) {
pw.println(a);
}
public void print(String a) {
pw.print(a);
}
public String readLine() throws IOException {
byte[] buf = new byte[3000064]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public void sort(int[] arr) {
ArrayList<Integer> arlist = new ArrayList<>();
for (int i : arr)
arlist.add(i);
Collections.sort(arlist);
for (int i = 0; i < arr.length; i++)
arr[i] = arlist.get(i);
}
public void sort(long[] arr) {
ArrayList<Long> arlist = new ArrayList<>();
for (long i : arr)
arlist.add(i);
Collections.sort(arlist);
for (int i = 0; i < arr.length; i++)
arr[i] = arlist.get(i);
}
public int[] nextIntArray(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) throws IOException {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
public double[] nextDoubleArray(int n) throws IOException {
double[] arr = new double[n];
for (int i = 0; i < n; i++) {
arr[i] = nextDouble();
}
return arr;
}
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();
if (pw != null) pw.close();
}
}
} | Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 8 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | e395a0ab4ae9e6490e5302810a5198b3 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | //package Codeforces.Round716Div2;
import java.io.*;
import java.util.*;
public class First {
static class Query implements Comparable<Query>{
int id;
int start;
int end;
int blockno;
Query(int id, int start, int end, int blockno){
this.id = id;
this.start = start;
this.end = end;
this.blockno = blockno;
}
public int compareTo(Query q){
int c = Integer.compare(this.blockno, q.blockno);
if(c==0){
return Integer.compare(this.end, q.end);
}
else return c;
}
}
public static void main(String[] args) throws IOException {
v sc = new v();
int n = sc.nextInt();
int q = sc.nextInt();
int[] arr = sc.nextIntArray(n);
int blocksize = (int) Math.sqrt(n);
Query[] queries = new Query[q];
for(int i=0;i<q;i++){
int l = sc.nextInt()-1;
int r = sc.nextInt()-1;
int blockno = l/blocksize;
queries[i] = new Query(i, l, r, blockno);
}
Arrays.sort(queries);
int ll=0, ul=0;
int[] hash = new int[n+10];
int[] counter = new int[n+10];
hash[arr[0]] = 1;
counter[1] = 1;
int max = 1;
int[] output = new int[q];
for(Query query: queries){
while(ul<query.end){
ul++;
counter[hash[arr[ul]]]--;
hash[arr[ul]]++;
counter[hash[arr[ul]]]++;
max = Math.max(max, hash[arr[ul]]);
}
while(ll>query.start){
ll--;
counter[hash[arr[ll]]]--;
hash[arr[ll]]++;
counter[hash[arr[ll]]]++;
max = Math.max(max, hash[arr[ll]]);
}
while(ul>query.end){
counter[hash[arr[ul]]]--;
hash[arr[ul]]--;
counter[hash[arr[ul]]]++;
while(counter[max]==0)
max--;
ul--;
}
while(ll<query.start){
counter[hash[arr[ll]]]--;
hash[arr[ll]]--;
counter[hash[arr[ll]]]++;
while(counter[max]==0)
max--;
ll++;
}
/*System.out.println(Arrays.toString(hash));
System.out.println(Arrays.toString(counter));
System.out.println(query.id+" "+max);*/
int rangelength = (query.end-query.start+1);
int restfreq = rangelength-max;
if(restfreq<max){
output[query.id] = max-restfreq;
}
else{
output[query.id] = 1;
}
}
StringBuilder sb = new StringBuilder();
for(int i: output){
sb.append(i).append("\n");
}
System.out.println(sb);
sc.close();
}
static class v {
final private int BUFFER_SIZE = 1 << 18;
final private DataInputStream din;
final private byte[] buffer;
private PrintWriter pw;
private int bufferPointer, bytesRead;
StringTokenizer st;
public v() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public v(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public void streamOutput(String file) throws IOException {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
pw = new PrintWriter(bw);
}
public void println(String a) {
pw.println(a);
}
public void print(String a) {
pw.print(a);
}
public String readLine() throws IOException {
byte[] buf = new byte[3000064]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public void sort(int[] arr) {
ArrayList<Integer> arlist = new ArrayList<>();
for (int i : arr)
arlist.add(i);
Collections.sort(arlist);
for (int i = 0; i < arr.length; i++)
arr[i] = arlist.get(i);
}
public void sort(long[] arr) {
ArrayList<Long> arlist = new ArrayList<>();
for (long i : arr)
arlist.add(i);
Collections.sort(arlist);
for (int i = 0; i < arr.length; i++)
arr[i] = arlist.get(i);
}
public int[] nextIntArray(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) throws IOException {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
public double[] nextDoubleArray(int n) throws IOException {
double[] arr = new double[n];
for (int i = 0; i < n; i++) {
arr[i] = nextDouble();
}
return arr;
}
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;*/
if (din != null) din.close();
if (pw != null) pw.close();
}
}
}
| Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 8 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | 7706bbd4b48d762fe0a0547a4aca15b8 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | import java.io.*;
import java.util.*;
public class D {
public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
public static void main(String[] args) throws IOException {
readInput();
out.close();
}
static int n;
static int ans(int l, int r, int cur) {
int ll = -1, rr = g[cur].size();
while (ll+1<rr) {
// Floor
int m = (ll+rr)>>1;
if (g[cur].get(m) > r) rr = m;
else ll = m;
}
int top = ll;
ll = -1;
rr = g[cur].size();
while (ll+1<rr) {
// Floor
int m = (ll+rr)>>1;
if (g[cur].get(m) < l) ll = m;
else rr = m;
}
int bot = rr;
return top - bot +1;
}
static List<Integer>[] g;
public static void readInput() throws IOException {
// br = new BufferedReader(new FileReader(".in"));
// out = new PrintWriter(new FileWriter(".out"));
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
int q = Integer.parseInt(st.nextToken());
int[] a = new int[n];
g = new List[n+1];
for (int i = 0; i <= n; i++) g[i] = new ArrayList<Integer>();
st = new StringTokenizer(br.readLine());
for (int i= 0; i < n; i++) {
a[i] = Integer.parseInt(st.nextToken());
g[a[i]].add(i);
}
double[] randoms = new double[40];
for (int i = 0; i < randoms.length; i++) randoms[i] = Math.random();
while(q-->0) {
int ans = 1;
st = new StringTokenizer(br.readLine());
int l = Integer.parseInt(st.nextToken())-1;
int r = Integer.parseInt(st.nextToken())-1;
int len = (r-l+1);
for (int tq = 0; tq < 25; tq++) {
int rand = (int)(randoms[tq] * len) + l;
int cur = a[rand];
int cnt = ans(l,r,cur);
//out.println(cnt + " " + (len+1)/2);
if (cnt > (len+1)/2) {
int freq = cnt;
int opp = len-cnt;
int sol = 1;
freq-=(opp+1);
opp = 0;
sol += freq;
ans = sol;
break;
}
}
out.println(ans);
}
}
} | Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 8 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | 0c28f4254f4036d38ec306b41084b609 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | import java.io.*;
import java.util.*;
public class Practice1 {
private static int block_size;
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken()); int q = Integer.parseInt(st.nextToken());
block_size = (int) Math.sqrt(n);
int a[] = new int[n];
st = new StringTokenizer(br.readLine());
for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(st.nextToken());
Query[] qry = new Query[q];
for(int i = 0; i < q; ++i) {
st = new StringTokenizer(br.readLine());
qry[i] = new Query(Integer.parseInt(st.nextToken())-1,Integer.parseInt(st.nextToken())-1,i);
}
//mo's algorithm (sqrt decomposition)
int[] ans = new int[q];
Arrays.sort(qry);
int cur_l = 0, cur_r = -1;
int[] cnt = new int[n+1];
int[] max = new int[n+1];
max[0] = n;
int cur_max = 0;
for (Query e : qry) {
while (cur_l > e.l) {
--cur_l;
--max[cnt[a[cur_l]]];
++max[++cnt[a[cur_l]]];
if(max[cur_max+1]>0)++cur_max;
}
while (cur_r < e.r) {
++cur_r;
--max[cnt[a[cur_r]]];
++max[++cnt[a[cur_r]]];
if(max[cur_max+1]>0)++cur_max;
}
while (cur_l < e.l) {
--max[cnt[a[cur_l]]];
++max[--cnt[a[cur_l]]];
++cur_l;
if(max[cur_max]==0)--cur_max;
}
while (cur_r > e.r) {
--max[cnt[a[cur_r]]];
++max[--cnt[a[cur_r]]];
--cur_r;
if(max[cur_max]==0)--cur_max;
}
int opp = e.r-e.l+1-cur_max;
if(cur_max>opp)ans[e.idx]=cur_max-opp;
else ans[e.idx]=1;
}
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
for(int i = 0; i < q; ++i)pw.println(ans[i]);
pw.close();
}
private static class Query implements Comparable<Query>{
int l, r, idx;
public Query(int l, int r, int idx){
this.l = l;
this.r = r;
this.idx = idx;
}
@Override
public int compareTo(Query o) {
if(l/block_size==o.l/block_size) {
if(r==o.r)return idx-o.idx;
return r-o.r;
}
return l/block_size-o.l/block_size;
}
}
} | Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 8 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | adbd49af573af097770eec6841301082 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | import java.io.*;
import java.util.*;
/*
10 4
1 1 2 1 2 1 1 2 1 1
1 7
2 8
1 10
4 10
*/
public class D{
static FastReader sc=null;
static int nax=(int) 3e5+ 5;
static int counts[];
static int freq[];
static int ans=0;
static int a[];
public static void main(String[] args) {
sc=new FastReader();
PrintWriter out=new PrintWriter(System.out);
int n=sc.nextInt(),q=sc.nextInt();
a=sc.readArray(n);
for(int i=0;i<n;i++)a[i]--;
//print(a);
int block=(int)Math.max(1,(int)Math.sqrt(n));
counts=new int[nax];
freq=new int[nax];
int p[]=new int[q];
Pair queries[]=new Pair[q];
for(int i=0;i<q;i++) {
queries[i]=new Pair(i,sc.nextInt()-1,sc.nextInt()-1,block);
}
Arrays.sort(queries);
for(int i=0,l=0,r=-1;i<q;i++) {
while(r<queries[i].r)add(++r);
while(l>queries[i].l)add(--l);
while(r>queries[i].r)remove(r--);
while(l<queries[i].l)remove(l++);
p[queries[i].id]=get(ans,r-l+1);
}
for(int i:p)out.println(i);
out.close();
}
static int get(int count,int size) {
if(count<=(size+1)/2)return 1;
return 2*count-size;
}
static void add(int x) {
freq[counts[a[x]]]--;
freq[++counts[a[x]]]++;
if(freq[ans+1]>0)ans++;
}
static void remove(int x) {
freq[counts[a[x]]--]--;
freq[counts[a[x]]]++;
if(freq[ans]==0)ans--;
}
static class Pair implements Comparable<Pair>{
int id,l,r,lb;
Pair(int id,int l,int r,int block){
this.id=id;
this.l=l;
this.r=r;
this.lb=l/block;
}
@Override
public int compareTo(Pair o) {
if(this.lb==o.lb) {
if((this.lb & 1)>0)return this.r-o.r;
else return o.r-this.r;
}
return this.lb-o.lb;
//return this.l-o.l;
}
@Override
public String toString() {
return "Pair [id=" + id + ", l=" + l + ", r=" + r + ", lb=" + lb + "]";
}
}
static int[] ruffleSort(int a[]) {
ArrayList<Integer> al=new ArrayList<>();
for(int i:a)al.add(i);
Collections.sort(al);
for(int i=0;i<a.length;i++)a[i]=al.get(i);
return a;
}
static void print(int a[]) {
for(int e:a) {
System.out.print(e+" ");
}
System.out.println();
}
static class FastReader{
StringTokenizer st=new StringTokenizer("");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
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());
}
long nextLong() {
return Long.parseLong(next());
}
int[] readArray(int n) {
int a[]=new int[n];
for(int i=0;i<n;i++)a[i]=sc.nextInt();
return a;
}
}
}
| Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 8 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | c92ba995b280601bdd10a7de708a7dba | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | import java.io.*;
import java.util.*;
/*
10 4
1 1 2 1 2 1 1 2 1 1
1 7
2 8
1 10
4 10
*/
public class D2{
static FastReader sc=null;
static ArrayList<Integer> pos[];
public static void main(String[] args) {
sc=new FastReader();
PrintWriter out=new PrintWriter(System.out);
int n=sc.nextInt(),q=sc.nextInt();
int a[]=sc.readArray(n);
pos=new ArrayList[n];
for(int i=0;i<n;i++)pos[i]=new ArrayList<>();
for(int i=0;i<n;i++) {
a[i]--;
pos[a[i]].add(i);
}
int p[]=new int[q];
for(int i=0;i<q;i++) {
int l=sc.nextInt()-1,r=sc.nextInt()-1;
int size=r-l+1;
int ans=1;
for(int j=0;j<25;j++) {
double rand=Math.random();
int id=(int)(rand*size+l);
int val=a[id];
int count=bsR(val,r)-bsL(val,l)+1;
if(count<=(size+1)/2)continue;
ans=2*count-size;
break;
}
p[i]=ans;
}
for(int i:p)out.println(i);
out.close();
}
static int bsR(int val,int b) {
int l=-1,r=pos[val].size();
while(l+1<r) {
int mid=(l+r)>>1;
if(pos[val].get(mid)>b)r=mid;
else l=mid;
}
return l;
}
static int bsL(int val,int b) {
int l=-1,r=pos[val].size();
while(l+1<r) {
int mid=(l+r)>>1;
if(pos[val].get(mid)<b)l=mid;
else r=mid;
}
return r;
}
static int[] ruffleSort(int a[]) {
ArrayList<Integer> al=new ArrayList<>();
for(int i:a)al.add(i);
Collections.sort(al);
for(int i=0;i<a.length;i++)a[i]=al.get(i);
return a;
}
static void print(int a[]) {
for(int e:a) {
System.out.print(e+" ");
}
System.out.println();
}
static class FastReader{
StringTokenizer st=new StringTokenizer("");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
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());
}
long nextLong() {
return Long.parseLong(next());
}
int[] readArray(int n) {
int a[]=new int[n];
for(int i=0;i<n;i++)a[i]=sc.nextInt();
return a;
}
}
}
| Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 8 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | 85fd0df7771752afe7c76a204fd56b8e | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | import java.io.*;
import java.util.*;
/*
10 4
1 1 2 1 2 1 1 2 1 1
1 7
2 8
1 10
4 10
*/
public class D2{
static FastReader sc=null;
static Random rand=new Random();
static int nax=(int)1e6;
static ArrayList<Integer> pos[];
public static void main(String[] args) {
sc=new FastReader();
PrintWriter out=new PrintWriter(System.out);
int n=sc.nextInt(),q=sc.nextInt();
int a[]=sc.readArray(n);
pos=new ArrayList[n];
for(int i=0;i<n;i++)pos[i]=new ArrayList<>();
for(int i=0;i<n;i++) {
a[i]--;
pos[a[i]].add(i);
}
int p[]=new int[q];
for(int i=0;i<q;i++) {
int l=sc.nextInt()-1,r=sc.nextInt()-1;
int size=r-l+1;
int ans=1;
for(int j=0;j<25;j++) {
int id=rand.nextInt(nax);
id=id%size+l;
int val=a[id];
int count=bsR(val,r)-bsL(val,l)+1;
if(count<=(size+1)/2)continue;
ans=2*count-size;
break;
}
p[i]=ans;
}
for(int i:p)out.println(i);
out.close();
}
static int bsR(int val,int b) {
int l=-1,r=pos[val].size();
while(l+1<r) {
int mid=(l+r)>>1;
if(pos[val].get(mid)>b)r=mid;
else l=mid;
}
return l;
}
static int bsL(int val,int b) {
int l=-1,r=pos[val].size();
while(l+1<r) {
int mid=(l+r)>>1;
if(pos[val].get(mid)<b)l=mid;
else r=mid;
}
return r;
}
static int[] ruffleSort(int a[]) {
ArrayList<Integer> al=new ArrayList<>();
for(int i:a)al.add(i);
Collections.sort(al);
for(int i=0;i<a.length;i++)a[i]=al.get(i);
return a;
}
static void print(int a[]) {
for(int e:a) {
System.out.print(e+" ");
}
System.out.println();
}
static class FastReader{
StringTokenizer st=new StringTokenizer("");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
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());
}
long nextLong() {
return Long.parseLong(next());
}
int[] readArray(int n) {
int a[]=new int[n];
for(int i=0;i<n;i++)a[i]=sc.nextInt();
return a;
}
}
}
| Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 8 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | 5113e3461f1b0e867edd35e22f09e0d8 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
import java.math.BigInteger;
//import javafx.util.*;
public final class B
{
static StringBuilder ans=new StringBuilder();
static FastReader in=new FastReader();
static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
static ArrayList<ArrayList<Integer>> g;
static long mod=(long)(1e9+7);
static int D1[],D2[],par[];
static boolean set[];
static int value[];
static long INF=Long.MAX_VALUE;
static int dp[][];
static int N,M;
static int A[][],B[][];
public static void main(String args[])throws IOException
{
int N=i(),Q=i();
int A[]=input(N);
int block_size=(int)Math.sqrt(N);
ArrayList<node> query=new ArrayList<>();
int t[]=new int[Q]; //stores the answers
for(int i=0; i<Q; i++)
{
query.add(new node(i()-1,i()-1,i,block_size));
}
Collections.sort(query);
int f[]=new int[N+1];
int max[]=new int[N+1];
max[0]=N;
int mo_left=0,mo_right=-1;
int m=0;
for(node x:query)
{
int l=x.l,r=x.r;
while(mo_right<r)
{
++mo_right;
--max[f[A[mo_right]]];
++max[++f[A[mo_right]]];
if(max[m+1]>0)++m;
}
while(mo_right>r)
{
--max[f[A[mo_right]]];
++max[--f[A[mo_right]]];
if(max[m]==0)--m;
--mo_right;
}
while(mo_left>l)
{
--mo_left;
--max[f[A[mo_left]]];
++max[++f[A[mo_left]]];
if(max[m+1]>0)++m;
}
while(mo_left<l)
{
--max[f[A[mo_left]]];
++max[--f[A[mo_left]]];
if(max[m]==0)--m;
++mo_left;
}
int len=(r-l)+1;
int n=len-m;
n++;
int a=1;
a+=Math.max(0, m-n);
t[x.index]=a;
}
for(int a:t)ans.append(a+"\n");
out.println(ans);
out.close();
}
static int apt(int x,ArrayList<Integer> A)
{
int l=-1,r=A.size();
while(r-l>1)
{
int m=(l+r)/2;
int a=A.get(m);
if(a>=x)r=m;
else l=m;
}
return r;
}
static int find(int x,ArrayList<Integer> A)
{
int l=0,r=A.size()-1;
while(l<=r)
{
int m=(l+r)/2;
int a=A.get(m);
if(a==x)return m;
if(a<x)l=m+1;
else r=m-1;
}
return 0;
}
static boolean isSorted(int A[])
{
int N=A.length;
for(int i=0; i<N-1; i++)
{
if(A[i]>A[i+1])return false;
}
return true;
}
static int f1(int x,ArrayList<Integer> A)
{
int l=-1,r=A.size();
while(r-l>1)
{
int m=(l+r)/2;
int a=A.get(m);
if(a<x)l=m;
else r=m;
}
return l;
}
static int ask(int t,int i,int j,int x)
{
System.out.println("? "+t+" "+i+" "+j+" "+x);
return i();
}
static int ask(int a)
{
System.out.println("? 1 "+a);
return i();
}
static int f(int st,int end,int d)
{
if(st>end)return 0;
int a=0,b=0,c=0;
if(d>1)a=f(st+d-1,end,d-1);
b=f(st+d,end,d);
c=f(st+d+1,end,d+1);
return value[st]+max(a,b,c);
}
static int max(int a,int b,int c)
{
return Math.max(a, Math.max(c, b));
}
static int value(char X[],char Y[])
{
int c=0;
for(int i=0; i<7; i++)
{
if(Y[i]=='1' && X[i]=='0')return -1;
if(X[i]=='1' && Y[i]=='0')c++;
}
return c;
}
static boolean isValid(int i,int j)
{
if(i<0 || i>=N)return false;
if(j<0 || j>=M)return false;
return true;
}
static long fact(long N)
{
long num=1L;
while(N>=1)
{
num=((num%mod)*(N%mod))%mod;
N--;
}
return num;
}
static boolean reverse(long A[],int l,int r)
{
while(l<r)
{
long t=A[l];
A[l]=A[r];
A[r]=t;
l++;
r--;
}
if(isSorted(A))return true;
else return false;
}
static boolean isSorted(long A[])
{
for(int i=1; i<A.length; i++)if(A[i]<A[i-1])return false;
return true;
}
static boolean isPalindrome(char X[],int l,int r)
{
while(l<r)
{
if(X[l]!=X[r])return false;
l++; r--;
}
return true;
}
static long min(long a,long b,long c)
{
return Math.min(a, Math.min(c, b));
}
static void print(int a)
{
System.out.println("! "+a);
}
static int ask(int a,int b)
{
System.out.println("? "+a+" "+b);
return i();
}
static int find(int a)
{
if(par[a]<0)return a;
return par[a]=find(par[a]);
}
static void union(int a,int b)
{
a=find(a);
b=find(b);
if(a!=b)
{
par[a]+=par[b]; //transfers the size
par[b]=a; //changes the parent
}
}
static void swap(char A[],int a,int b)
{
char ch=A[a];
A[a]=A[b];
A[b]=ch;
}
static void sort(long[] a) //check for long
{
ArrayList<Long> l=new ArrayList<>();
for (long i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static void setGraph(int N)
{
g=new ArrayList<ArrayList<Integer>>();
for(int i=0; i<=N; i++)
{
g.add(new ArrayList<Integer>());
}
}
static long pow(long a,long b)
{
long mod=1000000007;
long pow=1;
long x=a;
while(b!=0)
{
if((b&1)!=0)pow=(pow*x)%mod;
x=(x*x)%mod;
b/=2;
}
return pow;
}
static long toggleBits(long x)//one's complement || Toggle bits
{
int n=(int)(Math.floor(Math.log(x)/Math.log(2)))+1;
return ((1<<n)-1)^x;
}
static int countBits(long a)
{
return (int)(Math.log(a)/Math.log(2)+1);
}
static void sort(int[] a) {
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static boolean isPrime(long N)
{
if (N<=1) return false;
if (N<=3) return true;
if (N%2 == 0 || N%3 == 0) return false;
for (int i=5; i*i<=N; i=i+6)
if (N%i == 0 || N%(i+2) == 0)
return false;
return true;
}
static long GCD(long a,long b)
{
if(b==0)
{
return a;
}
else return GCD(b,a%b );
}
//Debugging Functions Starts
static void print(char A[])
{
for(char c:A)System.out.print(c+" ");
System.out.println();
}
static void print(boolean A[])
{
for(boolean c:A)System.out.print(c+" ");
System.out.println();
}
static void print(int A[])
{
for(int a:A)System.out.print(a+" ");
System.out.println();
}
static void print(long A[])
{
for(long i:A)System.out.print(i+ " ");
System.out.println();
}
static void print(ArrayList<Integer> A)
{
for(int a:A)System.out.print(a+" ");
System.out.println();
}
//Debugging Functions END
//----------------------
//IO FUNCTIONS STARTS
static HashMap<Integer,Integer> Hash(int A[])
{
HashMap<Integer,Integer> mp=new HashMap<>();
for(int a:A)
{
int f=mp.getOrDefault(a,0)+1;
mp.put(a, f);
}
return mp;
}
static int i()
{
return in.nextInt();
}
static long l()
{
return in.nextLong();
}
static int[] input(int N){
int A[]=new int[N];
for(int i=0; i<N; i++)
{
A[i]=in.nextInt();
}
return A;
}
static long[] inputLong(int N) {
long A[]=new long[N];
for(int i=0; i<A.length; i++)A[i]=in.nextLong();
return A;
}
//IO FUNCTIONS END
}
class node implements Comparable<node>//we need l we need r we need index
{
int l,r,index,bs;
node(int l,int r,int index,int bs)
{
this.l=l;
this.r=r;
this.index=index;
this.bs=bs;
}
public int compareTo(node X)
{
int a=this.l/this.bs,b=X.l/X.bs;
if(a==b)return this.r-X.r;
else return a-b;
}
}
//Code For FastReader
//Code For FastReader
//Code For FastReader
//Code For FastReader
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());
}
//gey
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str="";
try
{
str=br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
} | Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 8 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | 16f03c11db9e603d6e1c7e6a9974f9da | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | // Credits: MagentaCobra
// Reason: Can't cope with sluggish Java.
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import static java.lang.System.out;
import java.util.*;
import java.io.*;
import java.math.*;
public class x1514D
{
public static void main(String hi[]) throws Exception
{
FastScanner infile = new FastScanner();
int N = infile.nextInt();
int Q = infile.nextInt();
int[] arr = infile.nextInts(N);
Query[] qq = new Query[Q];
for(int i=0; i < Q; i++)
{
int a = infile.nextInt();
int b = infile.nextInt();
qq[i] = new Query(a-1, b-1, i);
}
Arrays.sort(qq);
int[] res = new int[Q];
//do first query
int[] freq = new int[N+1];
int[] vals = new int[N+1];
for(int i=qq[0].left; i <= qq[0].right; i++)
freq[arr[i]]++;
for(int v=0; v <= N; v++)
vals[freq[v]]++;
int large = 0;
for(int v=1; v <= N; v++)
if(vals[v] > 0)
large = v;
res[qq[0].id] = get(qq[0].right-qq[0].left+1, large);
int L = qq[0].left;
int R = qq[0].right;
for(int q=1; q < Q; q++)
{
//extend out then in
int left = qq[q].left;
int right = qq[q].right;
while(L > left)
{
L--;
freq[arr[L]]++;
int f = freq[arr[L]];
vals[f-1]--;
vals[f]++;
if(large < f)
large = f;
}
while(R < right)
{
R++;
freq[arr[R]]++;
int f = freq[arr[R]];
vals[f-1]--;
vals[f]++;
if(large < f)
large = f;
}
//shrink
while(L < left)
{
int f = freq[arr[L]];
freq[arr[L]]--;
vals[f-1]++;
vals[f]--;
if(vals[large] == 0)
large--;
L++;
}
while(R > right)
{
int f = freq[arr[R]];
freq[arr[R]]--;
vals[f-1]++;
vals[f]--;
if(vals[large] == 0)
large--;
R--;
}
res[qq[q].id] = get(right-left+1, large);
}
StringBuilder sb = new StringBuilder();
for(int x: res)
sb.append(x+"\n");
System.out.print(sb);
}
public static int get(int N, int K)
{
if(K <= ((N+1)>>1))
return 1;
int small = N-K;
return K-small;
}
}
class Query implements Comparable<Query>
{
public int left;
public int right;
public int id;
public int SQRT = 548;
public Query(int a, int b, int i)
{
left = a;
right = b;
id = i;
}
public int compareTo(Query oth)
{
if(left/SQRT == oth.left/SQRT)
return right-oth.right;
return left/SQRT-oth.left/SQRT;
}
}
/*
a subsequence is valid if you can rearrange it such that no two adjacents are the same value
process queries offline? (left then right or something else)
mo's will almost definitely tle (with segtree)
maybe it'll pass with O(1) extra stuff
*/
class FastScanner
{
private int BS = 1 << 16;
private char NC = (char) 0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
} catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
private char getChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1) return NC;
bId = 0;
}
return (char) buf[bId++];
}
public int nextInt() {
return (int) nextLong();
}
public int[] nextInts(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] nextLongs(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public long nextLong() {
cnt = 1;
boolean neg = false;
if (c == NC) c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-') neg = true;
}
long res = 0;
for (; c >= '0' && c <= '9'; c = getChar()) {
res = (res << 3) + (res << 1) + c - '0';
cnt *= 10;
}
return neg ? -res : res;
}
public double nextDouble() {
double cur = nextLong();
return c != '.' ? cur : cur + nextLong() / cnt;
}
public double[] nextDoubles(int N) {
double[] res = new double[N];
for (int i = 0; i < N; i++) {
res[i] = nextDouble();
}
return res;
}
public String next() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
public boolean hasNext() {
if (c > 32) return true;
while (true) {
c = getChar();
if (c == NC) return false;
else if (c > 32) return true;
}
}
} | Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 8 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | ad289b761029db9f62722ce4d1ef8b7b | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | import java.util.*;import java.io.*;import java.math.*;
public class Main
{
static int block;
static class Node
{
int l,r,ind;
Node(int l,int r,int ind)
{
this.l=l;
this.r=r;
this.ind=ind;
}
}
public static class CustomSort implements Comparator<Node>{
public int compare(Node a,Node b){
if(a.l/block!=b.l/block)
return a.l-b.l;
return (a.r-b.r);
}
}
public static void process()throws IOException
{
int n=ni();
int m=ni();
block=(int)Math.sqrt(n);
int[]freq=new int[n+1];
int[]counter=new int[n+1];
int[]A=nai(n);
Node[]q=new Node[m];
int[]ans=new int[m];
for(int i=0;i<m;i++)
q[i]=new Node(ni()-1,ni()-1,i);
Arrays.sort(q,new CustomSort());
// for(int i=0;i<m;i++)
// System.err.println(q[i].l+" "+q[i].r+" "+q[i].ind);
int curl = 1, curr = 0;
int t_ans = 0;
for(int i=0;i<m;i++){
int l = q[i].l;
int r = q[i].r;
while(curr < r){
++curr;
int val = A[curr];
int c = freq[val];
counter[c]--;
freq[val]++;
counter[freq[val]]++;
t_ans = Math.max(t_ans, freq[val]);
}
while(curl > l){
--curl;
int val = A[curl];
int c = freq[val];
counter[c]--;
freq[val]++;
counter[freq[val]]++;
t_ans = Math.max(t_ans, freq[val]);
}
while(curr > r){
int val = A[curr];
int c = freq[val];
counter[c]--;
freq[val]--;
counter[freq[val]]++;
while(counter[t_ans] == 0) t_ans--;
--curr;
}
while(curl < l){
int val = A[curl];
counter[freq[val]]--;
freq[val]--;
counter[freq[val]]++;
while(counter[t_ans] == 0) t_ans--;
++curl;
}
ans[q[i].ind] = Math.max(2*t_ans-(r-l+1),1);
}
for(int i=0;i<m;i++)
pn(ans[i]);
}
static AnotherReader sc;
static PrintWriter out;
public static void main(String[]args)throws IOException
{
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
if(oj){sc=new AnotherReader();out=new PrintWriter(System.out);}
else{sc=new AnotherReader(100);out=new PrintWriter("output.txt");}
int t=1;
// t=ni();
while(t-->0) {process();}
out.flush();out.close();
}
static void pn(Object o){out.println(o);}
static void p(Object o){out.print(o);}
static void pni(Object o){out.println(o);out.flush();}
static int ni()throws IOException{return sc.nextInt();}
static long nl()throws IOException{return sc.nextLong();}
static double nd()throws IOException{return sc.nextDouble();}
static String nln()throws IOException{return sc.nextLine();}
static int[] nai(int N)throws IOException{int[]A=new int[N];for(int i=0;i!=N;i++){A[i]=ni();}return A;}
static long[] nal(int N)throws IOException{long[]A=new long[N];for(int i=0;i!=N;i++){A[i]=nl();}return A;}
static long gcd(long a, long b)throws IOException{return (b==0)?a:gcd(b,a%b);}
static int gcd(int a, int b)throws IOException{return (b==0)?a:gcd(b,a%b);}
static int bit(long n)throws IOException{return (n==0)?0:(1+bit(n&(n-1)));}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
static class AnotherReader{BufferedReader br; StringTokenizer st;
AnotherReader()throws FileNotFoundException{
br=new BufferedReader(new InputStreamReader(System.in));}
AnotherReader(int a)throws FileNotFoundException{
br = new BufferedReader(new FileReader("input.txt"));}
String next()throws IOException{
while (st == null || !st.hasMoreElements()) {try{
st = new StringTokenizer(br.readLine());}
catch (IOException e){ e.printStackTrace(); }}
return st.nextToken(); } int nextInt() throws IOException{
return Integer.parseInt(next());}
long nextLong() throws IOException
{return Long.parseLong(next());}
double nextDouble()throws IOException { return Double.parseDouble(next()); }
String nextLine() throws IOException{ String str = ""; try{
str = br.readLine();} catch (IOException e){
e.printStackTrace();} return str;}}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
} | Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 8 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | 2da9ce6224d1a49b4b4511702cde9f04 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
/**
*
* @Har_Har_Mahadev
*/
public class D {
private static long INF = 2000000000000000000L, M = 1000000007, MM = 998244353;
static int N = 4_000_01;
static int Block = (int) sqrt(N);
static int arr[] = new int[N];
static int ans[] = new int[N];
static int fre[] = new int[N];
static int freOfFre[] = new int[N];
static int currMax = 0;
static class Query implements Comparable<Query>{
int l,r,index;
public Query(int l,int r, int index) {
this.l = l;
this.r = r;
this.index = index;
}
@Override
public int compareTo(Query o) {
int a = l/Block;
int b = o.l/Block;
if(a == b)return Integer.compare(r, o.r);
return Integer.compare(l, o.l);
}
}
private static void add(int pos) {
int preF = fre[arr[pos]];
fre[arr[pos]]++;
int currF = fre[arr[pos]];
freOfFre[preF]--;
freOfFre[currF]++;
if(currF > currMax)
{
currMax = currF;
}
}
private static void remove(int pos) {
int preF = fre[arr[pos]];
fre[arr[pos]]--;
int currF = fre[arr[pos]];
freOfFre[preF]--;
freOfFre[currF]++;
if(currF < currMax)
{
while(freOfFre[currMax] == 0)
currMax--;
}
}
public static void process() throws IOException {
int n = sc.nextInt(),q = sc.nextInt();
for(int i=0; i<n; i++)arr[i] = sc.nextInt();
ArrayList<Query> lis = new ArrayList<Query>();
for(int i=0; i<q; i++) {
int l = sc.nextInt(),r = sc.nextInt();
lis.add(new Query(l-1, r-1, i));
}
Collections.sort(lis);
// for(Query e : lis)System.out.println(e.l+" "+e.r+" "+e.index);
int ml = 0, mr = -1;
for(int i=0; i<q; i++) {
int l = lis.get(i).l;
int r = lis.get(i).r;
// extended
while(ml > l) {
ml--;
add(ml);
}
while(mr < r) {
mr++;
add(mr);
}
// reduces
while(ml < l) {
remove(ml);
ml++;
}
while(mr > r) {
remove(mr);
mr--;
}
// answers
int total = lis.get(i).r - lis.get(i).l + 1;
int rem = total - currMax;
int half = (total+1)/2;
if(currMax <= half)
ans[lis.get(i).index] = 1;
else
{
ans[lis.get(i).index] = total - 2*rem;
}
}
for(int i=0; i<q; i++) {
println(ans[i]);
}
}
//=============================================================================
//--------------------------The End---------------------------------
//=============================================================================
static FastScanner sc;
static PrintWriter out;
public static void main(String[] args) throws IOException {
boolean oj = true;
if (oj) {
sc = new FastScanner();
out = new PrintWriter(System.out);
} else {
sc = new FastScanner(100);
out = new PrintWriter("output.txt");
}
int t = 1;
// t = sc.nextInt();
while (t-- > 0) {
process();
}
out.flush();
out.close();
}
static class Pair implements Comparable<Pair> {
int x, y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Pair o) {
return Integer.compare(this.x, o.x);
}
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (!(o instanceof Pair)) return false;
// Pair key = (Pair) o;
// return x == key.x && y == key.y;
// }
//
// @Override
// public int hashCode() {
// int result = x;
// result = 31 * result + y;
// return result;
// }
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
static void println(Object o) {
out.println(o);
}
static void println() {
out.println();
}
static void print(Object o) {
out.print(o);
}
static void pflush(Object o) {
out.println(o);
out.flush();
}
static int ceil(int x, int y) {
return (x % y == 0 ? x / y : (x / y + 1));
}
static long ceil(long x, long y) {
return (x % y == 0 ? x / y : (x / y + 1));
}
static int max(int x, int y) {
return Math.max(x, y);
}
static int min(int x, int y) {
return Math.min(x, y);
}
static int abs(int x) {
return Math.abs(x);
}
static long abs(long x) {
return Math.abs(x);
}
static long sqrt(long z) {
long sqz = (long) Math.sqrt(z);
while (sqz * 1L * sqz < z) {
sqz++;
}
while (sqz * 1L * sqz > z) {
sqz--;
}
return sqz;
}
static int log2(int N) {
int result = (int) (Math.log(N) / Math.log(2));
return result;
}
static long max(long x, long y) {
return Math.max(x, y);
}
static long min(long x, long y) {
return Math.min(x, y);
}
public static int gcd(int a, int b) {
BigInteger b1 = BigInteger.valueOf(a);
BigInteger b2 = BigInteger.valueOf(b);
BigInteger gcd = b1.gcd(b2);
return gcd.intValue();
}
public static long gcd(long a, long b) {
BigInteger b1 = BigInteger.valueOf(a);
BigInteger b2 = BigInteger.valueOf(b);
BigInteger gcd = b1.gcd(b2);
return gcd.longValue();
}
public static long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
public static int lcm(int a, int b) {
return (a * b) / gcd(a, b);
}
public static int lower_bound(int[] arr, int x) {
int low = 0, high = arr.length, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] >= x)
high = mid;
else
low = mid + 1;
}
return low;
}
public static int upper_bound(int[] arr, int x) {
int low = 0, high = arr.length, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] > x)
high = mid;
else
low = mid + 1;
}
return low;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner() throws FileNotFoundException {
br = new BufferedReader(new InputStreamReader(System.in));
}
FastScanner(int a) throws FileNotFoundException {
br = new BufferedReader(new FileReader("input.txt"));
}
String next() throws IOException {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
String nextLine() throws IOException {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] readArray(int n) throws IOException {
int[] A = new int[n];
for (int i = 0; i != n; i++) {
A[i] = sc.nextInt();
}
return A;
}
long[] readArrayLong(int n) throws IOException {
long[] A = new long[n];
for (int i = 0; i != n; i++) {
A[i] = sc.nextLong();
}
return A;
}
}
static void ruffleSort(int[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
Arrays.sort(a);
}
static void ruffleSort(long[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
long temp = a[i];
a[i] = a[r];
a[r] = temp;
}
Arrays.sort(a);
}
}
| Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 8 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | bcbb8f5db4a77d0893f770f34bbda43c | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | import java.io.*;
import java.util.*;
public class Main{
static int[]occ,occofocc;
static int maxOcc;
static void add(int x) {
occofocc[occ[x]]--;
occ[x]++;
occofocc[occ[x]]++;
maxOcc=Math.max(maxOcc, occ[x]);
}
static void remove(int x) {
occofocc[occ[x]]--;
occ[x]--;
occofocc[occ[x]]++;
if(occofocc[maxOcc]==0) {
maxOcc--;
}
}
static int solve(int occ,int len) {
int ll = len - occ;
occ -= ll;
occ--;
return 1 + Math.max(0, occ);
}
static void main() throws Exception{
int n=sc.nextInt();
int q=sc.nextInt();
int[]in=sc.intArr(n);
final int sq=(int)(Math.sqrt(n)+1);
int[][]qs=new int[q][4];
for(int i=0;i<q;i++) {
for(int j=0;j<2;j++) {
qs[i][j]=sc.nextInt()-1;
}
qs[i][2]=i;
qs[i][3]=qs[i][0]/sq;
}
int[]ans=new int[q];
Arrays.sort(qs,(x,y)->(x[3])!=(y[3])?(x[3])-(y[3]):x[1]-y[1]);
occ=new int[n+7];occofocc=new int[n+7];
occofocc[0]=n;
int curL = qs[0][0];
int curR = curL-1;
for(int idxq=0;idxq<q;idxq++) {
int l=qs[idxq][0],r=qs[idxq][1];
while(curL > l) {
curL--;
add(in[curL]);
}
while(curR < r) {
curR++;
add(in[curR]);
}
while(curL < l) {
remove(in[curL]);
curL++;
}
while(curR > r) {
remove(in[curR]);
curR--;
}
ans[qs[idxq][2]] = solve(maxOcc, r-l+1);
}
for(int i=0;i<q;i++) {
pw.println(ans[i]);
}
}
public static void main(String[] args) throws Exception{
sc=new MScanner(System.in);
pw = new PrintWriter(System.out);
int tc=1;
// tc=sc.nextInt();
for(int i=1;i<=tc;i++) {
// pw.printf("Case #%d:", i);
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[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt();
return in;
}
public long[] longArr(int n) throws IOException {
long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong();
return in;
}
public int[] intSortedArr(int n) throws IOException {
int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt();
shuffle(in);
Arrays.sort(in);
return in;
}
public long[] longSortedArr(int n) throws IOException {
long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong();
shuffle(in);
Arrays.sort(in);
return in;
}
public Integer[] IntegerArr(int n) throws IOException {
Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt();
return in;
}
public Long[] LongArr(int n) throws IOException {
Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=nextLong();
return in;
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
static void sort(int[]in) {
shuffle(in);
Arrays.sort(in);
}
static void sort(long[]in) {
shuffle(in);
Arrays.sort(in);
}
static void shuffle(int[]in) {
for(int i=0;i<in.length;i++) {
int idx=(int)(Math.random()*in.length);
int tmp=in[i];
in[i]=in[idx];
in[idx]=tmp;
}
}
static void shuffle(long[]in) {
for(int i=0;i<in.length;i++) {
int idx=(int)(Math.random()*in.length);
long tmp=in[i];
in[i]=in[idx];
in[idx]=tmp;
}
}
} | Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 8 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | ade47dac2dc954f8f8b016185e626d56 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | import java.io.*;
import java.util.*;
public class Main{
static int[]occ,occofocc;
static int maxOcc;
static void add(int x) {
occofocc[occ[x]]--;
occ[x]++;
occofocc[occ[x]]++;
maxOcc=Math.max(maxOcc, occ[x]);
}
static void remove(int x) {
occofocc[occ[x]]--;
occ[x]--;
occofocc[occ[x]]++;
if(occofocc[maxOcc]==0) {
maxOcc--;
}
}
static int solve(int occ,int curlen) {
int lo=0,hi=occ-1;
int ans=hi;
while(lo<=hi) {
int mid=(lo+hi)>>1;
int num=occ-mid,den=curlen-mid;
if(num<=(den+1)/2) {
ans=mid;
hi=mid-1;
}
else {
lo=mid+1;
}
}
return ans+1;
}
static void main() throws Exception{
int n=sc.nextInt();
int q=sc.nextInt();
int[]in=sc.intArr(n);
final int sq=(int)(Math.sqrt(n)+1);
int[][]qs=new int[q][4];
for(int i=0;i<q;i++) {
for(int j=0;j<2;j++) {
qs[i][j]=sc.nextInt()-1;
}
qs[i][2]=i;
qs[i][3]=qs[i][0]/sq;
}
int[]ans=new int[q];
Arrays.sort(qs,(x,y)->(x[3])!=(y[3])?(x[3])-(y[3]):x[1]-y[1]);
occ=new int[n+7];occofocc=new int[n+7];
occofocc[0]=n;
int curL = qs[0][0];
int curR = curL-1;
for(int idxq=0;idxq<q;idxq++) {
int l=qs[idxq][0],r=qs[idxq][1];
while(curL > l) {
curL--;
add(in[curL]);
}
while(curR < r) {
curR++;
add(in[curR]);
}
while(curL < l) {
remove(in[curL]);
curL++;
}
while(curR > r) {
remove(in[curR]);
curR--;
}
ans[qs[idxq][2]] = solve(maxOcc, r-l+1);
}
for(int i=0;i<q;i++) {
pw.println(ans[i]);
}
}
public static void main(String[] args) throws Exception{
sc=new MScanner(System.in);
pw = new PrintWriter(System.out);
int tc=1;
// tc=sc.nextInt();
for(int i=1;i<=tc;i++) {
// pw.printf("Case #%d:", i);
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[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt();
return in;
}
public long[] longArr(int n) throws IOException {
long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong();
return in;
}
public int[] intSortedArr(int n) throws IOException {
int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt();
shuffle(in);
Arrays.sort(in);
return in;
}
public long[] longSortedArr(int n) throws IOException {
long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong();
shuffle(in);
Arrays.sort(in);
return in;
}
public Integer[] IntegerArr(int n) throws IOException {
Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt();
return in;
}
public Long[] LongArr(int n) throws IOException {
Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=nextLong();
return in;
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
static void sort(int[]in) {
shuffle(in);
Arrays.sort(in);
}
static void sort(long[]in) {
shuffle(in);
Arrays.sort(in);
}
static void shuffle(int[]in) {
for(int i=0;i<in.length;i++) {
int idx=(int)(Math.random()*in.length);
int tmp=in[i];
in[i]=in[idx];
in[idx]=tmp;
}
}
static void shuffle(long[]in) {
for(int i=0;i<in.length;i++) {
int idx=(int)(Math.random()*in.length);
long tmp=in[i];
in[i]=in[idx];
in[idx]=tmp;
}
}
} | Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 8 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | 2416808ff548e640d47a75cf0b9f0f74 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | import java.io.*;
import java.util.*;
public class Main{
static int[]occ,occofocc;
static int maxOcc;
static void add(int x) {
occofocc[occ[x]]--;
occ[x]++;
occofocc[occ[x]]++;
maxOcc=Math.max(maxOcc, occ[x]);
}
static void remove(int x) {
occofocc[occ[x]]--;
occ[x]--;
occofocc[occ[x]]++;
if(occofocc[maxOcc]==0) {
maxOcc--;
}
}
static int solve(int occ,int curlen) {
int lo=0,hi=occ-1;
int ans=hi;
while(lo<=hi) {
int mid=(lo+hi)>>1;
int num=occ-mid,den=curlen-mid;
if(num<=(den+1)/2) {
ans=mid;
hi=mid-1;
}
else {
lo=mid+1;
}
}
return ans+1;
}
static void main() throws Exception{
int n=sc.nextInt();
int q=sc.nextInt();
int[]in=sc.intArr(n);
final int sq=600;
int[][]qs=new int[q][4];
for(int i=0;i<q;i++) {
for(int j=0;j<2;j++) {
qs[i][j]=sc.nextInt()-1;
}
qs[i][2]=i;
qs[i][3]=qs[i][0]/sq;
}
int[]ans=new int[q];
Arrays.sort(qs,(x,y)->(x[3])!=(y[3])?(x[3])-(y[3]):x[1]-y[1]);
occ=new int[n+7];occofocc=new int[n+7];
occofocc[0]=n;
int curL = qs[0][0];
int curR = curL-1;
for(int idxq=0;idxq<q;idxq++) {
int l=qs[idxq][0],r=qs[idxq][1];
while(curL > l) {
curL--;
add(in[curL]);
}
while(curR < r) {
curR++;
add(in[curR]);
}
while(curL < l) {
remove(in[curL]);
curL++;
}
while(curR > r) {
remove(in[curR]);
curR--;
}
ans[qs[idxq][2]] = solve(maxOcc, r-l+1);
}
for(int i=0;i<q;i++) {
pw.println(ans[i]);
}
}
public static void main(String[] args) throws Exception{
sc=new MScanner(System.in);
pw = new PrintWriter(System.out);
int tc=1;
// tc=sc.nextInt();
for(int i=1;i<=tc;i++) {
// pw.printf("Case #%d:", i);
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[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt();
return in;
}
public long[] longArr(int n) throws IOException {
long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong();
return in;
}
public int[] intSortedArr(int n) throws IOException {
int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt();
shuffle(in);
Arrays.sort(in);
return in;
}
public long[] longSortedArr(int n) throws IOException {
long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong();
shuffle(in);
Arrays.sort(in);
return in;
}
public Integer[] IntegerArr(int n) throws IOException {
Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt();
return in;
}
public Long[] LongArr(int n) throws IOException {
Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=nextLong();
return in;
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
static void sort(int[]in) {
shuffle(in);
Arrays.sort(in);
}
static void sort(long[]in) {
shuffle(in);
Arrays.sort(in);
}
static void shuffle(int[]in) {
for(int i=0;i<in.length;i++) {
int idx=(int)(Math.random()*in.length);
int tmp=in[i];
in[i]=in[idx];
in[idx]=tmp;
}
}
static void shuffle(long[]in) {
for(int i=0;i<in.length;i++) {
int idx=(int)(Math.random()*in.length);
long tmp=in[i];
in[i]=in[idx];
in[idx]=tmp;
}
}
} | Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 8 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | 19342ae4ab772ef35d04f07406a75e92 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | import java.io.*;
import java.util.*;
public class Main{
static int log=19;
static ArrayList<Integer>[]occ;
static int[]in;
static int[][]dom;
static int[][]cnt;
static int numOcc(int l,int r,int x) {
if(l>r)return 0;
if(l==r) {
return in[l]==x?1:0;
}
int lo=0,hi=occ[x].size()-1;
int first=-1,last=-1;
while(lo<=hi) {
int mid=(lo+hi)>>1;
int idx=occ[x].get(mid);
if(idx>=l) {
first=mid;
hi=mid-1;
}
else {
lo=mid+1;
}
}
if(first==-1 || first>r)return 0;
lo=0;hi=occ[x].size()-1;
while(lo<=hi) {
int mid=(lo+hi)>>1;
int idx=occ[x].get(mid);
if(idx<=r) {
last=mid;
lo=mid+1;
}
else {
hi=mid-1;
}
}
return last-first+1;
}
static int[] query(int l,int r,int i,int len) {
if(l>r)return new int[] {-1,0};
if(l+len-1>r) {
return query(l, r, i-1, len>>1);
}
int u=dom[l][i];
if(u!=-1) {
int occ=cnt[l][i]+numOcc(l+len, r, u);
if(occ>(r-l+1+1)/2) {
return new int[] {u,occ};
}
}
int[]right=query(l+len, r, i-1, len>>1);
int v=right[0];
if(v!=-1) {
int occ=right[1]+numOcc(l, l+len-1, v);
if(occ>(r-l+1+1)/2) {
return new int[] {v,occ};
}
}
return new int[] {-1,0};
}
static void main() throws Exception{
int n=sc.nextInt(),q=sc.nextInt();
in=new int[n];
occ=new ArrayList[n];
dom=new int[n][log];
cnt=new int[n][log];
for(int i=0;i<n;i++) {
occ[i]=new ArrayList<Integer>();
}
for(int i=0;i<n;i++) {
in[i]=sc.nextInt()-1;
occ[in[i]].add(i);
}
for(int i=0;i<n;i++) {
dom[i][0]=in[i];
cnt[i][0]=1;
}
for(int i=1,len=2;len<=n;i++,len<<=1) {
for(int j=0;j<n;j++) {
if(j+(len>>1)>=n) {
dom[j][i]=-1;
continue;
}
int u=dom[j][i-1],v=dom[j+(len>>1)][i-1];
dom[j][i]=-1;
if(u!=-1) {
int occ=cnt[j][i-1]+numOcc(j+(len>>1), j+len-1, u);
if(occ>(len>>1)) {
dom[j][i]=u;
cnt[j][i]=occ;
}
}
if(v!=-1 && dom[j][i]==-1) {
int occ=cnt[j+(len>>1)][i-1]+numOcc(j, j+(len>>1)-1, v);
if(occ>(len>>1)) {
dom[j][i]=v;
cnt[j][i]=occ;
}
}
}
}
int len=1<<(log-1);
while(q-->0) {
int l=sc.nextInt()-1,r=sc.nextInt()-1;
int[]res=query(l, r, log-1, len);
if(res[0]==-1) {
pw.println(1);
continue;
}
int occ=res[1];
int curlen=(r-l+1);
int lo=1,hi=occ-1;
int ans=0;
while(lo<=hi) {
int mid=(lo+hi)>>1;
int num=occ-mid,den=curlen-mid;
if(num<=(den+1)/2) {
ans=mid;
hi=mid-1;
}
else {
lo=mid+1;
}
}
pw.println(ans+1);
}
}
public static void main(String[] args) throws Exception{
sc=new MScanner(System.in);
pw = new PrintWriter(System.out);
int tc=1;
// tc=sc.nextInt();
for(int i=1;i<=tc;i++) {
// pw.printf("Case #%d:", i);
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[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt();
return in;
}
public long[] longArr(int n) throws IOException {
long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong();
return in;
}
public int[] intSortedArr(int n) throws IOException {
int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt();
shuffle(in);
Arrays.sort(in);
return in;
}
public long[] longSortedArr(int n) throws IOException {
long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong();
shuffle(in);
Arrays.sort(in);
return in;
}
public Integer[] IntegerArr(int n) throws IOException {
Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt();
return in;
}
public Long[] LongArr(int n) throws IOException {
Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=nextLong();
return in;
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
static void sort(int[]in) {
shuffle(in);
Arrays.sort(in);
}
static void sort(long[]in) {
shuffle(in);
Arrays.sort(in);
}
static void shuffle(int[]in) {
for(int i=0;i<in.length;i++) {
int idx=(int)(Math.random()*in.length);
int tmp=in[i];
in[i]=in[idx];
in[idx]=tmp;
}
}
static void shuffle(long[]in) {
for(int i=0;i<in.length;i++) {
int idx=(int)(Math.random()*in.length);
long tmp=in[i];
in[i]=in[idx];
in[idx]=tmp;
}
}
} | Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 8 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | 761600eb9d6beb071207c831b5d6c7da | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | import java.io.*;
import java.util.*;
public class CutandStick {
private static int block_size;
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken()); int q = Integer.parseInt(st.nextToken());
block_size = (int) Math.sqrt(n);
int a[] = new int[n];
st = new StringTokenizer(br.readLine());
for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(st.nextToken());
Query[] qry = new Query[q];
for(int i = 0; i < q; ++i) {
st = new StringTokenizer(br.readLine());
qry[i] = new Query(Integer.parseInt(st.nextToken())-1,Integer.parseInt(st.nextToken())-1,i);
}
//mo's algorithm (sqrt decomposition)
int[] ans = new int[q];
Arrays.sort(qry);
int cur_l = 0, cur_r = -1;
int[] cnt = new int[n+1];
int[] max = new int[n+1];
max[0] = n;
int cur_max = 0;
for (Query e : qry) {
while (cur_l > e.l) {
--cur_l;
--max[cnt[a[cur_l]]];
++max[++cnt[a[cur_l]]];
if(max[cur_max+1]>0)++cur_max;
}
while (cur_r < e.r) {
++cur_r;
--max[cnt[a[cur_r]]];
++max[++cnt[a[cur_r]]];
if(max[cur_max+1]>0)++cur_max;
}
while (cur_l < e.l) {
--max[cnt[a[cur_l]]];
++max[--cnt[a[cur_l]]];
++cur_l;
if(max[cur_max]==0)--cur_max;
}
while (cur_r > e.r) {
--max[cnt[a[cur_r]]];
++max[--cnt[a[cur_r]]];
--cur_r;
if(max[cur_max]==0)--cur_max;
}
int opp = e.r-e.l+1-cur_max;
if(cur_max>opp)ans[e.idx]=cur_max-opp;
else ans[e.idx]=1;
}
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
for(int i = 0; i < q; ++i)pw.println(ans[i]);
pw.close();
}
private static class Query implements Comparable<Query>{
int l, r, idx;
public Query(int l, int r, int idx){
this.l = l;
this.r = r;
this.idx = idx;
}
@Override
public int compareTo(Query o) {
if(l/block_size==o.l/block_size) {
if(r==o.r)return idx-o.idx;
return r-o.r;
}
return l/block_size-o.l/block_size;
}
}
}
| Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 8 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | 10a55a91f5d94d8f14a6e24a1c4a5eba | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | import java.io.*;
import java.util.*;
public class Main {
static long MOD = 1000000007;
static int[] readArray(int size, InputReader in, boolean subOne) {
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = in.nextInt() + (subOne ? -1 : 0);
}
return a;
}
static long[] readLongArray(int size, InputReader in) {
long[] a = new long[size];
for (int i = 0; i < size; i++) {
a[i] = in.nextLong();
}
return a;
}
static void sortArray(int[] a) {
Random random = new Random();
for (int i = 0; i < a.length; i++) {
int randomPos = random.nextInt(a.length);
int t = a[i];
a[i] = a[randomPos];
a[randomPos] = t;
}
Arrays.sort(a);
}
static class SegTree {
private final int[] a;
private int size;
private final int[] tree;
List<Integer>[] occs;
SegTree(int[] a) {
this.a = a;
size = 1;
while (size < a.length) {
size *= 2;
}
occs = new List[a.length + 1];
for (int i = 0; i <= a.length; i++) {
occs[i] = new ArrayList<>();
}
for (int i = 0; i < a.length; i++) {
occs[a[i]].add(i);
}
tree = new int[2 * size - 1];
build(a, 0, 0, size);
}
private void build(int[] a, int x, int lx, int rx) {
if (rx - lx == 1) {
if (lx < a.length) {
tree[x] = a[lx];
}
} else {
int m = (rx + lx) / 2;
build(a, 2 * x + 1, lx, m);
build(a, 2 * x + 2, m, rx);
int occs1 = getOccs(lx, rx, tree[2 * x + 1]);
int occs2 = getOccs(lx, rx, tree[2 * x + 2]);
if (occs1 >= occs2) {
tree[x] = tree[2 * x + 1];
} else {
tree[x] = tree[2 * x + 2];
}
}
}
public Set<Integer> getPossibleAnswers(int l, int r) {
Set<Integer> res = new HashSet<>();
getPossibleAnswers(l, r, 0, 0, size, res);
return res;
}
private void getPossibleAnswers(int l, int r, int x, int lx, int rx, Collection<Integer> res) {
if (l >= rx || lx >= r) {
return;
}
if (lx >= l && rx <= r) {
res.add(tree[x]);
return;
}
int m = (lx + rx) / 2;
getPossibleAnswers(l, r, 2 * x + 1, lx, m, res);
getPossibleAnswers(l, r, 2 * x + 2, m, rx, res);
}
public int getOccs(int l, int r, int val) {
return binSearchRight(occs[val], r - 1) - binSearchLeft(occs[val], l) + 1;
}
}
public static void main(String[] args) throws FileNotFoundException {
// long startTime = System.currentTimeMillis();
// PrintWriter out = new PrintWriter(new BufferedOutputStream(new FileOutputStream("cowrect.out")));
InputReader in = new InputReader(System.in);
// InputReader in = new InputReader(new FileInputStream("cowrect.in"));
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
int n = in.nextInt();
int q = in.nextInt();
int[] a = readArray(n, in, false);
List<Integer>[] occs = new ArrayList[n + 1];
for (int i = 0; i <= n; i++) {
occs[i] = new ArrayList<>();
}
for (int i = 0; i < n; i++) {
occs[a[i]].add(i);
}
SegTree segmentTree = new SegTree(a);
outer:
for (int i = 0; i < q; i++) {
// out.flush();
int l = in.nextInt() - 1;
int r = in.nextInt();
Set<Integer> possibleAnswers = segmentTree.getPossibleAnswers(l, r);
for (int possibleAnswer : possibleAnswers) {
int x = binSearchRight(occs[possibleAnswer], r - 1) - binSearchLeft(occs[possibleAnswer], l) + 1;
if (2 * x - (r - l) >= 1) {
out.println(2 * x - (r - l));
continue outer;
}
}
out.println(1);
}
out.close();
}
static int binSearchLeft(List<Integer> list, int key) {
int l = -1;
int r = list.size();
while (l < r - 1) {
int m = (l + r) / 2;
if (list.get(m) < key) {
l = m;
} else {
r = m;
}
}
return r;
}
static int binSearchRight(List<Integer> list, int key) {
int l = -1;
int r = list.size();
while (l < r - 1) {
int m = (l + r) / 2;
if (list.get(m) <= key) {
l = m;
} else {
r = m;
}
}
return l;
}
private static void outputArray(long[] ans, PrintWriter out, boolean addOne) {
StringBuilder str = new StringBuilder();
for (int j = 1; j < ans.length; j++) {
long i = ans[j];
long an = i + (addOne ? 1 : 0);
str.append(an);
if (j < ans.length - 1) {
str.append(' ');
}
}
out.println(str);
// out.flush();
}
private 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 String nextString() {
try {
return reader.readLine();
} catch (IOException 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());
}
public char nextChar() {
return next().charAt(0);
}
public String nextWord() {
return next();
}
private List<Integer>[] readTree(int n) {
return readGraph(n, n - 1);
}
private List<Integer>[] readGraph(int n, int m) {
List<Integer>[] result = new List[n];
for (int i = 0; i < n; i++) {
result[i] = new ArrayList<>();
}
for (int i = 0; i < m; i++) {
int u = nextInt() - 1;
int v = nextInt() - 1;
result[u].add(v);
result[v].add(u);
}
return result;
}
private Map<Integer, Long>[] readWeightedGraph(int n, int m) {
Map<Integer, Long>[] result = new HashMap[n];
for (int i = 0; i < n; i++) {
result[i] = new HashMap<>();
}
for (int i = 0; i < m; i++) {
int u = nextInt() - 1;
int v = nextInt() - 1;
long w = nextLong();
result[u].put(v, Math.min(w, result[u].getOrDefault(v, Long.MAX_VALUE)));
result[v].put(u, Math.min(w, result[v].getOrDefault(u, Long.MAX_VALUE)));
}
return result;
}
}
} | Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 8 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | c21a6bae629cc2f496a8e2ff37bb71d8 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | /*
*
* CREATED BY : NAITIK V
*
*
*/
import java.util.*;
import java.io.*;
public class A
{
static FastReader sc=new FastReader();
static long dp[][];
static int mod=1000000007;
static int max=555;
static int large;
static int block_size=555;
static int F[]=new int[300001];
//static HashMap<Integer,Integer> map=new HashMap<Integer, Integer>();
static int map[]=new int[300001];
public static void main(String[] args)
{
PrintWriter out=new PrintWriter(System.out);
StringBuffer sb=new StringBuffer("");
int ttt=1;
// ttt =i();
outer :while (ttt-- > 0)
{
int n=i();
int q=i();
int A[]=input(n);
Tri P[]=new Tri[q];
for(int i=0;i<q;i++) {
int a=i()-1;
int b=i()-1;
P[i]=new Tri(a, b, i);
}
Arrays.sort(P);
int R[]=new int[q];
int l=0,u=-1;
for(int i=0;i<q;i++) {
int a=P[i].x;
int b=P[i].y;
int idx=P[i].z;
while(u<b) {
u++;
add(A,u);
}
while(l>a) {
l--;
add(A,l);
}
while(u>b) {
remove(A,u);
u--;
}
while(l<a) {
remove(A,l);
l++;
}
int len=b-a+1;
len=(len+1)/2;
if(large<=len) {
R[idx]=1;
continue;
}
len=b-a+1;
// int left=len-large;
// int y=left*2+1;
// len-=y;
// len++;
R[idx]=2*large-len;
}
for(int i=0;i<q;i++) {
out.println(R[i]);
}
}
out.close();
// System.out.println(sb.toString());
//CHECK FOR N=1 //CHECK FOR M=0
//CHECK FOR N=1 //CHECK FOR M=0
//CHECK FOR N=1
//CHECK FOR N=1
//CHECK FOR N=1
}
private static void remove(int A[],int u) {
int pv=F[A[u]];
F[A[u]]--;
if(pv==large) {
if(map[pv]==1) {
map[pv]=0;
large--;
}
else {
map[pv]--;
}
}
else
map[pv]--;
pv--;
map[pv]++;
}
private static void add(int A[],int u) {
int pv=F[A[u]];
// if(map.containsKey(pv)) {
// map.put(pv, map.get(pv)-1);
// if(map.get(pv)==0)
// map.remove(pv);
// }
if(map[pv]>0)
map[pv]--;
F[A[u]]++;
pv++;
map[pv]++;
large=Math.max(large, F[A[u]]);
}
static class Tri implements Comparable<Tri>
{
int x;
int y;
int z;
Tri(int x,int y,int z){
this.x=x;
this.y=y;
this.z=z;
}
@Override
public int compareTo(Tri o) {
// int a=this.x/max;
// int b=o.x/max;
// if(a<b)
// return 1;
// else if(a>b)
// return -1;
// else {
// if(this.y<o.y)
// return 1;
// else
// return -1;
// }
if(this.x/block_size==o.x/block_size) {
if(this.y==o.y)return this.z-o.z;
return y-o.y;
}
return x/block_size-o.x/block_size;
}
}
static class Pair implements Comparable<Pair>
{
int x;
int y;
Pair(int x,int y){
this.x=x;
this.y=y;
}
@Override
// public int compareTo(Pair o) {
// if(this.x>o.x)
// return 1;
// else if(this.x<o.x)
// return -1;
// else {
// if(this.y<o.y)
// return 1;
// else if(this.y>o.y)
// return -1;
// else
// return 0;
// }
// }
public int compareTo(Pair o) {
if (x > o.x) {
return 1;
}
if (x < o.x) {
return -1;
}
if (y > o.y) {
return 1;
}
if (y < o.y) {
return -1;
}
return 0;
}
}
static int[] input(int n) {
int A[]=new int[n];
for(int i=0;i<n;i++) {
A[i]=sc.nextInt();
}
return A;
}
static long[] inputL(int n) {
long A[]=new long[n];
for(int i=0;i<n;i++) {
A[i]=sc.nextLong();
}
return A;
}
static String[] inputS(int n) {
String A[]=new String[n];
for(int i=0;i<n;i++) {
A[i]=sc.next();
}
return A;
}
static long sum(int A[]) {
long sum=0;
for(int i : A) {
sum+=i;
}
return sum;
}
static long sum(long A[]) {
long sum=0;
for(long i : A) {
sum+=i;
}
return sum;
}
static void input(int A[],int B[]) {
for(int i=0;i<A.length;i++) {
A[i]=sc.nextInt();
B[i]=sc.nextInt();
}
}
static int[][] input(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]=i();
}
}
return A;
}
static char[][] charinput(int n,int m){
char A[][]=new char[n][m];
for(int i=0;i<n;i++) {
String s=s();
for(int j=0;j<m;j++) {
A[i][j]=s.charAt(j);
}
}
return A;
}
static int max(int A[]) {
int max=Integer.MIN_VALUE;
for(int i=0;i<A.length;i++) {
max=Math.max(max, A[i]);
}
return max;
}
static int min(int A[]) {
int min=Integer.MAX_VALUE;
for(int i=0;i<A.length;i++) {
min=Math.min(min, A[i]);
}
return min;
}
static long max(long A[]) {
long max=Long.MIN_VALUE;
for(int i=0;i<A.length;i++) {
max=Math.max(max, A[i]);
}
return max;
}
static long min(long A[]) {
long min=Long.MAX_VALUE;
for(int i=0;i<A.length;i++) {
min=Math.min(min, A[i]);
}
return min;
}
static long mod(long x) {
int mod=1000000007;
return ((x%mod + mod)%mod);
}
static String reverse(String s) {
StringBuffer p=new StringBuffer(s);
p.reverse();
return p.toString();
}
static int i() {
return sc.nextInt();
}
static String s() {
return sc.next();
}
static long l() {
return sc.nextLong();
}
static void sort(int[] A){
int n = A.length;
Random rnd = new Random();
for(int i=0; i<n; ++i){
int tmp = A[i];
int randomPos = i + rnd.nextInt(n-i);
A[i] = A[randomPos];
A[randomPos] = tmp;
}
Arrays.sort(A);
}
static void sort(long[] A){
int n = A.length;
Random rnd = new Random();
for(int i=0; i<n; ++i){
long tmp = A[i];
int randomPos = i + rnd.nextInt(n-i);
A[i] = A[randomPos];
A[randomPos] = tmp;
}
Arrays.sort(A);
}
static String sort(String s) {
Character ch[]=new Character[s.length()];
for(int i=0;i<s.length();i++) {
ch[i]=s.charAt(i);
}
Arrays.sort(ch);
StringBuffer st=new StringBuffer("");
for(int i=0;i<s.length();i++) {
st.append(ch[i]);
}
return st.toString();
}
static HashMap<Integer,Integer> hash(int A[]){
HashMap<Integer,Integer> map=new HashMap<Integer, Integer>();
for(int i : A) {
if(map.containsKey(i)) {
map.put(i, map.get(i)+1);
}
else {
map.put(i, 1);
}
}
return map;
}
static HashMap<Long,Integer> hash(long A[]){
HashMap<Long,Integer> map=new HashMap<Long, Integer>();
for(long i : A) {
if(map.containsKey(i)) {
map.put(i, map.get(i)+1);
}
else {
map.put(i, 1);
}
}
return map;
}
static TreeMap<Integer,Integer> tree(int A[]){
TreeMap<Integer,Integer> map=new TreeMap<Integer, Integer>();
for(int i : A) {
if(map.containsKey(i)) {
map.put(i, map.get(i)+1);
}
else {
map.put(i, 1);
}
}
return map;
}
static TreeMap<Long,Integer> tree(long A[]){
TreeMap<Long,Integer> map=new TreeMap<Long, Integer>();
for(long i : A) {
if(map.containsKey(i)) {
map.put(i, map.get(i)+1);
}
else {
map.put(i, 1);
}
}
return map;
}
static void primefact(int n) {
for(int i=2;i*i<=n;i++) {
if(n%i==0) {
int cnt=0;
while(n%i==0) {
cnt++;
n/=i;
}
System.out.println(i+"^"+cnt);
}
}
if(n>1) {
System.out.println(n+"^ 1");
}
}
static boolean prime(int n)
{
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
double sq=Math.sqrt(n);
for (int i = 5; i <= sq; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static boolean prime(long n)
{
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
double sq=Math.sqrt(n);
for (int i = 5; i <= sq; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static long power(long x, long y, long p)
{
long res = 1;
x = x % p;
while (y > 0) {
if (y % 2 == 1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
static long modInverse(long n, long p)
{
return power(n, p - 2, p);
}
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
}
| Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 8 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | 14d94d267ac8206e5d6a94e91812d1ad | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | import java.util.*;
import java.io.*;
public class D3 {
public static void main(String[] args) {
FastScanner sc = new FastScanner();
int n = sc.nextInt();
int q = sc.nextInt();
int[] arr = new int[n];
for(int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
WaveletTree wt = new WaveletTree(arr, 1, n);
StringBuilder sb = new StringBuilder();
for(int qi = 0; qi < q; qi++) {
int L = sc.nextInt();
int R = sc.nextInt();
int d = R - L + 1;
int med = wt.kth(L, R, d/2+1);
int c = wt.count(L, R, med);
int res = Math.max(c - (d - c), 1);
sb.append(res+"\n");
}
PrintWriter pw = new PrintWriter(System.out);
pw.println(sb.toString().trim());
pw.flush();
}
static class WaveletTree{
int lo, hi;
WaveletTree wtl, wtr;
int[] b;
//nums are in range [x,y]
public WaveletTree(int[] arr, int x, int y){
lo = x; hi = y;
if(lo == hi || arr.length == 0) return;
int mid = (lo+hi)/2;
b = new int[arr.length + 1];
int ib = 0;
int curr = 0;
b[ib++] = curr;
int k = 0;
for(int v: arr) {
if(v <= mid) {
k++; curr++;
}
b[ib++] = curr;
}
int[] arrlo = new int[k];
int[] arrhi = new int[arr.length - k];
int ilo = 0, ihi = 0;
for(int v: arr) {
if(v <= mid) arrlo[ilo++] = v;
else arrhi[ihi++] = v;
}
wtl = new WaveletTree(arrlo, lo, mid);
wtr = new WaveletTree(arrhi, mid+1, hi);
}
//kth smallest element in [l, r]
int kth(int l, int r, int k){
if(l > r) return 0;
if(lo == hi) return lo;
int inLeft = b[r] - b[l-1];
int lb = b[l-1]; //amt of nos in first (l-1) nos that go in left
int rb = b[r]; //amt of nos in first (r) nos that go in left
if(k <= inLeft) return wtl.kth(lb+1, rb , k);
return wtr.kth(l-lb, r-rb, k-inLeft);
}
//count of nos in [l, r] Less than or equal to k
int LTE(int l, int r, int k) {
if(l > r || k < lo) return 0;
if(hi <= k) return r - l + 1;
int lb = b[l-1], rb = b[r];
return wtl.LTE(lb+1, rb, k) + wtr.LTE(l-lb, r-rb, k);
}
//count of nos in [l, r] equal to k
int count(int l, int r, int k) {
if(l > r || k < lo || k > hi) return 0;
if(lo == hi) return r - l + 1;
int lb = b[l-1], rb = b[r], mid = (lo+hi)/2;
if(k <= mid) return wtl.count(lb+1, rb, k);
return wtr.count(l-lb, r-rb, k);
}
}
static class FastScanner {
public BufferedReader reader;
public StringTokenizer tokenizer;
public FastScanner() {
reader = new BufferedReader(new InputStreamReader(System.in), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
try {
return reader.readLine();
} catch(IOException e) {
throw new RuntimeException(e);
}
}
}
}
| Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 8 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | 3517f53422b920795ea26445412025ea | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | import java.util.*;
import java.io.*;
public class D2 { //this is all wrong
public static void main(String[] args) {
FastScanner sc = new FastScanner();
int n = sc.nextInt();
int q = sc.nextInt();
ArrayList<Integer> arr = new ArrayList<>();
for(int i = 0; i < n; i++) {
int a = sc.nextInt();
arr.add(a);
}
WaveletTree wt = new WaveletTree(arr, 1, n);
StringBuilder sb = new StringBuilder();
for(int qi = 0; qi < q; qi++) {
int L = sc.nextInt();
int R = sc.nextInt();
int d = R - L + 1;
int med = wt.kth(L, R, d/2+1);
int c = wt.count(L, R, med);
int res = Math.max(c - (d - c), 1);
sb.append(res+"\n");
}
PrintWriter pw = new PrintWriter(System.out);
pw.println(sb.toString().trim());
pw.flush();
}
static class WaveletTree{
int lo, hi;
WaveletTree wtl, wtr;
ArrayList<Integer> b;
//nums are in range [x,y]
//array indices are [from, to)
public WaveletTree(ArrayList<Integer> arr, int x, int y){
lo = x; hi = y;
if(lo == hi || arr.isEmpty()) return;
int mid = (lo+hi)/2;
b = new ArrayList<>();
int curr = 0;
b.add(curr);
for(int v: arr) {
if(v <= mid) curr++;
b.add(curr);
}
ArrayList<Integer> arrlo = new ArrayList<>();
ArrayList<Integer> arrhi = new ArrayList<>();
for(int v: arr) {
if(v <= mid) arrlo.add(v);
else arrhi.add(v);
}
wtl = new WaveletTree(arrlo, lo, mid);
wtr = new WaveletTree(arrhi, mid+1, hi);
}
//kth smallest element in [l, r]
int kth(int l, int r, int k){
if(l > r) return 0;
if(lo == hi) return lo;
int inLeft = b.get(r) - b.get(l-1);
int lb = b.get(l-1); //amt of nos in first (l-1) nos that go in left
int rb = b.get(r); //amt of nos in first (r) nos that go in left
if(k <= inLeft) return wtl.kth(lb+1, rb , k);
return wtr.kth(l-lb, r-rb, k-inLeft);
}
//count of nos in [l, r] Less than or equal to k
int LTE(int l, int r, int k) {
if(l > r || k < lo) return 0;
if(hi <= k) return r - l + 1;
int lb = b.get(l-1), rb = b.get(r);
return wtl.LTE(lb+1, rb, k) + wtr.LTE(l-lb, r-rb, k);
}
//count of nos in [l, r] equal to k
int count(int l, int r, int k) {
if(l > r || k < lo || k > hi) return 0;
if(lo == hi) return r - l + 1;
int lb = b.get(l-1), rb = b.get(r), mid = (lo+hi)/2;
if(k <= mid) return wtl.count(lb+1, rb, k);
return wtr.count(l-lb, r-rb, k);
}
}
static class FastScanner {
public BufferedReader reader;
public StringTokenizer tokenizer;
public FastScanner() {
reader = new BufferedReader(new InputStreamReader(System.in), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
try {
return reader.readLine();
} catch(IOException e) {
throw new RuntimeException(e);
}
}
}
}
| Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 8 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | 16f9f50a46410afe13a932ee4325bbe7 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
import java.awt.Point;
public class Main {
static final long MOD = 1000000007L;
//static final long MOD2 = 1000000009L;
//static final long MOD = 998244353L;
//static final long INF = 500000000000L;
static final int INF = 1000000005;
static final int NINF = -1000000005;
//static final long NINF = -1000000000000000000L;
static FastScanner sc;
static PrintWriter pw;
static final int[][] dirs = {{-1,0},{1,0},{0,-1},{0,1}};
static final int MO = 1200;
public static void main(String[] args) {
sc = new FastScanner();
pw = new PrintWriter(System.out);
int N = sc.ni();
int Q = sc.ni();
Random r = new Random();
int[] A = sc.intArray(N, -1);
int[][] queries = new int[Q][3];
for (int i = 0; i < Q; i++) {
queries[i] = new int[]{sc.ni()-1,sc.ni()-1,i};
}
sort(queries); //mo's algorithm
int[] cnt = new int[N];
int L = 0;
int R = -1;
int[] ans = new int[Q];
for (int[] query: queries) {
if (R < query[1]) {
while (R < query[1]) {
R++;
cnt[A[R]] += 1;
}
} else {
while (R > query[1]) {
cnt[A[R]] -= 1;
R--;
}
}
if (L < query[0]) {
while (L < query[0]) {
cnt[A[L]] -= 1;
L++;
}
} else {
while (L > query[0]) {
L--;
cnt[A[L]] += 1;
}
}
//random code
int sz = R-L+1;
int other = sz;
for (int a = 0; a < 25; a++) {
int i = r.nextInt(sz)+L;
if (cnt[A[i]] > (sz+1)/2) {
other = sz-cnt[A[i]];
break;
}
}
ans[query[2]] = Math.max(1,(R-L+1)-2*other);
}
for (int a: ans) {
pw.println(a);
}
pw.close();
}
public static void sort(int[] arr) {
Random rgen = new Random();
for (int i = 0; i < arr.length; i++) {
int r = rgen.nextInt(arr.length);
int temp = arr[i];
arr[i] = arr[r];
arr[r] = temp;
}
Arrays.sort(arr);
}
public static void sort(long[] arr) {
Random rgen = new Random();
for (int i = 0; i < arr.length; i++) {
int r = rgen.nextInt(arr.length);
long temp = arr[i];
arr[i] = arr[r];
arr[r] = temp;
}
Arrays.sort(arr);
}
//Sort an array (immune to quicksort TLE)
public static void sort(int[][] arr) {
Random rgen = new Random();
for (int i = 0; i < arr.length; i++) {
int r = rgen.nextInt(arr.length);
int[] temp = arr[i];
arr[i] = arr[r];
arr[r] = temp;
}
Arrays.sort(arr, new Comparator<int[]>() {
@Override
public int compare(int[] a, int[] b) {
int ablock = a[0]/MO;
int bblock = b[0]/MO;
if (ablock != bblock)
return ablock-bblock;
else
return a[1]-b[1];
}
});
}
public static void sort(long[][] arr) {
Random rgen = new Random();
for (int i = 0; i < arr.length; i++) {
int r = rgen.nextInt(arr.length);
long[] temp = arr[i];
arr[i] = arr[r];
arr[r] = temp;
}
Arrays.sort(arr, new Comparator<long[]>() {
@Override
public int compare(long[] a, long[] b) {
if (a[0] > b[0])
return 1;
else if (a[0] < b[0])
return -1;
else
return 0;
//Ascending order.
}
});
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in), 32768);
st = null;
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int ni() {
return Integer.parseInt(next());
}
int[][] graph(int N, int[][] edges) {
int[][] graph = new int[N][];
int[] sz = new int[N];
for (int[] e: edges) {
sz[e[0]] += 1;
sz[e[1]] += 1;
}
for (int i = 0; i < N; i++) {
graph[i] = new int[sz[i]];
}
int[] cur = new int[N];
for (int[] e: edges) {
graph[e[0]][cur[e[0]]] = e[1];
graph[e[1]][cur[e[1]]] = e[0];
cur[e[0]] += 1;
cur[e[1]] += 1;
}
return graph;
}
int[] intArray(int N, int mod) {
int[] ret = new int[N];
for (int i = 0; i < N; i++)
ret[i] = ni()+mod;
return ret;
}
long nl() {
return Long.parseLong(next());
}
long[] longArray(int N, long mod) {
long[] ret = new long[N];
for (int i = 0; i < N; i++)
ret[i] = nl()+mod;
return ret;
}
double nd() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 8 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | 48966728a782fd734890395ec66a41eb | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
import java.awt.Point;
public class Main {
static final long MOD = 1000000007L;
//static final long MOD2 = 1000000009L;
//static final long MOD = 998244353L;
//static final long INF = 500000000000L;
static final int INF = 1000000005;
static final int NINF = -1000000005;
//static final long NINF = -1000000000000000000L;
static FastScanner sc;
static PrintWriter pw;
static final int[][] dirs = {{-1,0},{1,0},{0,-1},{0,1}};
static final int MO = 200;
public static void main(String[] args) {
sc = new FastScanner();
pw = new PrintWriter(System.out);
int N = sc.ni();
int Q = sc.ni();
Random r = new Random();
int[] A = sc.intArray(N, -1);
int[][] queries = new int[Q][3];
for (int i = 0; i < Q; i++) {
queries[i] = new int[]{sc.ni()-1,sc.ni()-1,i};
}
sort(queries); //mo's algorithm
int[] cnt = new int[N];
int L = 0;
int R = -1;
int[] ans = new int[Q];
for (int[] query: queries) {
if (R < query[1]) {
while (R < query[1]) {
R++;
cnt[A[R]] += 1;
}
} else {
while (R > query[1]) {
cnt[A[R]] -= 1;
R--;
}
}
if (L < query[0]) {
while (L < query[0]) {
cnt[A[L]] -= 1;
L++;
}
} else {
while (L > query[0]) {
L--;
cnt[A[L]] += 1;
}
}
//random code
int sz = R-L+1;
int other = sz;
for (int a = 0; a < 25; a++) {
int i = r.nextInt(sz)+L;
if (cnt[A[i]] > (sz+1)/2) {
other = sz-cnt[A[i]];
break;
}
}
ans[query[2]] = Math.max(1,(R-L+1)-2*other);
}
for (int a: ans) {
pw.println(a);
}
pw.close();
}
public static void sort(int[] arr) {
Random rgen = new Random();
for (int i = 0; i < arr.length; i++) {
int r = rgen.nextInt(arr.length);
int temp = arr[i];
arr[i] = arr[r];
arr[r] = temp;
}
Arrays.sort(arr);
}
public static void sort(long[] arr) {
Random rgen = new Random();
for (int i = 0; i < arr.length; i++) {
int r = rgen.nextInt(arr.length);
long temp = arr[i];
arr[i] = arr[r];
arr[r] = temp;
}
Arrays.sort(arr);
}
//Sort an array (immune to quicksort TLE)
public static void sort(int[][] arr) {
Random rgen = new Random();
for (int i = 0; i < arr.length; i++) {
int r = rgen.nextInt(arr.length);
int[] temp = arr[i];
arr[i] = arr[r];
arr[r] = temp;
}
Arrays.sort(arr, new Comparator<int[]>() {
@Override
public int compare(int[] a, int[] b) {
int ablock = a[0]/MO;
int bblock = b[0]/MO;
if (ablock != bblock)
return ablock-bblock;
else
return a[1]-b[1];
}
});
}
public static void sort(long[][] arr) {
Random rgen = new Random();
for (int i = 0; i < arr.length; i++) {
int r = rgen.nextInt(arr.length);
long[] temp = arr[i];
arr[i] = arr[r];
arr[r] = temp;
}
Arrays.sort(arr, new Comparator<long[]>() {
@Override
public int compare(long[] a, long[] b) {
if (a[0] > b[0])
return 1;
else if (a[0] < b[0])
return -1;
else
return 0;
//Ascending order.
}
});
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in), 32768);
st = null;
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int ni() {
return Integer.parseInt(next());
}
int[][] graph(int N, int[][] edges) {
int[][] graph = new int[N][];
int[] sz = new int[N];
for (int[] e: edges) {
sz[e[0]] += 1;
sz[e[1]] += 1;
}
for (int i = 0; i < N; i++) {
graph[i] = new int[sz[i]];
}
int[] cur = new int[N];
for (int[] e: edges) {
graph[e[0]][cur[e[0]]] = e[1];
graph[e[1]][cur[e[1]]] = e[0];
cur[e[0]] += 1;
cur[e[1]] += 1;
}
return graph;
}
int[] intArray(int N, int mod) {
int[] ret = new int[N];
for (int i = 0; i < N; i++)
ret[i] = ni()+mod;
return ret;
}
long nl() {
return Long.parseLong(next());
}
long[] longArray(int N, long mod) {
long[] ret = new long[N];
for (int i = 0; i < N; i++)
ret[i] = nl()+mod;
return ret;
}
double nd() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 8 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | b846c658d45961aeab955bed7c939408 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
import java.awt.Point;
public class Main {
static final long MOD = 1000000007L;
//static final long MOD2 = 1000000009L;
//static final long MOD = 998244353L;
//static final long INF = 500000000000L;
static final int INF = 1000000005;
static final int NINF = -1000000005;
//static final long NINF = -1000000000000000000L;
static FastScanner sc;
static PrintWriter pw;
static final int[][] dirs = {{-1,0},{1,0},{0,-1},{0,1}};
static final int MO = 550;
public static void main(String[] args) {
sc = new FastScanner();
pw = new PrintWriter(System.out);
int N = sc.ni();
int Q = sc.ni();
Random r = new Random();
int[] A = sc.intArray(N, -1);
int[][] queries = new int[Q][3];
for (int i = 0; i < Q; i++) {
queries[i] = new int[]{sc.ni()-1,sc.ni()-1,i};
}
sort(queries); //mo's algorithm
int[] cnt = new int[N];
int L = 0;
int R = -1;
int[] ans = new int[Q];
for (int[] query: queries) {
if (R < query[1]) {
while (R < query[1]) {
R++;
cnt[A[R]] += 1;
}
} else {
while (R > query[1]) {
cnt[A[R]] -= 1;
R--;
}
}
if (L < query[0]) {
while (L < query[0]) {
cnt[A[L]] -= 1;
L++;
}
} else {
while (L > query[0]) {
L--;
cnt[A[L]] += 1;
}
}
//random code
int sz = R-L+1;
int other = sz;
for (int a = 0; a < 25; a++) {
int i = r.nextInt(sz)+L;
if (cnt[A[i]] > (sz+1)/2) {
other = sz-cnt[A[i]];
break;
}
}
ans[query[2]] = Math.max(1,(R-L+1)-2*other);
}
for (int a: ans) {
pw.println(a);
}
pw.close();
}
public static void sort(int[] arr) {
Random rgen = new Random();
for (int i = 0; i < arr.length; i++) {
int r = rgen.nextInt(arr.length);
int temp = arr[i];
arr[i] = arr[r];
arr[r] = temp;
}
Arrays.sort(arr);
}
public static void sort(long[] arr) {
Random rgen = new Random();
for (int i = 0; i < arr.length; i++) {
int r = rgen.nextInt(arr.length);
long temp = arr[i];
arr[i] = arr[r];
arr[r] = temp;
}
Arrays.sort(arr);
}
//Sort an array (immune to quicksort TLE)
public static void sort(int[][] arr) {
Random rgen = new Random();
for (int i = 0; i < arr.length; i++) {
int r = rgen.nextInt(arr.length);
int[] temp = arr[i];
arr[i] = arr[r];
arr[r] = temp;
}
Arrays.sort(arr, new Comparator<int[]>() {
@Override
public int compare(int[] a, int[] b) {
int ablock = a[0]/MO;
int bblock = b[0]/MO;
if (ablock != bblock)
return ablock-bblock;
else
return a[1]-b[1];
}
});
}
public static void sort(long[][] arr) {
Random rgen = new Random();
for (int i = 0; i < arr.length; i++) {
int r = rgen.nextInt(arr.length);
long[] temp = arr[i];
arr[i] = arr[r];
arr[r] = temp;
}
Arrays.sort(arr, new Comparator<long[]>() {
@Override
public int compare(long[] a, long[] b) {
if (a[0] > b[0])
return 1;
else if (a[0] < b[0])
return -1;
else
return 0;
//Ascending order.
}
});
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in), 32768);
st = null;
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int ni() {
return Integer.parseInt(next());
}
int[][] graph(int N, int[][] edges) {
int[][] graph = new int[N][];
int[] sz = new int[N];
for (int[] e: edges) {
sz[e[0]] += 1;
sz[e[1]] += 1;
}
for (int i = 0; i < N; i++) {
graph[i] = new int[sz[i]];
}
int[] cur = new int[N];
for (int[] e: edges) {
graph[e[0]][cur[e[0]]] = e[1];
graph[e[1]][cur[e[1]]] = e[0];
cur[e[0]] += 1;
cur[e[1]] += 1;
}
return graph;
}
int[] intArray(int N, int mod) {
int[] ret = new int[N];
for (int i = 0; i < N; i++)
ret[i] = ni()+mod;
return ret;
}
long nl() {
return Long.parseLong(next());
}
long[] longArray(int N, long mod) {
long[] ret = new long[N];
for (int i = 0; i < N; i++)
ret[i] = nl()+mod;
return ret;
}
double nd() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 8 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | 1d01a844d5c1d336708edaa4f35fdb62 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | import java.util.*;
import java.io.*;
public class tr0 {
static PrintWriter out;
static StringBuilder sb;
static long mod = (long) 1e9 + 7;
static long inf = (long) 1e16;
static int n, m, k;
static ArrayList<Integer>[] ad;
static int[][] remove, add;
static long[][] memo, memo1[];
static boolean vis[];
static long[] inv, ncr[];
static HashMap<Integer, Integer> hm;
static int[] pre, suf, Smax[], Smin[];
static int idmax, idmin;
static ArrayList<Integer> av;
static HashMap<Integer, Integer> mm;
static boolean[] msks;
static int[] lazy[], lazyCount;
static int[] dist;
static char[][] g;
static int s;
static ArrayList<Integer> gl;
static int[] a, q;
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
out = new PrintWriter(System.out);
int n = sc.nextInt();
int q = sc.nextInt();
int[] a = sc.nextArrInt(n);
s = (int) (Math.sqrt(n) + 1);
Query queries[] = new Query[q];
for (int i = 0; i < q; i++)
queries[i] = new Query(sc.nextInt() - 1, sc.nextInt() - 1, i);
int left = -1, right = -1;
Arrays.sort(queries);
int[] ans = new int[q];
Counter counter = new Counter(n, a);
for (int i = 0; i < q; i++) {
int qleft = queries[i].l;
int qright = queries[i].r;
while (left > qleft)
counter.add(--left);
while (right > qright)
counter.remove(right--);
while (right < qright)
counter.add(++right);
while (left < qleft)
counter.remove(left++);
int len = qright - qleft + 1;
int limit = (len + 1) / 2;
int ele = counter.ans;
int ll = len - ele;
if (counter.ans <= limit)
ans[queries[i].idx] = 1;
else {
ele -= ll;
ele--;
ans[queries[i].idx] = 1 + Math.max(0, ele);
}
}
for (int x : ans)
out.println(x);
out.flush();
}
static class Query implements Comparable<Query> {
int l, r, idx, leftBlock;
public Query(int l, int r, int idx) {
this.l = l;
this.r = r;
this.idx = idx;
this.leftBlock = l / s;
}
@Override
public int compareTo(Query o) {
return leftBlock == o.leftBlock ? r - o.r : leftBlock - o.leftBlock;
}
}
static class Counter {
int n, a[], cnt[], dcnt[];
int ans;
int max;
public Counter(int n, int[] a) {
this.n = n;
this.a = a;
max = 0;
cnt = new int[n + 5];
dcnt = new int[n + 5];
}
void add(int idx) {
int val = a[idx];
dcnt[cnt[val]]--;
cnt[val]++;
dcnt[cnt[val]]++;
max = Math.max(max, cnt[val]);
ans = max;
}
void remove(int idx) {
if (idx == -1)
return;
int val = a[idx];
dcnt[cnt[val]]--;
if (dcnt[cnt[val]] == 0 && max == cnt[val])
max--;
cnt[val]--;
dcnt[cnt[val]]++;
ans = max;
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public Scanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public Long nextLong() throws IOException {
return Long.parseLong(next());
}
public int[] nextArrInt(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public long[] nextArrLong(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public int[] nextArrIntSorted(int n) throws IOException {
int[] a = new int[n];
Integer[] a1 = new Integer[n];
for (int i = 0; i < n; i++)
a1[i] = nextInt();
Arrays.sort(a1);
for (int i = 0; i < n; i++)
a[i] = a1[i].intValue();
return a;
}
public long[] nextArrLongSorted(int n) throws IOException {
long[] a = new long[n];
Long[] a1 = new Long[n];
for (int i = 0; i < n; i++)
a1[i] = nextLong();
Arrays.sort(a1);
for (int i = 0; i < n; i++)
a[i] = a1[i].longValue();
return a;
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
} | Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 8 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | 7bfb08607db6e0a47aee87921df60190 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | import java.io.*;
import java.util.*;
public class Practice1 {
private static int block_size;
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken()); int q = Integer.parseInt(st.nextToken());
block_size = (int) Math.sqrt(n);
int a[] = new int[n];
st = new StringTokenizer(br.readLine());
for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(st.nextToken());
Query[] qry = new Query[q];
for(int i = 0; i < q; ++i) {
st = new StringTokenizer(br.readLine());
qry[i] = new Query(Integer.parseInt(st.nextToken())-1,Integer.parseInt(st.nextToken())-1,i);
}
//mo's algorithm (sqrt decomposition)
int[] ans = new int[q];
Arrays.sort(qry);
int cur_l = 0, cur_r = -1;
int[] cnt = new int[n+1];
int[] max = new int[n+1];
max[0] = n;
int cur_max = 0;
for (Query e : qry) {
while (cur_l > e.l) {
--cur_l;
--max[cnt[a[cur_l]]];
++max[++cnt[a[cur_l]]];
if(max[cur_max+1]>0)++cur_max;
}
while (cur_r < e.r) {
++cur_r;
--max[cnt[a[cur_r]]];
++max[++cnt[a[cur_r]]];
if(max[cur_max+1]>0)++cur_max;
}
while (cur_l < e.l) {
--max[cnt[a[cur_l]]];
++max[--cnt[a[cur_l]]];
++cur_l;
if(max[cur_max]==0)--cur_max;
}
while (cur_r > e.r) {
--max[cnt[a[cur_r]]];
++max[--cnt[a[cur_r]]];
--cur_r;
if(max[cur_max]==0)--cur_max;
}
int opp = e.r-e.l+1-cur_max;
if(cur_max>opp)ans[e.idx]=cur_max-opp;
else ans[e.idx]=1;
}
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
for(int i = 0; i < q; ++i)pw.println(ans[i]);
pw.close();
}
private static class Query implements Comparable<Query>{
int l, r, idx;
public Query(int l, int r, int idx){
this.l = l;
this.r = r;
this.idx = idx;
}
@Override
public int compareTo(Query o) {
if(l/block_size==o.l/block_size) {
if(r==o.r)return idx-o.idx;
return r-o.r;
}
return l/block_size-o.l/block_size;
}
}
} | Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 8 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | 9a679115ee4d3497708a829072788b1c | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | import java.util.*;
import java.io.*;
public class Main {
public static void main(String args[]) {new Main().run();}
FastReader in = new FastReader();
PrintWriter out = new PrintWriter(System.out);
void run(){
work();
out.flush();
}
long mod=1000000007;
long gcd(long a,long b) {
return a==0?b:gcd(b%a,a);
}
final int inf=Integer.MAX_VALUE/2;
int maxn=1000000;
ArrayList<Integer>[] rec;
int[] T;
int[] A;
void work() {
int n=ni(),q=ni();
rec=ng(n,0);
A=nia(n);
T=new int[n<<2];
for(int i=0;i<n;i++){
rec[A[i]].add(i);
}
build(1,0,n-1);
for(;q>0;q--){
int s=ni()-1,e=ni()-1;
long r=query(1,0,n-1,s,e);
int v=(int)(r>>32);
out.println(Math.max(v-(e-s+1-v),1));
}
}
private long query(int node, int l, int r,int s,int e) {
if(s<=l&&r<=e){
return (T[node])|(count(T[node],s,e)<<32L);
}else{
int m=(l+r)/2;
long v1=-1,v2=-1;
if(m>=s)v1=query(node<<1,l,m,s,e);
if(m+1<=e)v2=query(node<<1|1,m+1,r,s,e);
return Math.max(v2,v1);
}
}
private void build(int node, int l, int r) {
if(l==r){
T[node]=A[l];
}else{
int m=(l+r)/2;
build(node<<1,l,m);
build(node<<1|1,m+1,r);
int v1=T[node<<1];
int v2=T[node<<1|1];
T[node]=-1;
if(count(v1,l,r)>count(v2,l,r)){
T[node]=v1;
}else{
T[node]=v2;
}
}
}
long count(int v,int idx1,int idx2){
ArrayList<Integer> list=rec[v];
int size=list.size();
int l=0,r=size;
int i1=0,i2=0;
while(l<r){
int m=(l+r)/2;
if(list.get(m)<idx1){
l=m+1;
}else{
r=m;
}
}
i1=l;
l=0;r=size;
while(l<r){
int m=(l+r)/2;
if(list.get(m)<=idx2){
l=m+1;
}else{
r=m;
}
}
i2=l;
return i2-i1;
}
//input
@SuppressWarnings("unused")
private ArrayList<Integer>[] ng(int n, int m) {
ArrayList<Integer>[] graph=(ArrayList<Integer>[])new ArrayList[n];
for(int i=0;i<n;i++) {
graph[i]=new ArrayList<>();
}
for(int i=1;i<=m;i++) {
int s=in.nextInt()-1,e=in.nextInt()-1;
graph[s].add(e);
graph[e].add(s);
}
return graph;
}
private ArrayList<long[]>[] ngw(int n, int m) {
ArrayList<long[]>[] graph=(ArrayList<long[]>[])new ArrayList[n];
for(int i=0;i<n;i++) {
graph[i]=new ArrayList<>();
}
for(int i=1;i<=m;i++) {
long s=in.nextLong()-1,e=in.nextLong()-1,w=in.nextLong();
graph[(int)s].add(new long[] {e,w});
graph[(int)e].add(new long[] {s,w});
}
return graph;
}
private int ni() {
return in.nextInt();
}
private long nl() {
return in.nextLong();
}
private String ns() {
return in.next();
}
private long[] na(int n) {
long[] A=new long[n];
for(int i=0;i<n;i++) {
A[i]=in.nextLong();
}
return A;
}
private int[] nia(int n) {
int[] A=new int[n];
for(int i=0;i<n;i++) {
A[i]=in.nextInt()-1;
}
return A;
}
}
class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br=new BufferedReader(new InputStreamReader(System.in));
}
public String next()
{
while(st==null || !st.hasMoreElements())//回车,空行情况
{
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt()
{
return Integer.parseInt(next());
}
public long nextLong()
{
return Long.parseLong(next());
}
} | Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 8 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | aa728bcf399bd5a10dde151ce71bc18b | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | import java.io.*;
import java.util.*;
public final class Solution {
static PrintWriter out = new PrintWriter(System.out);
static FastReader in = new FastReader();
static long mod = (long) 1e9 + 7;
static Pair[] moves = new Pair[]{new Pair(-1, 0), new Pair(1, 0), new Pair(0, -1), new Pair(0, 1)};
public static void main(String[] args) {
int n = i();
int q = i();
int[] arr = input(n);
int sq = (int) (Math.sqrt(n) + 1);
int[][] qq = new int[q][4];
int[] ans = new int[q];
for (int i = 0; i < q; i++) {
qq[i][0] = i() - 1;
qq[i][1] = i() - 1;
qq[i][2] = i;
qq[i][3] = qq[i][0] / sq;
}
Arrays.sort(qq, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return o1[3] - o2[3];
}
}.thenComparing(new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return o1[1] - o2[1];
}
}));
int curL = qq[0][0];
int curR = curL - 1;
occ = new int[n + 7];
occofocc = new int[n + 7];
occofocc[0] = n;
for (int i = 0; i < q; i++) {
int l = qq[i][0];
int r = qq[i][1];
int idx = qq[i][2];
while (curL > l) {
curL--;
add(arr[curL]);
}
while (curR < r) {
curR++;
add(arr[curR]);
}
while (curL < l) {
remove(arr[curL]);
curL++;
}
while (curR > r) {
remove(arr[curR]);
curR--;
}
ans[idx] = solve(r - l + 1, maxOcc);
}
for (int i = 0; i < q; i++) {
out.println(ans[i]);
}
out.flush();
}
// Mo's algorithm
private static int[] occ, occofocc;
private static int maxOcc;
private static void add(int x) {
occofocc[occ[x]]--;
occ[x]++;
occofocc[occ[x]]++;
maxOcc = Math.max(maxOcc, occ[x]);
}
private static void remove(int x) {
occofocc[occ[x]]--;
occ[x]--;
occofocc[occ[x]]++;
if (occofocc[maxOcc] == 0) {
maxOcc--;
}
}
private static int solve(int len, int max) {
int a;
if (len % 2 == 0) {
if (max <= len / 2) {
a = 1;
} else {
int d = max - len / 2;
// 47 35 23 11
a = d * 2;
}
} else {
if (max <= (len + 1) / 2) {
a = 1;
} else {
int d = max - (len + 1) / 2;
// 48 36 24 12
a = 1 + d * 2;
}
}
return a;
}
public static boolean isPS(int x) {
if (x == 1) {
return true;
}
for (int i = 2; i <= x / 2; i++) {
if (i * i == x) {
return true;
}
}
return false;
}
public static long calc(int type, long X, long K) {
if (type == 1) {
return (X + 99999) / 100000 + K;
} else {
return (K * X + 99999) / 100000;
}
}
static int sd(long i) {
int d = 0;
while (i > 0) {
d += i % 10;
i = i / 10;
}
return d;
}
static int lower(long A[], long x) {
int l = -1, r = A.length;
while (r - l > 1) {
int m = (l + r) / 2;
if (A[m] >= x) {
r = m;
} else {
l = m;
}
}
return r;
}
static int upper(long A[], long x) {
int l = -1, r = A.length;
while (r - l > 1) {
int m = (l + r) / 2;
if (A[m] <= x) {
l = m;
} else {
r = m;
}
}
return l;
}
static void swap(int A[], int a, int b) {
int t = A[a];
A[a] = A[b];
A[b] = t;
}
static int lowerBound(int A[], int low, int high, int x) {
if (low > high) {
if (x >= A[high]) {
return A[high];
}
}
int mid = (low + high) / 2;
if (A[mid] == x) {
return A[mid];
}
if (mid > 0 && A[mid - 1] <= x && x < A[mid]) {
return A[mid - 1];
}
if (x < A[mid]) {
return lowerBound(A, low, mid - 1, x);
}
return lowerBound(A, mid + 1, high, x);
}
static long pow(long a, long b) {
long pow = 1;
long x = a;
while (b != 0) {
if ((b & 1) != 0) {
pow = (pow * x) % mod;
}
x = (x * x) % mod;
b /= 2;
}
return pow;
}
static boolean isPrime(long N) {
if (N <= 1) {
return false;
}
if (N <= 3) {
return true;
}
if (N % 2 == 0 || N % 3 == 0) {
return false;
}
for (int i = 5; i * i <= N; i = i + 6) {
if (N % i == 0 || N % (i + 2) == 0) {
return false;
}
}
return true;
}
static void print(char A[]) {
for (char c : A) {
out.print(c);
}
out.println();
}
static void print(boolean A[]) {
for (boolean c : A) {
out.print(c + " ");
}
out.println();
}
static void print(int A[]) {
for (int c : A) {
out.print(c + " ");
}
out.println();
}
static void print(long A[]) {
for (long i : A) {
out.print(i + " ");
}
out.println();
}
static void print(List<Integer> A) {
for (int a : A) {
out.print(a + " ");
}
}
static int i() {
return in.nextInt();
}
static long l() {
return in.nextLong();
}
static String s() {
return in.nextLine();
}
static int[] input(int N) {
int A[] = new int[N];
for (int i = 0; i < N; i++) {
A[i] = in.nextInt();
}
return A;
}
static long[] inputLong(int N) {
long A[] = new long[N];
for (int i = 0; i < A.length; i++) {
A[i] = in.nextLong();
}
return A;
}
static int GCD(int a, int b) {
if (b == 0) {
return a;
} else {
return GCD(b, a % b);
}
}
static long GCD(long a, long b) {
if (b == 0) {
return a;
} else {
return GCD(b, a % b);
}
}
}
class SegmentTree {
long[] t;
public SegmentTree(int n) {
t = new long[n + n];
Arrays.fill(t, Long.MIN_VALUE);
}
public long get(int i) {
return t[i + t.length / 2];
}
public void add(int i, long value) {
i += t.length / 2;
t[i] = value;
for (; i > 1; i >>= 1) {
t[i >> 1] = Math.max(t[i], t[i ^ 1]);
}
}
// max[a, b]
public long max(int a, int b) {
long res = Long.MIN_VALUE;
for (a += t.length / 2, b += t.length / 2; a <= b; a = (a + 1) >> 1, b = (b - 1) >> 1) {
if ((a & 1) != 0) {
res = Math.max(res, t[a]);
}
if ((b & 1) == 0) {
res = Math.max(res, t[b]);
}
}
return res;
}
}
class Pair {
int i, j;
Pair(int i, int j) {
this.i = i;
this.j = j;
}
}
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 | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 8 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | f0c34caab8ac9ba1199b9c25b9b9d7ea | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | /*
bts songs to dance to:
Filter
*/
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import static java.lang.System.out;
import java.util.*;
import java.io.*;
import java.math.*;
public class x1514D
{
public static void main(String hi[]) throws Exception
{
FastScanner infile = new FastScanner();
int N = infile.nextInt();
int Q = infile.nextInt();
int[] arr = infile.nextInts(N);
Query[] qq = new Query[Q];
for(int i=0; i < Q; i++)
{
int a = infile.nextInt();
int b = infile.nextInt();
qq[i] = new Query(a-1, b-1, i);
}
Arrays.sort(qq);
int[] res = new int[Q];
//do first query
int[] freq = new int[N+1];
int[] vals = new int[N+1];
for(int i=qq[0].left; i <= qq[0].right; i++)
freq[arr[i]]++;
for(int v=0; v <= N; v++)
vals[freq[v]]++;
int large = 0;
for(int v=1; v <= N; v++)
if(vals[v] > 0)
large = v;
res[qq[0].id] = get(qq[0].right-qq[0].left+1, large);
int L = qq[0].left;
int R = qq[0].right;
for(int q=1; q < Q; q++)
{
//extend out then in
int left = qq[q].left;
int right = qq[q].right;
while(L > left)
{
L--;
freq[arr[L]]++;
int f = freq[arr[L]];
vals[f-1]--;
vals[f]++;
if(large < f)
large = f;
}
while(R < right)
{
R++;
freq[arr[R]]++;
int f = freq[arr[R]];
vals[f-1]--;
vals[f]++;
if(large < f)
large = f;
}
//shrink
while(L < left)
{
int f = freq[arr[L]];
freq[arr[L]]--;
vals[f-1]++;
vals[f]--;
if(vals[large] == 0)
large--;
L++;
}
while(R > right)
{
int f = freq[arr[R]];
freq[arr[R]]--;
vals[f-1]++;
vals[f]--;
if(vals[large] == 0)
large--;
R--;
}
res[qq[q].id] = get(right-left+1, large);
}
StringBuilder sb = new StringBuilder();
for(int x: res)
sb.append(x+"\n");
System.out.print(sb);
}
public static int get(int N, int K)
{
if(K <= ((N+1)>>1))
return 1;
int small = N-K;
return K-small;
}
}
class Query implements Comparable<Query>
{
public int left;
public int right;
public int id;
public int SQRT = 548;
public Query(int a, int b, int i)
{
left = a;
right = b;
id = i;
}
public int compareTo(Query oth)
{
if(left/SQRT == oth.left/SQRT)
return right-oth.right;
return left/SQRT-oth.left/SQRT;
}
}
/*
a subsequence is valid if you can rearrange it such that no two adjacents are the same value
process queries offline? (left then right or something else)
mo's will almost definitely tle (with segtree)
maybe it'll pass with O(1) extra stuff
*/
class FastScanner
{
private int BS = 1 << 16;
private char NC = (char) 0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
} catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
private char getChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1) return NC;
bId = 0;
}
return (char) buf[bId++];
}
public int nextInt() {
return (int) nextLong();
}
public int[] nextInts(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] nextLongs(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public long nextLong() {
cnt = 1;
boolean neg = false;
if (c == NC) c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-') neg = true;
}
long res = 0;
for (; c >= '0' && c <= '9'; c = getChar()) {
res = (res << 3) + (res << 1) + c - '0';
cnt *= 10;
}
return neg ? -res : res;
}
public double nextDouble() {
double cur = nextLong();
return c != '.' ? cur : cur + nextLong() / cnt;
}
public double[] nextDoubles(int N) {
double[] res = new double[N];
for (int i = 0; i < N; i++) {
res[i] = nextDouble();
}
return res;
}
public String next() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
public boolean hasNext() {
if (c > 32) return true;
while (true) {
c = getChar();
if (c == NC) return false;
else if (c > 32) return true;
}
}
}
| Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 8 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | a2c4b5af2740e748e579d30fd1915e8b | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | /*
bts songs to dance to:
Filter
*/
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import static java.lang.System.out;
import java.util.*;
import java.io.*;
import java.math.*;
public class x1514D
{
public static void main(String hi[]) throws Exception
{
FastScanner infile = new FastScanner();
int N = infile.nextInt();
int Q = infile.nextInt();
int[] arr = infile.nextInts(N);
Query[] qq = new Query[Q];
for(int i=0; i < Q; i++)
{
int a = infile.nextInt();
int b = infile.nextInt();
qq[i] = new Query(a-1, b-1, i);
}
Arrays.sort(qq);
int[] res = new int[Q];
//do first query
int[] freq = new int[N+1];
int[] vals = new int[N+1];
for(int i=qq[0].left; i <= qq[0].right; i++)
freq[arr[i]]++;
for(int v=0; v <= N; v++)
vals[freq[v]]++;
int large = 0;
for(int v=1; v <= N; v++)
if(vals[v] > 0)
large = v;
res[qq[0].id] = get(qq[0].right-qq[0].left+1, large);
int L = qq[0].left;
int R = qq[0].right;
for(int q=1; q < Q; q++)
{
//extend out then in
int left = qq[q].left;
int right = qq[q].right;
while(L > left)
{
L--;
freq[arr[L]]++;
int f = freq[arr[L]];
vals[f-1]--;
vals[f]++;
if(large < f)
large = f;
}
while(R < right)
{
R++;
freq[arr[R]]++;
int f = freq[arr[R]];
vals[f-1]--;
vals[f]++;
if(large < f)
large = f;
}
//shrink
while(L < left)
{
int f = freq[arr[L]];
freq[arr[L]]--;
vals[f-1]++;
vals[f]--;
if(vals[large] == 0)
large--;
L++;
}
while(R > right)
{
int f = freq[arr[R]];
freq[arr[R]]--;
vals[f-1]++;
vals[f]--;
if(vals[large] == 0)
large--;
R--;
}
res[qq[q].id] = get(right-left+1, large);
}
StringBuilder sb = new StringBuilder();
for(int x: res)
sb.append(x+"\n");
System.out.print(sb);
}
public static int get(int N, int K)
{
if(K <= ((N+1)>>1))
return 1;
int small = N-K;
return K-small;
}
}
class Query implements Comparable<Query>
{
public int left;
public int right;
public int id;
public int SQRT = 550;
public Query(int a, int b, int i)
{
left = a;
right = b;
id = i;
}
public int compareTo(Query oth)
{
if(left/SQRT == oth.left/SQRT)
return right-oth.right;
return left/SQRT-oth.left/SQRT;
}
}
/*
a subsequence is valid if you can rearrange it such that no two adjacents are the same value
process queries offline? (left then right or something else)
mo's will almost definitely tle (with segtree)
maybe it'll pass with O(1) extra stuff
*/
class FastScanner
{
private int BS = 1 << 16;
private char NC = (char) 0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
} catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
private char getChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1) return NC;
bId = 0;
}
return (char) buf[bId++];
}
public int nextInt() {
return (int) nextLong();
}
public int[] nextInts(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] nextLongs(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public long nextLong() {
cnt = 1;
boolean neg = false;
if (c == NC) c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-') neg = true;
}
long res = 0;
for (; c >= '0' && c <= '9'; c = getChar()) {
res = (res << 3) + (res << 1) + c - '0';
cnt *= 10;
}
return neg ? -res : res;
}
public double nextDouble() {
double cur = nextLong();
return c != '.' ? cur : cur + nextLong() / cnt;
}
public double[] nextDoubles(int N) {
double[] res = new double[N];
for (int i = 0; i < N; i++) {
res[i] = nextDouble();
}
return res;
}
public String next() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
public boolean hasNext() {
if (c > 32) return true;
while (true) {
c = getChar();
if (c == NC) return false;
else if (c > 32) return true;
}
}
}
| Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 8 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | 2854303a12d9e39553ac02c65086d153 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | /*
bts songs to dance to:
Filter
*/
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import static java.lang.System.out;
import java.util.*;
import java.io.*;
import java.math.*;
public class x1514D
{
public static void main(String hi[]) throws Exception
{
FastScanner infile = new FastScanner();
int N = infile.nextInt();
int Q = infile.nextInt();
int[] arr = infile.nextInts(N);
Query[] qq = new Query[Q];
for(int i=0; i < Q; i++)
{
int a = infile.nextInt();
int b = infile.nextInt();
qq[i] = new Query(a-1, b-1, i);
}
Arrays.sort(qq);
int[] res = new int[Q];
//do first query
int[] freq = new int[N+1];
int[] vals = new int[N+1];
for(int i=qq[0].left; i <= qq[0].right; i++)
freq[arr[i]]++;
for(int v=0; v <= N; v++)
vals[freq[v]]++;
int large = 0;
for(int v=1; v <= N; v++)
if(vals[v] > 0)
large = v;
res[qq[0].id] = get(qq[0].right-qq[0].left+1, large);
int L = qq[0].left;
int R = qq[0].right;
for(int q=1; q < Q; q++)
{
//extend out then in
int left = qq[q].left;
int right = qq[q].right;
while(L > left)
{
L--;
freq[arr[L]]++;
int f = freq[arr[L]];
vals[f-1]--;
vals[f]++;
if(large < f)
large = f;
}
while(R < right)
{
R++;
freq[arr[R]]++;
int f = freq[arr[R]];
vals[f-1]--;
vals[f]++;
if(large < f)
large = f;
}
//shrink
while(L < left)
{
int f = freq[arr[L]];
freq[arr[L]]--;
vals[f-1]++;
vals[f]--;
if(vals[large] == 0)
large--;
L++;
}
while(R > right)
{
int f = freq[arr[R]];
freq[arr[R]]--;
vals[f-1]++;
vals[f]--;
if(vals[large] == 0)
large--;
R--;
}
res[qq[q].id] = get(right-left+1, large);
}
StringBuilder sb = new StringBuilder();
for(int x: res)
sb.append(x+"\n");
System.out.print(sb);
}
public static int get(int N, int K)
{
if(K <= ((N+1)>>1))
return 1;
int small = N-K;
return K-small;
}
}
class Query implements Comparable<Query>
{
public int left;
public int right;
public int id;
public int SQRT = 548;
public Query(int a, int b, int i)
{
left = a;
right = b;
id = i;
}
public int compareTo(Query oth)
{
if(left/SQRT == oth.left/SQRT)
return right-oth.right;
return left/SQRT-oth.left/SQRT;
}
}
/*
a subsequence is valid if you can rearrange it such that no two adjacents are the same value
process queries offline? (left then right or something else)
mo's will almost definitely tle (with segtree)
maybe it'll pass with O(1) extra stuff
*/
class FastScanner
{
private int BS = 1 << 16;
private char NC = (char) 0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
} catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
private char getChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1) return NC;
bId = 0;
}
return (char) buf[bId++];
}
public int nextInt() {
return (int) nextLong();
}
public int[] nextInts(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] nextLongs(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public long nextLong() {
cnt = 1;
boolean neg = false;
if (c == NC) c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-') neg = true;
}
long res = 0;
for (; c >= '0' && c <= '9'; c = getChar()) {
res = (res << 3) + (res << 1) + c - '0';
cnt *= 10;
}
return neg ? -res : res;
}
public double nextDouble() {
double cur = nextLong();
return c != '.' ? cur : cur + nextLong() / cnt;
}
public double[] nextDoubles(int N) {
double[] res = new double[N];
for (int i = 0; i < N; i++) {
res[i] = nextDouble();
}
return res;
}
public String next() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
public boolean hasNext() {
if (c > 32) return true;
while (true) {
c = getChar();
if (c == NC) return false;
else if (c > 32) return true;
}
}
} | Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 8 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | 7f8510515a6f5775a76a0796de5fce57 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | import java.io.*;import java.util.*;import java.math.*;
public class Main
{
public void tq()throws Exception
{
st=new StringTokenizer(br.readLine());
int tq=1;
sb=new StringBuilder(1000000);
o:
while(tq-->0)
{
int n=i();
int q=i();
int ar[]=ari(n);
int qq[][]=new int[q][3];
int bl=(int)(Math.sqrt(n));
for(int x=0;x<q;x++)
{
int a=i();
int b=i();
qq[x][0]=a-1;
qq[x][1]=b-1;
qq[x][2]=x;
}
Arrays.sort(qq,(aa,bb)->
{
if(aa[0]/bl!=bb[0]/bl)return (aa[0]-bb[0]<=0?-1:1);
return (aa[1]-bb[1]<=0?-1:1);
});
int f[]=new int[n+1];
int ff[]=new int[n+1];
ff[0]=n;
int l=0;
int r=-1;
int m=0;
int fi[]=new int[q];
for(int e[]:qq)
{
// p(e);
while(l>e[0])
{
l--;
ff[f[ar[l]]]--;
f[ar[l]]++;
ff[f[ar[l]]]++;
if(f[ar[l]]==m+1)m++;
}
// p(f);
// p(ff);
while(r<e[1])
{
r++;
ff[f[ar[r]]]--;
f[ar[r]]++;
ff[f[ar[r]]]++;
if(f[ar[r]]==m+1)m++;
}
// p(f);
// p(ff);
while(l<e[0])
{
if(f[ar[l]]==m&&ff[f[ar[l]]]==1)m--;
ff[f[ar[l]]]--;
f[ar[l]]--;
ff[f[ar[l]]]++;
l++;
}
// p(f);
// p(ff);
while(r>e[1])
{
if(f[ar[r]]==m&&ff[f[ar[r]]]==1)m--;
ff[f[ar[r]]]--;
f[ar[r]]--;
ff[f[ar[r]]]++;
r--;
}
// p(f);
// p(ff);
int d=e[1]-e[0]+1;
d=(d+3)/2;
if(m>=d)
{
int nn=(e[1]-e[0]+1);
int le=nn-m;
fi[e[2]]=nn-2*le;
}
else fi[e[2]]=1;
}
for(int x:fi)sl(x);
}
p(sb);
}
long mod=1000000007l;int max=Integer.MAX_VALUE,min=Integer.MIN_VALUE;
long maxl=Long.MAX_VALUE,minl=Long.MIN_VALUE;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;StringBuilder sb;
public static void main(String[] a)throws Exception{new Main().tq();}
int[] so(int ar[]){Integer r[]=new Integer[ar.length];for(int x=0;x<ar.length;x++)r[x]=ar[x];
Arrays.sort(r);for(int x=0;x<ar.length;x++)ar[x]=r[x];return ar;}
long[] so(long ar[]){Long r[]=new Long[ar.length];for(int x=0;x<ar.length;x++)r[x]=ar[x];
Arrays.sort(r);for(int x=0;x<ar.length;x++)ar[x]=r[x];return ar;}
char[] so(char ar[])
{Character r[]=new Character[ar.length];for(int x=0;x<ar.length;x++)r[x]=ar[x];
Arrays.sort(r);for(int x=0;x<ar.length;x++)ar[x]=r[x];return ar;}
void s(String s){sb.append(s);}void s(int s){sb.append(s);}void s(long s){sb.append(s);}
void s(char s){sb.append(s);}void s(double s){sb.append(s);}
void ss(){sb.append(' ');}void sl(String s){sb.append(s);sb.append("\n");}
void sl(int s){sb.append(s);sb.append("\n");}
void sl(long s){sb.append(s);sb.append("\n");}void sl(char s){sb.append(s);sb.append("\n");}
void sl(double s){sb.append(s);sb.append("\n");}void sl(){sb.append("\n");}
int min(int a,int b){return a<b?a:b;}
int min(int a,int b,int c){return a<b?a<c?a:c:b<c?b:c;}
int max(int a,int b){return a>b?a:b;}
int max(int a,int b,int c){return a>b?a>c?a:c:b>c?b:c;}
long min(long a,long b){return a<b?a:b;}
long min(long a,long b,long c){return a<b?a<c?a:c:b<c?b:c;}
long max(long a,long b){return a>b?a:b;}
long max(long a,long b,long c){return a>b?a>c?a:c:b>c?b:c;}
int abs(int a){return Math.abs(a);}
long abs(long a){return Math.abs(a);}
int sq(int a){return (int)Math.sqrt(a);}long sq(long a){return (long)Math.sqrt(a);}
long gcd(long a,long b){while(b>0l){long c=a%b;a=b;b=c;}return a;}
int gcd(int a,int b){while(b>0){int c=a%b;a=b;b=c;}return a;}
boolean pa(String s,int i,int j){while(i<j)if(s.charAt(i++)!=s.charAt(j--))return false;return true;}
boolean[] si(int n)
{boolean bo[]=new boolean[n+1];bo[0]=true;bo[1]=true;for(int x=4;x<=n;x+=2)bo[x]=true;
for(int x=3;x*x<=n;x+=2){if(!bo[x]){int vv=(x<<1);for(int y=x*x;y<=n;y+=vv)bo[y]=true;}}
return bo;}long mul(long a,long b,long m)
{long r=1l;a%=m;while(b>0){if((b&1)==1)r=(r*a)%m;b>>=1;a=(a*a)%m;}return r;}
int i()throws IOException{if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine());
return Integer.parseInt(st.nextToken());}
long l()throws IOException{if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine());
return Long.parseLong(st.nextToken());}String s()throws IOException
{if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine());return st.nextToken();}
double d()throws IOException{if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine());
return Double.parseDouble(st.nextToken());}void p(Object p){System.out.print(p);}
void p(String p){System.out.print(p);}void p(int p){System.out.print(p);}
void p(double p){System.out.print(p);}void p(long p){System.out.print(p);}
void p(char p){System.out.print(p);}void p(boolean p){System.out.print(p);}
void pl(Object p){System.out.println(p);}void pl(String p){System.out.println(p);}
void pl(int p){System.out.println(p);}void pl(char p){System.out.println(p);}
void pl(double p){System.out.println(p);}void pl(long p){System.out.println(p);}
void pl(boolean p){System.out.println(p);}void pl(){System.out.println();}
void s(int a[]){for(int e:a){sb.append(e);sb.append(' ');}sb.append("\n");}
void s(long a[]){for(long e:a){sb.append(e);sb.append(' ');}sb.append("\n");}
void s(int ar[][]){for(int a[]:ar){for(int e:a){sb.append(e);sb.append(' ');}sb.append("\n");}}
void s(char a[]){for(char e:a){sb.append(e);sb.append(' ');}sb.append("\n");}
void s(char ar[][]){for(char a[]:ar){for(char e:a){sb.append(e);sb.append(' ');}sb.append("\n");}}
int[] ari(int n)throws IOException
{int ar[]=new int[n];if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine());
for(int x=0;x<n;x++)ar[x]=Integer.parseInt(st.nextToken());return ar;}
int[][] ari(int n,int m)throws IOException
{int ar[][]=new int[n][m];for(int x=0;x<n;x++){if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine());
for(int y=0;y<m;y++)ar[x][y]=Integer.parseInt(st.nextToken());}return ar;}
long[] arl(int n)throws IOException
{long ar[]=new long[n];if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine());
for(int x=0;x<n;x++) ar[x]=Long.parseLong(st.nextToken());return ar;}
long[][] arl(int n,int m)throws IOException
{long ar[][]=new long[n][m];for(int x=0;x<n;x++)
{if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine());
for(int y=0;y<m;y++)ar[x][y]=Long.parseLong(st.nextToken());}return ar;}
String[] ars(int n)throws IOException
{String ar[]=new String[n];if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine());
for(int x=0;x<n;x++) ar[x]=st.nextToken();return ar;}
double[] ard(int n)throws IOException
{double ar[]=new double[n];if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine());
for(int x=0;x<n;x++)ar[x]=Double.parseDouble(st.nextToken());return ar;}
double[][] ard(int n,int m)throws IOException
{double ar[][]=new double[n][m];for(int x=0;x<n;x++)
{if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine());
for(int y=0;y<m;y++)ar[x][y]=Double.parseDouble(st.nextToken());}return ar;}
char[] arc(int n)throws IOException{char ar[]=new char[n];if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine());
for(int x=0;x<n;x++)ar[x]=st.nextToken().charAt(0);return ar;}
char[][] arc(int n,int m)throws IOException{char ar[][]=new char[n][m];
for(int x=0;x<n;x++){String s=br.readLine();for(int y=0;y<m;y++)ar[x][y]=s.charAt(y);}return ar;}
void p(int ar[]){StringBuilder sb=new StringBuilder(11*ar.length);
for(int a:ar){sb.append(a);sb.append(' ');}System.out.println(sb);}
void p(int ar[][]){StringBuilder sb=new StringBuilder(2*ar.length*ar[0].length);
for(int a[]:ar){for(int aa:a){sb.append(aa);sb.append(' ');}sb.append("\n");}p(sb);}
void p(long ar[]){StringBuilder sb=new StringBuilder(2*ar.length);
for(long a:ar){sb.append(a);sb.append(' ');}System.out.println(sb);}
void p(long ar[][]){StringBuilder sb=new StringBuilder(2*ar.length*ar[0].length);
for(long a[]:ar){for(long aa:a){sb.append(aa);sb.append(' ');}sb.append("\n");}p(sb);}
void p(String ar[]){int c=0;for(String s:ar)c+=s.length()+1;StringBuilder sb=new StringBuilder(c);
for(String a:ar){sb.append(a);sb.append(' ');}System.out.println(sb);}
void p(double ar[]){StringBuilder sb=new StringBuilder(2*ar.length);
for(double a:ar){sb.append(a);sb.append(' ');}System.out.println(sb);}
void p(double ar[][]){StringBuilder sb=new StringBuilder(2*ar.length*ar[0].length);
for(double a[]:ar){for(double aa:a){sb.append(aa);sb.append(' ');}sb.append("\n");}p(sb);}
void p(char ar[]){StringBuilder sb=new StringBuilder(2*ar.length);
for(char aa:ar){sb.append(aa);sb.append(' ');}System.out.println(sb);}
void p(char ar[][]){StringBuilder sb=new StringBuilder(2*ar.length*ar[0].length);
for(char a[]:ar){for(char aa:a){sb.append(aa);sb.append(' ');}sb.append("\n");}p(sb);}
} | Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 8 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | d4aa9efb3a9836e35bb41b5d570eb1e8 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | import java.util.*;
import java.io.*;
public class D
{
static InputReader in=new InputReader(System.in);
static OutputWriter out=new OutputWriter(System.out);
static StringBuilder sb=new StringBuilder();
static int MAX = 3 * 100000 + 5;
static int n;
// Main Class Starts Here
public static void main(String[] args)throws IOException
{
// Write your code.
int t = 1;
while(t-- > 0){
int n = in();
int q = in();
int a[] = an(n);
Query[] queries = new Query[q];
for(int i = 0; i < q; i++) {
queries[i] = new Query(in() - 1, in() - 1, i);
}
// APPLY MO's Algorithm - Square Root Decomposition
// Sort based on blocks, if equal based on r (non-decreasing)
int block_size = (int)Math.sqrt(n);
Comparator<Query> c1 = (q1, q2) -> {
if((q1.l / block_size) == (q2.l / block_size))
return q1.r - q2.r;
return (q1.l / block_size) - (q2.l / block_size);
};
Arrays.sort(queries, c1);
int count[] = new int[MAX+1];
int freq[] = new int[MAX+1];
// instead of tracking the frequency of element.
// keep track of frequency of frequency.
// meaning - if there is an element with frequency = 5 then, frequencyArray[5]++.
// if the frequency of the same element decreases by 1, the frequency[5]--, frequency[4]++.
int start = 0;
int end = 0;
int max = 0;
for(int i = 0; i < q; i++){
int L = queries[i].l;
int R = queries[i].r;
while(end <= R){
int prevCount = count[a[end]];
int curCount = ++count[a[end]];
freq[prevCount]--;
freq[curCount]++;
if(curCount > max)
max = curCount;
end++;
}
while(end > R + 1){
end--;
int prevCount = count[a[end]];
int curCount = --count[a[end]];
freq[prevCount]--;
if(freq[max] == 0)
max--;
freq[curCount]++;
}
while(start < L){
int prevCount = count[a[start]];
int curCount = --count[a[start]];
freq[prevCount]--;
freq[curCount]++;
if(freq[max] == 0)
max--;
start++;
}
while(start > L){
start--;
int prevCount = count[a[start]];
int curCount = ++count[a[start]];
freq[prevCount]--;
freq[curCount]++;
if(curCount > max)
max = curCount;
}
// app("Range : "+queries[i].toString()+" , Maximum Frequency: "+max+"\n");
int segmentSize = (queries[i].r - queries[i].l) + 1;
int violationLimit = (int)(Math.ceil((1.0D * segmentSize)/ 2.0D));
// prln("Violation Limit : "+violationLimit+" \nSegment Size: "+segmentSize);
int ans = -1;
if(segmentSize % 2 == 0){ // even
if(max <= violationLimit){
ans = 1;
}
else{
int diff = max - violationLimit;
ans = 2 * diff - 1;
ans++;
}
}
else{
if(max <= violationLimit){
ans = 1;
}
else{
int diff = max - violationLimit;
ans = 2 * diff;
ans++;
}
}
queries[i].setAnswer(ans);
}
c1 = (q1, q2) -> (q1.index - q2.index);
Arrays.sort(queries, c1);
for(Query query: queries){
app(query.answer+"\n");
}
}
out.printLine(sb);
out.close();
}
static class Query{
int l;
int r;
int index;
int answer;
public Query(int l, int r, int index){
this.l = l;
this.r = r;
this.index = index;
}
public void setAnswer(int answer){
this.answer = answer;
}
@Override
public String toString(){
return "("+(l+1)+","+(r+1)+")";
}
}
static class Pair{
int x, y;
public Pair(int x, int y){
this.x = x;
this.y = y;
}
@Override
public String toString(){
return "("+x+","+y+")";
}
}
static class DisjointSet{
int parent[];
int rank[];
int size;
public DisjointSet(int n){
this.parent = new int[n];
this.rank = new int[n];
this.size = n;
for(int i = 0; i < n; i++)
parent[i] = i;
}
public int findParent(int x){
if(parent[x] != x){
return parent[x] = findParent(parent[x]);
}
return parent[x];
}
public boolean inSameComponents(int x, int y){
int parentX = findParent(x);
int parentY = findParent(y);
return parentX == parentY;
}
public int mergeComponents(int x, int y){
int parentX = findParent(x);
int parentY = findParent(y);
if(parentX == parentY) {
return 0; // merge failed as in the same components hence no change in components
}
if(rank[parentX] < rank[parentY]){
parent[parentX] = parentY;
}
else if(rank[parentX] > rank[parentY]){
parent[parentY] = parentX;
}
else{
// merge component of y to x.
parent[parentY] = parentX;
rank[parentX]++;
}
return 1; // merge successful - decrease in merge components
}
public int countComponents(){
int count = 0;
for(int i = 0; i < size; i++)
if(parent[i] == i) count++;
return count;
}
public TreeMap<Integer, List<Integer>> getComponents(){
TreeMap<Integer, List<Integer>> componentMap = new TreeMap<>();
for(int i = 0; i < size; i++){
List<Integer> componentElements = componentMap.getOrDefault(parent[i], new ArrayList<>());
componentElements.add(i);
componentMap.put(parent[i], componentElements);
}
return componentMap;
}
public Set<Integer> getComponentsWithNode(int x){
HashSet<Integer> set = new HashSet<>();
int parentX = findParent(x);
for(int i = 0; i < n; i++){
if(parent[i] == parentX){
set.add(i);
}
}
return set;
}
}
// segment tree.
static class SegmentTree{
int size;
List<Integer> st[];
int n;
public SegmentTree(int a[], int n){
int x = (int)Math.ceil((Math.log(n) / Math.log(2)));
this.size = (int)Math.pow(2, 2 * x) - 1;
st = new ArrayList[size];
buildTree(0, n-1, 0, a);
this.n = n;
}
public List<Integer> buildTree(int l, int r, int curIndex, int a[]){
if(l == r){
st[curIndex] = new ArrayList<>();
st[curIndex].add(a[l]);
return st[curIndex];
}
int mid = (l + r) / 2;
List<Integer> leftList = buildTree(l, mid, 2 * curIndex + 1, a);
List<Integer> rightList = buildTree(mid + 1, r, 2 * curIndex + 2, a);
int lastLeftProduct = leftList.get(leftList.size() - 1);
int firstRightProduct = rightList.get(0);
int gcd = gcd(lastLeftProduct, firstRightProduct);
if(gcd > 1){
st[curIndex] = new ArrayList<>(leftList);
st[curIndex].addAll(rightList);
}
else{
st[curIndex] = new ArrayList<>();
for(int i = 0; i < leftList.size() - 1; i++)
st[curIndex].add(leftList.get(i));
st[curIndex].add(lastLeftProduct * firstRightProduct);
for(int i = 1 ; i < rightList.size(); i++)
st[curIndex].add((rightList.get(i)));
}
return st[curIndex];
}
public int resolveQuery(int ql, int qr){
List<Integer> ans = mergeRanges(0, n-1, ql, qr, 0);
return ans.size();
}
public List<Integer> mergeRanges(int l, int r, int ql, int qr, int curIndex){
if(l > qr || r < ql) return null;
if(ql <= l && qr >= r){
return st[curIndex];
}
int mid = (l + r) / 2;
List<Integer> leftList = mergeRanges(l, mid, ql, qr, 2 * curIndex + 1);
List<Integer> rightList = mergeRanges(mid + 1, r, ql, qr, 2 * curIndex + 2);
if(leftList != null && rightList != null){
int lastLeftProduct = leftList.get(leftList.size() - 1);
int firstRightProduct = rightList.get(0);
int gcd = gcd(lastLeftProduct, firstRightProduct);
List<Integer> mergedList = new ArrayList<>();
if(gcd > 1){
mergedList.addAll(leftList);
mergedList.addAll(rightList);
}
else{
for(int i = 0; i < leftList.size() - 1; i++)
mergedList.add(leftList.get(i));
mergedList.add(lastLeftProduct * firstRightProduct);
for(int i = 1 ; i < rightList.size(); i++)
mergedList.add((rightList.get(i)));
}
return mergedList;
}
else if(leftList != null) return leftList;
else return rightList;
}
public void printTree(){
for(int i = 0; i < st.length; i++)
prln(i+" , "+st[i]);
}
}
public static String atsi(int a[]){
return Arrays.toString(a);
}
public static String atsl(long a[]){
return Arrays.toString(a);
}
public static long gcd(long a, long b){
if(b == 0) return a;
return gcd(b, a % b);
}
public static int gcd(int a, int b){
if(b == 0) return a;
return gcd(b, a % b);
}
public static int[] an(int n) {
int ar[]=new int[n];
for(int i=0;i<n;i++)
ar[i]=in();
return ar;
}
public static long[] lan(int n) {
long ar[]=new long[n];
for(int i=0;i<n;i++)
ar[i]=lin();
return ar;
}
public static String atos(Object ar[]) {
return Arrays.toString(ar);
}
public static int in() {
return in.readInt();
}
public static long lin() {
return in.readLong();
}
public static String sn() {
return in.readString();
}
public static void prln(Object o) {
out.printLine(o);
}
public static void prn(Object o) {
out.print(o);
}
public static void app(Object o) {
sb.append(o);
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public 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 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 | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 8 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | c228ea8b8c41d5815a96c45f5069441f | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | import java.util.*;
import java.util.Map.Entry;
import java.math.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
InputReader in = new InputReader(System.in);
// Scanner in = new Scanner(System.in);
// Scanner in = new Scanner(new BufferedReader(new
// InputStreamReader(System.in)));
PrintWriter out = new PrintWriter(System.out);
// InputReader in = new InputReader(new
// File("ethan_traverses_a_tree.txt"));
// PrintWriter out = new PrintWriter(new
// File("ethan_traverses_a_tree-output.txt"));
int n = in.nextInt();
int q = in.nextInt();
Map<Integer, List<Integer>> map = new HashMap<Integer, List<Integer>>();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
if (map.containsKey(a[i]) == false) {
map.put(a[i], new ArrayList<Integer>());
}
map.get(a[i]).add(i);
}
int k = 1;
int tmpn = 1;
while (tmpn <= n) {
tmpn = tmpn * 2;
k++;
}
k--;
int[][] dp = new int[k][n];
for (int i = 0; i < k; i++) {
int size = 1 << i;
HashMap<Integer, Integer> tmpmap = new HashMap<Integer, Integer>();
for (int j = 0; j < size; j++) {
mapadd(tmpmap, a[j]);
}
for (int j = 0; j <= n - size; j++) {
if (j != 0) {
mapadd(tmpmap, a[j + size - 1]);
mapremove(tmpmap, a[j - 1]);
}
if (size == 1) {
dp[i][j] = a[j];
} else {
int v1 = dp[i - 1][j];
int v2 = dp[i - 1][j + size / 2];
if (tmpmap.get(v1) > tmpmap.get(v2)) {
dp[i][j] = v1;
} else {
dp[i][j] = v2;
}
}
}
}
for (int p = 0; p < q; p++) {
int l = in.nextInt() - 1;
int r = in.nextInt() - 1;
int length = r - l + 1;
int nowlength = length;
int nowl = l;
int maxtime = 1;
for (int i = k - 1; i >= 0; i--) {
int size = 1 << i;
if (nowlength >= size) {
int checknum = dp[i][nowl];
maxtime = Math.max(maxtime, getcount(map.get(checknum), l, r));
nowl = nowl + size;
nowlength = nowlength - size;
if (nowlength == 0) {
break;
}
}
}
int remain = length - maxtime;
int ans = maxtime - remain;
if (ans < 1) {
ans = 1;
}
out.printf("%d\n", ans);
}
out.close();
}
static public void mapadd(HashMap<Integer, Integer> treeMap, int key) {
if (treeMap.containsKey(key) == false) {
treeMap.put(key, 1);
} else {
treeMap.put(key, treeMap.get(key) + 1);
}
}
static public void mapremove(HashMap<Integer, Integer> treeMap, int key) {
if (treeMap.get(key) == 1) {
treeMap.remove(key);
} else {
treeMap.put(key, treeMap.get(key) - 1);
}
}
static public int getcount(List<Integer> list, int l, int r) {
return binarySearch(list, r + 1) - binarySearch(list, l);
}
static public int binarySearch(List<Integer> list, int value) {
int left = 0;
int right = list.size();
while (left < right) {
int mid = (left + right) / 2;
int now = list.get(mid);
if (now < value) {
left = mid + 1;
} else {
right = mid;
}
}
return left;
}
static class InputReader {
BufferedReader br;
StringTokenizer st;
public InputReader(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public InputReader(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public boolean hasNext() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return false;
st = new StringTokenizer(s);
}
return true;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
} | Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 8 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | e404c9bd9814230243e14db8fb89fd46 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | import java.io.BufferedInputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class P1514D {
private static int bits(int n) {
int k = 0;
while (n > 0) {
n >>= 1;
k++;
}
return k;
}
private static int[][] buildTree(final int n, final int[] A) {
final int m = bits(n-1) + 1;
final int[][] T = new int[m][];
int l = 1;
for (int k = 0; k < m; k++) {
T[k] = new int[((n-1) >> k) + 1];
// log("k=" + k + ", l=" + l + ", w=" + T[k].length);
for (int j = 0; j < T[k].length; j++) {
final Map<Integer, Integer> idx = new HashMap<>(l);
final int[] F = new int[l];
int ma = -1;
int mf = 0;
final int i0 = j << k;
final int i1 = Math.min(i0 + l, n);
for (int i = i0; i < i1; i++) {
final int a = A[i];
final int b = idx.computeIfAbsent(a, a_ -> idx.size());
F[b]++;
if (F[b] > mf) {
ma = a;
mf = F[b];
}
}
T[k][j] = ma;
}
// log("T[" + k + "]=" + Arrays.toString(T[k]));
l <<= 1;
}
return T;
}
private static Set<Integer> candidates(final int[][] T, int l, int r) {
final Set<Integer> result = new HashSet<>();
for (int k = 0; k < T.length; k++) {
if (l >= r) {
if (l == r) {
result.add(T[k][l]);
}
break;
}
if ((l & 1) == 1) {
result.add(T[k][l]);
l += 1;
}
if ((r & 1) == 0) {
result.add(T[k][r]);
r -= 1;
}
l >>= 1;
r >>= 1;
}
return result;
}
private static int[][] buildIndexArr(int n, int[] A) {
final List<List<Integer>> idxLst = new ArrayList<>(n);
for (int a = 0; a < n; a++) {
idxLst.add(new ArrayList<>());
}
for (int i = 0; i < n; i++) {
final int a = A[i];
idxLst.get(a).add(i);
}
final int[][] idxArr = new int[n][];
int a = 0;
for (final List<Integer> lst : idxLst) {
idxArr[a++] = toArray(lst);
}
return idxArr;
}
private static int binSearchL(final int[] X, final int x, int lo, int hi) {
while (lo < hi) {
int mid = (lo + hi) / 2;
if (X[mid] >= x) {
hi = mid;
} else {
lo = mid + 1;
}
}
return lo;
}
private static int binSearchR(final int[] X, final int x, int lo, int hi) {
while (lo < hi) {
int mid = (lo + hi) / 2;
if (X[mid] > x) {
hi = mid;
} else {
lo = mid + 1;
}
}
return lo;
}
private static int freq(int[] I, int l, int r) {
final int j0 = binSearchL(I, l, 0, I.length);
final int j1 = binSearchR(I, r, j0, I.length);
return j1 - j0;
}
private static int[] solve(int n, int q, int[] A, int[][] Q) {
final int[][] T = buildTree(n, A);
final int[][] I = buildIndexArr(n, A);
final int[] R = new int[q];
for (int i = 0; i < q; i++) {
final int l = Q[i][0];
final int r = Q[i][1];
final int d = r - l + 1;
int mf = 0;
for (int c : candidates(T, l, r)) {
final int f = freq(I[c], l, r);
mf = Math.max(f, mf);
}
R[i] = Math.max(mf - (d - mf), 1);
}
return R;
}
public static void main(String[] args) throws IOException {
try {
final FastReader fr = new FastReader(
new BufferedInputStream(System.in));
final int n = fr.readInt();
final int q = fr.readInt();
final int[] A = new int[n];
final int[][] Q = new int[q][2];
for (int i = 0; i < n; i++) {
A[i] = fr.readInt() - 1;
}
for (int j = 0; j < q; j++) {
Q[j][0] = fr.readInt() - 1;
Q[j][1] = fr.readInt() - 1;
}
final int[] R = solve(n, q, A, Q);
final StringBuilder sb = new StringBuilder();
for (int j = 0; j < q; j++) {
sb.append(R[j]).append('\n');
}
System.out.print(sb);
} catch (Throwable t) {
t.printStackTrace(System.out);
System.exit(1);
}
}
private static int[] toArray(final List<Integer> lst) {
final int[] arr = new int[lst.size()];
int i = 0;
for (int x : lst) {
arr[i++] = x;
}
return arr;
}
private static void log(Object o) {
System.err.println(o);
}
private static class FastReader implements Closeable {
private static final byte B_SP = ' ';
private static final byte B_CR = '\r';
private static final byte B_LF = '\n';
private static final byte B_0 = '0';
private static final byte B_9 = '9';
private static final byte B_DASH = '-';
private final InputStream in;
private byte prev;
public FastReader(InputStream in) {
this.in = in;
}
public byte read() throws IOException {
return (prev = (byte) in.read());
}
public byte readNonWs() throws IOException {
byte b;
do {
b = read();
} while (b <= B_SP);
return b;
}
public int readInt() throws IOException {
byte b = readNonWs();
final boolean neg = (b == B_DASH);
if (neg) {
b = read();
}
int i = (b - B_0);
b = read();
while (b >= B_0 && b <= B_9) {
i = i * 10 + (b - B_0);
b = read();
}
return neg ? -i : i;
}
public long readLong() throws IOException {
byte b = readNonWs();
final boolean neg = (b == B_DASH);
if (neg) {
b = read();
}
long i = (b - B_0);
b = read();
while (b >= B_0 && b <= B_9) {
i = i * 10 + (b - B_0);
b = read();
}
return neg ? -i : i;
}
public int readToken(byte[] tbuf) throws IOException {
byte b = readNonWs();
int i = 0;
do {
tbuf[i++] = b;
b = read();
} while (b >= B_SP);
return i;
}
public int readLine(byte[] lbuf) throws IOException {
byte b;
if (prev == B_CR) {
b = read();
if (b == B_LF) {
b = read();
}
} else {
b = read();
}
int i = 0;
while (b >= B_SP) {
lbuf[i++] = b;
b = read();
}
return i;
}
@Override
public void close() throws IOException {
in.close();
}
}
}
| Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 8 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | 94ca92280a45c96ec03f7e80b361041c | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
import java.io.*;
import java.util.*;
import java.util.StringTokenizer;
import static java.lang.Math.*;
public class D {
static class FastScanner {
public BufferedReader reader;
public StringTokenizer tokenizer;
public FastScanner() {
reader = new BufferedReader(new InputStreamReader(System.in), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public int[] readIntArray(int n){
int[] arr=new int[n];
for(int i=0;i<n;i++){
arr[i]=nextInt();
}
return arr;
}
public long[] readLongArray(int n){
long[] arr=new long[n];
for(int i=0;i<n;i++){
arr[i]=nextLong();
}
return arr;
}
}
public static int[] sort(int[] arr){
ArrayList<Integer> temp = new ArrayList<>();
for(int x:arr) temp.add(x);
Collections.sort(temp);
int i=0;
for(int x:temp){
arr[i++]=x;
}
return arr;
}
public static int gcd(int a,int b){
if(b==0) return a;
return gcd(b,a%b);
}
public static void main(String args[]) throws Exception {
FastScanner sc = new FastScanner();
int T = 1;
// T = sc.nextInt();
PrintWriter pw = new PrintWriter(System.out);
StringBuilder sb = new StringBuilder();
while (T-- > 0) {
solve(sc, pw, sb);
}
pw.print(sb);
pw.close();
}
public static void solve(FastScanner sc, PrintWriter pw, StringBuilder sb) throws Exception {
int n=sc.nextInt();
int q=sc.nextInt();
ArrayList<Integer> arr=new ArrayList<>();
for(int i=0;i<n;i++){
int num=sc.nextInt();
arr.add(num);
}
WaveletTree wt=new WaveletTree(arr,1,n);
while(q-->0){
int l=sc.nextInt();
int r=sc.nextInt();
int range=r-l+1;
int med=wt.kth(l,r,range/2+1); // the middle element of the sorted range is the one that we need to get rid of
int cnt=wt.CountEqual(l,r,med);
int ans=max(cnt-(range-cnt),1);
sb.append(ans+"\n");
}
}
static class WaveletTree{
int lowx,highx; // lowx and highx are range for the tree
WaveletTree wtl,wtr; // for each node we will nedd to store info about it left and right child
ArrayList<Integer> LeftChildCount; // counts/maps the number of nodes that maps to left child
// The index in left child of index idx is found by LeftChildCount.get(idx)
// The index in right child of index idx is found by idx-LeftChildCount.get(idx)+1;
public WaveletTree (ArrayList<Integer> arr,int low,int high){
// arr is the array for which we need to build the current level of wavelet tree
// low and high are the min and max elements of the arr
lowx = low;
highx=high;
if(lowx == highx || arr.isEmpty()) return;
int mid=lowx+(highx-lowx)/2;
LeftChildCount=new ArrayList<>();
int cnt=0;
LeftChildCount.add(cnt);
for(int x:arr){
if(x<=mid) cnt++;
LeftChildCount.add(cnt);
}
ArrayList<Integer> arr_lo=new ArrayList<>();
ArrayList<Integer> arr_high=new ArrayList<>();
for(int x:arr){
if(x<=mid) arr_lo.add(x);
else arr_high.add(x);
}
wtl = new WaveletTree(arr_lo,lowx,mid);
wtr = new WaveletTree(arr_high,mid+1,highx);
}
// Returns the kth element in the range [l,r]
int kth(int l,int r,int k){
if(l>r) return 0;
if(lowx==highx) return lowx;
// we need to get the mapping of the elements at l-1 and r-1
int Map_Left=LeftChildCount.get(l-1);
int Map_Right=LeftChildCount.get(r);
// we count the number of elements between them
int CntLeft=Map_Right-Map_Left;
if(k<=CntLeft){
// if kth element lies in that range i.e it is in the right child now change the range using map accordingly
return wtl.kth(Map_Left+1,Map_Right,k);
}
return wtr.kth(l-Map_Left,r-Map_Right,k);
}
// count number of elements int the range[l,r] less than or equal to k
int CountLessThanOrEqual(int l,int r,int k){
if(l>r || k<lowx) return 0;
if(highx<=k) return r-l+1;
int Map_Left=LeftChildCount.get(l-1);
int Map_Right=LeftChildCount.get(r);
return wtl.CountLessThanOrEqual(Map_Left+1,Map_Right,k)+wtr.CountLessThanOrEqual(l-Map_Left,r-Map_Right,k);
}
// count number of elements in the range[l,r] equal to k
int CountEqual(int l,int r,int k){
if(l>r || k<lowx || k>highx) return 0;
if(lowx==highx) return r-l+1;
int Map_Left=LeftChildCount.get(l-1);
int Map_Right=LeftChildCount.get(r);
int mid=lowx+(highx-lowx)/2;
if(k<=mid) return wtl.CountEqual(Map_Left+1,Map_Right,k);
return wtr.CountEqual(l-Map_Left,r-Map_Right,k);
}
}
} | Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 8 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | 4fc0f2a25fd0314cf6a6b57631827cd0 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | // package FinalGrind;
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.StringTokenizer;
public class CutAndStick {
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
public static void main(String[] args)throws IOException {
Reader s=new Reader();
int n=s.nextInt();
int q=s.nextInt();
int freq[]=new int[n+1];
int a[]=new int[n+1];
for(int i=1;i<=n;i++){
a[i]=s.nextInt();
}
int block_size=(int)Math.sqrt(n);
ArrayList<Query> queries=new ArrayList<>();
for(int i=1;i<=q;i++){
int l=s.nextInt();
int r=s.nextInt();
int block=l/block_size;
queries.add(new Query(l,r,block,i));
}
Collections.sort(queries);
int freq_count[]=new int[n+1];
int left=0,right=0;
int ans[]=new int[q+1];
int max_freq=0;
for(Query query:queries){
int l=query.l;
int r=query.r;
if(left==0&&right==0){
for(int i=l;i<=r;i++){
freq[a[i]]++;
freq_count[freq[a[i]]]++;
freq_count[freq[a[i]]-1]--;
if(freq[a[i]]>max_freq){
max_freq=freq[a[i]];
}
}
left=l;
right=r;
}
while(left>l){
left--;
freq[a[left]]++;
freq_count[freq[a[left]]]++;
freq_count[freq[a[left]]-1]--;
if(freq[a[left]]>max_freq){
max_freq=freq[a[left]];
}
}
while(right<r){
right++;
freq[a[right]]++;
freq_count[freq[a[right]]]++;
freq_count[freq[a[right]]-1]--;
if(freq[a[right]]>max_freq){
max_freq=freq[a[right]];
}
}
while(left<l){
freq[a[left]]--;
freq_count[freq[a[left]]]++;
freq_count[freq[a[left]]+1]--;
if(max_freq==(freq[a[left]]+1)&&freq_count[max_freq]==0){
max_freq--;
}
left++;
}
while(right>r){
freq[a[right]]--;
freq_count[freq[a[right]]]++;
freq_count[freq[a[right]]+1]--;
if(max_freq==(freq[a[right]]+1)&&freq_count[max_freq]==0){
max_freq--;
}
right--;
}
int len=r-l+1;
int rem=len-max_freq;
if(max_freq>rem+1){
int del=max_freq-rem-1;
ans[query.index]=del+1;
}
else{
ans[query.index]=1;
}
}
StringBuilder print=new StringBuilder();
for(int i=1;i<=q;i++){
print.append(ans[i]+"\n");
}
System.out.print(print.toString());
}
}
class Query implements Comparable<Query>{
int l,r,block,index;
public Query(int l,int r,int block,int index){
this.l=l;
this.r=r;
this.block=block;
this.index=index;
}
@Override
public int compareTo(Query o) {
if(this.block!=o.block){
return this.block-o.block;
}
else{
return this.r-o.r;
}
}
}
| Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 8 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | aabc02d9cd684cf787b7ec0ff3be896a | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
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 Lynn
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
Scanner in;
PrintWriter out;
public void solve(int testNumber, Scanner in, PrintWriter out) {
this.in = in;
this.out = out;
run();
}
void run() {
int n = in.nextInt();
int q = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
SegTree st = new SegTree(a);
while (q-- != 0) {
int l = in.nextInt();
int r = in.nextInt();
int f = st.query(l - 1, r - 1);
out.println(Math.max(1, 2 * f - (r - l + 1)));
}
}
class SegTree {
public int N;
public int n;
public int[] is;
public ArrayList<ArrayList<Integer>> idx = new ArrayList<>();
public int[] a;
public SegTree(int[] a) {
this.a = a;
this.n = a.length;
N = Integer.highestOneBit(n) << 1;
is = new int[N * 2];
for (int i = 0; i < n; i++) {
a[i]--;
idx.add(new ArrayList<>());
}
for (int i = 0; i < n; i++) {
idx.get(a[i]).add(i);
}
buildTree(0, n - 1, 1);
}
public void buildTree(int l, int r, int cur) {
if (l == r) {
is[cur] = this.a[l];
} else {
int m = (l + r) / 2;
buildTree(l, m, cur * 2);
buildTree(m + 1, r, cur * 2 + 1);
is[cur] = mergeInfo(l, r, is[cur * 2], is[cur * 2 + 1]);
}
}
public int count(int l, int r, int x) {
return Algo.upperBound(this.idx.get(x), r) - Algo.lowerBound(this.idx.get(x), l);
}
public int mergeInfo(int l, int r, int lx, int rx) {
return count(l, r, lx) >= count(l, r, rx) ? lx : rx;
}
public int query(int s, int t) {
return query(1, 0, n - 1, s, t, new HashMap<Integer, Integer>());
}
int query(int o, int l, int r, int s, int t, HashMap<Integer, Integer> queryCache) {
if (s <= l && r <= t) {
return queryCache.getOrDefault(is[o], count(s, t, is[o]));
} else {
int m = (l + r) / 2;
if (t <= m) return query(o * 2, l, m, s, t, queryCache);
if (s > m) return query(o * 2 + 1, m + 1, r, s, t, queryCache);
return Math.max(query(o * 2, l, m, s, t, queryCache), query(o * 2 + 1, m + 1, r, s, t, queryCache));
}
}
}
}
static class Algo {
public static <T extends Comparable<T>> int lowerBound(List<T> tl, T v) {
return lowerBound(tl, 0, tl.size(), v);
}
public static <T extends Comparable<T>> int lowerBound(List<T> tl, int l, int r, T v) {
while (l < r) {
int m = (l + r) >> 1;
if (tl.get(m).compareTo(v) >= 0) r = m;
else l = m + 1;
}
return l;
}
public static <T extends Comparable<T>> int upperBound(List<T> tl, T v) {
return upperBound(tl, 0, tl.size(), v);
}
public static <T extends Comparable<T>> int upperBound(List<T> tl, int l, int r, T v) {
while (l < r) {
int m = (l + r) >> 1;
if (tl.get(m).compareTo(v) > 0) r = m;
else l = m + 1;
}
return l;
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
eat("");
}
private void eat(String s) {
st = new StringTokenizer(s);
}
public String nextLine() {
try {
return br.readLine();
} catch (IOException e) {
return null;
}
}
public boolean hasNext() {
while (!st.hasMoreTokens()) {
String s = nextLine();
if (s == null)
return false;
eat(s);
}
return true;
}
public String next() {
hasNext();
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 8 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | f7c080d77dddcef6e15cf571e90a3439 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | //Utilities
import java.io.*;
import java.util.*;
public class a {
static int t;
static int n, q;
static int[] a;
static ArrayList<Integer>[] arr;
static int[] left, log2;
static Pair[] p;
public static void main(String[] args) throws IOException {
t = 1;
while (t-- > 0) {
n = in.iscan(); q = in.iscan();
arr = new ArrayList[n+1]; left = new int[n+1]; log2 = new int[n+1];
log2[1] = 0;
for (int i = 0; i <= n; i++) {
arr[i] = new ArrayList<Integer>();
if (i >= 2) {
log2[i] = log2[i/2] + 1;
}
}
a = new int[n+1];
for (int i = 1; i <= n; i++) {
a[i] = in.iscan();
arr[a[i]].add(i);
}
p = new Pair[q];
for (int i = 0; i < q; i++) {
p[i] = new Pair(i, in.iscan(), in.iscan());
}
Arrays.sort(p);
int[] res = new int[q];
for (int j = 0; j < q; j++) {
int l = p[j].l, r = p[j].r, idx = p[j].idx;
int f = 0;
for (int i = 0; i < 22; i++) {
int rand = l + (int)((r-l+1) * Math.random());
f = Math.max(f, sumRange(l, r, a[rand]));
}
res[idx] = Math.max(1, 1 + f - ((r - l + 1) - f + 1));
}
for (int i = 0; i < q; i++) {
out.println(res[i]);
}
out.println();
}
out.close();
}
static int sumRange(int ql, int qr, int type) {
int sz = arr[type].size();
if (left[type] >= sz) {
return 0;
}
while (left[type] + 1 < sz && arr[type].get(left[type]) < ql) {
left[type]++;
}
int rr = -1;
int l = left[type], r = sz-1, mid;
while (l <= r) {
mid = (l+r)/2;
if (arr[type].get(mid) <= qr) {
rr = mid;
l = mid+1;
}
else {
r = mid-1;
}
}
return rr - left[type] + 1;
}
static class Pair implements Comparable<Pair>{
int idx, l, r;
Pair(int idx, int l, int r){
this.idx = idx;
this.l = l;
this.r = r;
}
public int compareTo(Pair p) {
return l - p.l;
}
}
static INPUT in = new INPUT(System.in);
static PrintWriter out = new PrintWriter(System.out);
private static class INPUT {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar, numChars;
public INPUT (InputStream stream) {
this.stream = stream;
}
public INPUT (String file) throws IOException {
this.stream = new FileInputStream (file);
}
public int cscan () throws IOException {
if (curChar >= numChars) {
curChar = 0;
numChars = stream.read (buf);
}
if (numChars == -1)
return numChars;
return buf[curChar++];
}
public int iscan () throws IOException {
int c = cscan (), sgn = 1;
while (space (c))
c = cscan ();
if (c == '-') {
sgn = -1;
c = cscan ();
}
int res = 0;
do {
res = (res << 1) + (res << 3);
res += c - '0';
c = cscan ();
}
while (!space (c));
return res * sgn;
}
public String sscan () throws IOException {
int c = cscan ();
while (space (c))
c = cscan ();
StringBuilder res = new StringBuilder ();
do {
res.appendCodePoint (c);
c = cscan ();
}
while (!space (c));
return res.toString ();
}
public double dscan () throws IOException {
int c = cscan (), sgn = 1;
while (space (c))
c = cscan ();
if (c == '-') {
sgn = -1;
c = cscan ();
}
double res = 0;
while (!space (c) && c != '.') {
if (c == 'e' || c == 'E')
return res * UTILITIES.fast_pow (10, iscan ());
res *= 10;
res += c - '0';
c = cscan ();
}
if (c == '.') {
c = cscan ();
double m = 1;
while (!space (c)) {
if (c == 'e' || c == 'E')
return res * UTILITIES.fast_pow (10, iscan ());
m /= 10;
res += (c - '0') * m;
c = cscan ();
}
}
return res * sgn;
}
public long lscan () throws IOException {
int c = cscan (), sgn = 1;
while (space (c))
c = cscan ();
if (c == '-') {
sgn = -1;
c = cscan ();
}
long res = 0;
do {
res = (res << 1) + (res << 3);
res += c - '0';
c = cscan ();
}
while (!space (c));
return res * sgn;
}
public boolean space (int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
public static class UTILITIES {
static final double EPS = 10e-6;
public static void sort(int[] a, boolean increasing) {
ArrayList<Integer> arr = new ArrayList<Integer>();
int n = a.length;
for (int i = 0; i < n; i++) {
arr.add(a[i]);
}
Collections.sort(arr);
for (int i = 0; i < n; i++) {
if (increasing) {
a[i] = arr.get(i);
}
else {
a[i] = arr.get(n-1-i);
}
}
}
public static void sort(long[] a, boolean increasing) {
ArrayList<Long> arr = new ArrayList<Long>();
int n = a.length;
for (int i = 0; i < n; i++) {
arr.add(a[i]);
}
Collections.sort(arr);
for (int i = 0; i < n; i++) {
if (increasing) {
a[i] = arr.get(i);
}
else {
a[i] = arr.get(n-1-i);
}
}
}
public static void sort(double[] a, boolean increasing) {
ArrayList<Double> arr = new ArrayList<Double>();
int n = a.length;
for (int i = 0; i < n; i++) {
arr.add(a[i]);
}
Collections.sort(arr);
for (int i = 0; i < n; i++) {
if (increasing) {
a[i] = arr.get(i);
}
else {
a[i] = arr.get(n-1-i);
}
}
}
public static int lower_bound (int[] arr, int x) {
int low = 0, high = arr.length, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] >= x)
high = mid;
else
low = mid + 1;
}
return low;
}
public static int upper_bound (int[] arr, int x) {
int low = 0, high = arr.length, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] > x)
high = mid;
else
low = mid + 1;
}
return low;
}
public static void updateMap(HashMap<Integer, Integer> map, int key, int v) {
if (!map.containsKey(key)) {
map.put(key, v);
}
else {
map.put(key, map.get(key) + v);
}
if (map.get(key) == 0) {
map.remove(key);
}
}
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 long fast_pow_mod (long b, long x, int mod) {
if (x == 0) return 1;
if (x == 1) return b;
if (x % 2 == 0) return fast_pow_mod (b * b % mod, x / 2, mod) % mod;
return b * fast_pow_mod (b * b % mod, x / 2, mod) % mod;
}
public static long fast_pow (long b, long x) {
if (x == 0) return 1;
if (x == 1) return b;
if (x % 2 == 0) return fast_pow (b * b, x / 2);
return b * fast_pow (b * b, x / 2);
}
public static long choose (long n, long k) {
k = Math.min (k, n - k);
long val = 1;
for (int i = 0; i < k; ++i)
val = val * (n - i) / (i + 1);
return val;
}
public static long permute (int n, int k) {
if (n < k) return 0;
long val = 1;
for (int i = 0; i < k; ++i)
val = (val * (n - i));
return val;
}
// start of permutation and lower/upper bound template
public static void nextPermutation(int[] nums) {
//find first decreasing digit
int mark = -1;
for (int i = nums.length - 1; i > 0; i--) {
if (nums[i] > nums[i - 1]) {
mark = i - 1;
break;
}
}
if (mark == -1) {
reverse(nums, 0, nums.length - 1);
return;
}
int idx = nums.length-1;
for (int i = nums.length-1; i >= mark+1; i--) {
if (nums[i] > nums[mark]) {
idx = i;
break;
}
}
swap(nums, mark, idx);
reverse(nums, mark + 1, nums.length - 1);
}
public static void swap(int[] nums, int i, int j) {
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
public static void reverse(int[] nums, int i, int j) {
while (i < j) {
swap(nums, i, j);
i++;
j--;
}
}
static int lower_bound (int[] arr, int hi, int cmp) {
int low = 0, high = hi, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] >= cmp) high = mid;
else low = mid + 1;
}
return low;
}
static int upper_bound (int[] arr, int hi, int cmp) {
int low = 0, high = hi, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] > cmp) high = mid;
else low = mid + 1;
}
return low;
}
// end of permutation and lower/upper bound template
}
} | Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 11 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | ea611e67595369321d0e50057bf74d26 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.Random;
public class SolutionD {
// author: Nagabhushan S Baddi
// PRIMARY VARIABLES
private static int n, m;
private static int[] a, b;
private static long ans;
private static int[][] id, dp;
private static int idf;
private static String s, t;
private static HashMap<Integer, ArrayList<Integer>> g;
// CONSTANTS
private static final int MOD = (int) 1e9 + 7;
public static void main(String[] args) {
n = ini();
int q = ini();
a = ina(n);
HashMap<Integer, ArrayList<Integer>> map = new HashMap<>();
for(int i=0; i<n; i++) {
int x = a[i];
if (!map.containsKey(x)) {
map.put(x, new ArrayList<>());
}
map.get(x).add(i);
}
Random random = new Random();
for(int j=0; j<q; j++) {
int l = ini()-1;
int r = ini()-1;
HashSet<Integer> picked = new HashSet<>();
int maxOcc = 0;
int maxOccVal = 0;
for(int gen=0; gen<30; gen++) {
int k = random.nextInt(r-l+1);
k += l;
int v = a[k];
if (picked.contains(v)) {
continue;
}
picked.add(v);
ArrayList<Integer> list = map.get(v);
int allowed = (r-l+1) / 2;
if (list.size() <= allowed) {
continue;
}
int low = 0;
int high = list.size()-1;
while(low<high) {
int mid = (low+high)/2;
if (list.get(mid)>r) {
high = mid;
} else {
low = mid+1;
}
}
int pivot1 = 0;
if (list.get(low)<=r) {
pivot1 = list.size()-1;
} else {
pivot1 = low-1;
}
low = 0;
high = list.size()-1;
while(low<high) {
int mid = low+(high-low+1)/2;
if (list.get(mid)<l) {
low = mid;
} else {
high = mid-1;
}
}
int pivot2 = 0;
if (list.get(low)>=l) {
pivot2 = 0;
} else {
pivot2 = low+1;
}
int occ = pivot1-pivot2+1;
// System.out.println(l+" "+r+" "+v+" "+occ);
if (occ>maxOcc) {
// System.out.println(l+" "+r+" --> "+v+" "+occ);
maxOcc = occ;
maxOccVal = v;
}
if (maxOcc>allowed) {
break;
}
}
int allowed = (int)Math.ceil((double)(r-l+1)/2);
if (maxOcc<=allowed) {
println(1);
continue;
}
int other = r-l+1-maxOcc;
int left = maxOcc-(other+1);
println(left+1);
// System.out.println((l+1)+" "+(r+1)+" "+maxOccVal);
}
out.flush();
out.close();
}
// Segment Tree
private static class SegmentTree<T extends Comparable<T>> {
private int n, m;
private T[] a;
private T[] seg;
private T NULLVALUE;
public SegmentTree(int n, T NULLVALUE) {
this.NULLVALUE = NULLVALUE;
this.n = n;
m = (int)Math.pow(2, 1+(int)Math.ceil(Math.log(n)/Math.log(2)));
seg = (T[]) new Object[m];
}
public SegmentTree(T[] a, int n, T NULLVALUE) {
this.NULLVALUE = NULLVALUE;
this.a = a;
this.n = n;
m = 4 * n;
seg = (T[]) new Object[m];
construct(0, n - 1, 0);
}
private void update(int pos) {
// Range Sum
// seg[pos] = seg[2*pos+1]+seg[2*pos+2];
// Range Min
if (seg[2 * pos + 1].compareTo(seg[2 * pos + 2]) <= 0) {
seg[pos] = seg[2 * pos + 1];
} else {
seg[pos] = seg[2 * pos + 2];
}
}
private T optimum(T leftValue, T rightValue) {
// Range Sum
// return leftValue+rightValue;
// Range Min
if (leftValue.compareTo(rightValue) <= 0) {
return leftValue;
} else {
return rightValue;
}
}
public void construct(int low, int high, int pos) {
if (low == high) {
seg[pos] = a[low];
return;
}
int mid = (low + high) / 2;
construct(low, mid, 2 * pos + 1);
construct(mid + 1, high, 2 * pos + 2);
update(pos);
}
public void add(int index, T value) {
add(index, value, 0, n - 1, 0);
}
private void add(int index, T value, int low, int high, int pos) {
if (low == high) {
seg[pos] = value;
return;
}
int mid = (low + high) / 2;
if (index <= mid) {
add(index, value, low, mid, 2 * pos + 1);
} else {
add(index, value, mid + 1, high, 2 * pos + 2);
}
update(pos);
}
public T get(int qlow, int qhigh) {
return get(qlow, qhigh, 0, n - 1, 0);
}
public T get(int qlow, int qhigh, int low, int high, int pos) {
if (qlow > low || low > qhigh) {
return NULLVALUE;
} else if (qlow <= low || qhigh >= high) {
return seg[pos];
} else {
int mid = (low + high) / 2;
T leftValue = get(qlow, qhigh, low, mid, 2 * pos + 1);
T rightValue = get(qlow, qhigh, mid + 1, high, 2 * pos + 2);
return optimum(leftValue, rightValue);
}
}
}
// INIT
private static void initCase(int z) {
idf = z;
ans = 0;
}
// PRINT ANSWER
private static void printAns(Object o) {
out.println(o);
}
private static void printAns(Object o, int testCaseNo) {
out.println("Case #" + testCaseNo + ": " + o);
}
private static void printArray(Object[] a) {
for (int i = 0; i < a.length; i++) {
out.print(a[i] + " ");
}
out.println();
}
// SORT SHORTCUTS - QUICK SORT TO MERGE SORT
private static void sort(int[] a) {
int n = a.length;
Integer[] b = new Integer[n];
for (int i = 0; i < n; i++) {
b[i] = a[i];
}
Arrays.sort(b);
for (int i = 0; i < n; i++) {
a[i] = b[i];
}
}
private static void sort(long[] a) {
int n = a.length;
Long[] b = new Long[n];
for (int i = 0; i < n; i++) {
b[i] = a[i];
}
Arrays.sort(b);
for (int i = 0; i < n; i++) {
a[i] = b[i];
}
}
// INPUT SHORTCUTS
private static int[] ina(int n) {
int[] temp = new int[n];
for (int i = 0; i < n; i++) {
temp[i] = in.nextInt();
}
return temp;
}
private static int[][] ina2d(int n, int m) {
int[][] temp = new int[n][m];
for (int i = 0; i < n; i++) {
temp[i] = ina(m);
}
return temp;
}
private static int ini() {
return in.nextInt();
}
private static long inl() {
return in.nextLong();
}
private static double ind() {
return Double.parseDouble(ins());
}
private static String ins() {
return in.readString();
}
// PRINT SHORTCUTS
private static void println(Object... o) {
for (Object x : o) {
out.write(x + "");
}
out.write("\n");
}
private static void pd(Object... o) {
for (Object x : o) {
out.write(x + "");
}
out.flush();
out.write("\n");
}
private static void print(Object... o) {
for (Object x : o) {
out.write(x + "");
}
}
// GRAPH SHORTCUTS
private static HashMap<Integer, ArrayList<Integer>> intree(int n) {
HashMap<Integer, ArrayList<Integer>> g = new HashMap<>();
for (int i = 0; i < n; i++) {
g.put(i, new ArrayList<>());
}
for (int i = 0; i < n - 1; i++) {
int u = ini() - 1;
int v = ini() - 1;
g.get(u).add(v);
g.get(v).add(u);
}
return g;
}
private static HashMap<Integer, ArrayList<Integer>> ingraph(int n, int m) {
HashMap<Integer, ArrayList<Integer>> g = new HashMap<>();
for (int i = 0; i < n; i++) {
g.put(i, new ArrayList<>());
}
for (int i = 0; i < m; i++) {
int u = ini() - 1;
int v = ini() - 1;
g.get(u).add(v);
g.get(v).add(u);
}
return g;
}
private static HashMap<Integer, ArrayList<Integer>> indirectedgraph(int n, int m) {
HashMap<Integer, ArrayList<Integer>> g = new HashMap<>();
for (int i = 0; i < n; i++) {
g.put(i, new ArrayList<>());
}
for (int i = 0; i < m; i++) {
int u = ini() - 1;
int v = ini() - 1;
g.get(u).add(v);
}
return g;
}
private static HashMap<Integer, ArrayList<Edge>> inweightedgraph(int n, int m) {
HashMap<Integer, ArrayList<Edge>> g = new HashMap<>();
for (int i = 0; i < n; i++) {
g.put(i, new ArrayList<>());
}
for (int i = 0; i < m; i++) {
int u = ini() - 1;
int v = ini() - 1;
int w = ini();
Edge edge = new Edge(u, v, w);
g.get(u).add(edge);
g.get(v).add(edge);
}
return g;
}
private static class Edge implements Comparable<Edge> {
private int u, v;
private long w;
public Edge(int a, int b, long c) {
u = a;
v = b;
w = c;
}
public int other(int x) {
return (x == u ? v : u);
}
public int compareTo(Edge edge) {
return Long.compare(w, edge.w);
}
}
private static class Pair {
private int u, v;
public Pair(int a, int b) {
u = a;
v = b;
}
public int hashCode() {
return u + v + u * v;
}
public boolean equals(Object object) {
Pair pair = (Pair) object;
return u == pair.u && v == pair.v;
}
}
private static class Node implements Comparable<Node> {
private int u;
private long dist;
public Node(int a, long b) {
u = a;
dist = b;
}
public int compareTo(Node node) {
return Long.compare(dist, node.dist);
}
}
// MATHS AND NUMBER THEORY SHORTCUTS
private static int gcd(int a, int b) {
// O(log(min(a,b)))
if (b == 0)
return a;
return gcd(b, a % b);
}
private static long modExp(long a, long b) {
if (b == 0)
return 1;
a %= MOD;
long exp = modExp(a, b / 2);
if (b % 2 == 0) {
return (exp * exp) % MOD;
} else {
return (a * ((exp * exp) % MOD)) % MOD;
}
}
private long mul(int a, int b) {
return a * 1L * b;
}
// DSU
private static class DSU {
private int[] id;
private int[] size;
private int n;
public DSU(int n) {
this.n = n;
id = new int[n];
for (int i = 0; i < n; i++) {
id[i] = i;
}
size = new int[n];
Arrays.fill(size, 1);
}
private int root(int u) {
while (u != id[u]) {
id[u] = id[id[u]];
u = id[u];
}
return u;
}
public boolean connected(int u, int v) {
return root(u) == root(v);
}
public void union(int u, int v) {
int p = root(u);
int q = root(v);
if (size[p] >= size[q]) {
id[q] = p;
size[p] += size[q];
} else {
id[p] = q;
size[q] += size[p];
}
}
}
// KMP
private static int countSearch(String s, String p) {
int n = s.length();
int m = p.length();
int[] b = backTable(p);
int j = 0;
int count = 0;
for (int i = 0; i < n; i++) {
if (j == m) {
j = b[j - 1];
count++;
}
while (j != 0 && s.charAt(i) != p.charAt(j)) {
j = b[j - 1];
}
if (s.charAt(i) == p.charAt(j)) {
j++;
}
}
if (j == m)
count++;
return count;
}
private static int[] backTable(String p) {
int m = p.length();
int j = 0;
int[] b = new int[m];
for (int i = 1; i < m; i++) {
while (j != 0 && p.charAt(i) != p.charAt(j)) {
j = b[j - 1];
}
if (p.charAt(i) == p.charAt(j)) {
b[i] = ++j;
}
}
return b;
}
private static class LCA {
private HashMap<Integer, ArrayList<Integer>> g;
private int[] level;
private int[] a;
private int[][] P;
private int n, m;
private int[] xor;
public LCA(HashMap<Integer, ArrayList<Integer>> g, int[] a) {
this.g = g;
this.a = a;
n = g.size();
m = (int) (Math.log(n) / Math.log(2)) + 5;
P = new int[n][m];
xor = new int[n];
level = new int[n];
preprocess();
}
private void preprocess() {
dfs(0, -1);
for (int j = 1; j < m; j++) {
for (int i = 0; i < n; i++) {
if (P[i][j - 1] != -1) {
P[i][j] = P[P[i][j - 1]][j - 1];
}
}
}
}
private void dfs(int u, int p) {
P[u][0] = p;
xor[u] = a[u] ^ (p == -1 ? 0 : xor[p]);
level[u] = (p == -1 ? 0 : level[p] + 1);
for (int v : g.get(u)) {
if (v == p)
continue;
dfs(v, u);
}
}
public int lca(int u, int v) {
if (level[v] > level[u]) {
int temp = v;
v = u;
u = temp;
}
for (int j = m; j >= 0; j--) {
if (level[u] - (1 << j) < level[v]) {
continue;
} else {
u = P[u][j];
}
}
if (u == v)
return u;
for (int j = m - 1; j >= 0; j--) {
if (P[u][j] == -1 || P[u][j] == P[v][j]) {
continue;
} else {
u = P[u][j];
v = P[v][j];
}
}
return P[u][0];
}
private int xor(int u, int v) {
int l = lca(u, v);
return xor[u] ^ xor[v] ^ a[l];
}
}
// FAST INPUT OUTPUT LIBRARY
private static InputReader in = new InputReader(System.in);
private static PrintWriter out = new PrintWriter(System.out);
private static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(InputStream st) {
this.stream = st;
}
public int read() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
}
| Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 11 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | 1461c0ca710e3736b2cd22db83b6b804 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.Random;
public class SolutionD {
// author: Nagabhushan S Baddi
// PRIMARY VARIABLES
private static int n, m;
private static int[] a, b;
private static long ans;
private static int[][] id, dp;
private static int idf;
private static String s, t;
private static HashMap<Integer, ArrayList<Integer>> g;
// CONSTANTS
private static final int MOD = (int) 1e9 + 7;
public static void main(String[] args) {
n = ini();
int q = ini();
a = ina(n);
HashMap<Integer, ArrayList<Integer>> map = new HashMap<>();
for(int i=0; i<n; i++) {
int x = a[i];
if (!map.containsKey(x)) {
map.put(x, new ArrayList<>());
}
map.get(x).add(i);
}
Random random = new Random();
for(int j=0; j<q; j++) {
int l = ini()-1;
int r = ini()-1;
HashSet<Integer> picked = new HashSet<>();
int maxOcc = 0;
int maxOccVal = 0;
for(int gen=0; gen<30; gen++) {
int k = random.nextInt(r-l+1);
k += l;
int v = a[k];
if (picked.contains(v)) {
continue;
}
picked.add(v);
ArrayList<Integer> list = map.get(v);
int allowed = (r-l+1) / 2;
if (list.size() <= allowed) {
continue;
}
int low = 0;
int high = list.size()-1;
while(low<high) {
int mid = (low+high)/2;
if (list.get(mid)>r) {
high = mid;
} else {
low = mid+1;
}
}
int pivot1 = 0;
if (list.get(low)<=r) {
pivot1 = list.size()-1;
} else {
pivot1 = low-1;
}
low = 0;
high = list.size()-1;
while(low<high) {
int mid = low+(high-low+1)/2;
if (list.get(mid)<l) {
low = mid;
} else {
high = mid-1;
}
}
int pivot2 = 0;
if (list.get(low)>=l) {
pivot2 = 0;
} else {
pivot2 = low+1;
}
int occ = pivot1-pivot2+1;
// System.out.println(l+" "+r+" "+v+" "+occ);
if (occ>maxOcc) {
// System.out.println(l+" "+r+" --> "+v+" "+occ);
maxOcc = occ;
maxOccVal = v;
}
if (maxOcc>allowed) {
break;
}
}
int allowed = (int)Math.ceil((double)(r-l+1)/2);
if (maxOcc<=allowed) {
println(1);
continue;
}
int other = r-l+1-maxOcc;
int left = maxOcc-(other+1);
println(left+1);
// System.out.println((l+1)+" "+(r+1)+" "+maxOccVal);
}
out.flush();
out.close();
}
// Segment Tree
private static class SegmentTree<T extends Comparable<T>> {
private int n, m;
private T[] a;
private T[] seg;
private T NULLVALUE;
public SegmentTree(int n, T NULLVALUE) {
this.NULLVALUE = NULLVALUE;
this.n = n;
m = (int)Math.pow(2, 1+(int)Math.ceil(Math.log(n)/Math.log(2)));
seg = (T[]) new Object[m];
}
public SegmentTree(T[] a, int n, T NULLVALUE) {
this.NULLVALUE = NULLVALUE;
this.a = a;
this.n = n;
m = 4 * n;
seg = (T[]) new Object[m];
construct(0, n - 1, 0);
}
private void update(int pos) {
// Range Sum
// seg[pos] = seg[2*pos+1]+seg[2*pos+2];
// Range Min
if (seg[2 * pos + 1].compareTo(seg[2 * pos + 2]) <= 0) {
seg[pos] = seg[2 * pos + 1];
} else {
seg[pos] = seg[2 * pos + 2];
}
}
private T optimum(T leftValue, T rightValue) {
// Range Sum
// return leftValue+rightValue;
// Range Min
if (leftValue.compareTo(rightValue) <= 0) {
return leftValue;
} else {
return rightValue;
}
}
public void construct(int low, int high, int pos) {
if (low == high) {
seg[pos] = a[low];
return;
}
int mid = (low + high) / 2;
construct(low, mid, 2 * pos + 1);
construct(mid + 1, high, 2 * pos + 2);
update(pos);
}
public void add(int index, T value) {
add(index, value, 0, n - 1, 0);
}
private void add(int index, T value, int low, int high, int pos) {
if (low == high) {
seg[pos] = value;
return;
}
int mid = (low + high) / 2;
if (index <= mid) {
add(index, value, low, mid, 2 * pos + 1);
} else {
add(index, value, mid + 1, high, 2 * pos + 2);
}
update(pos);
}
public T get(int qlow, int qhigh) {
return get(qlow, qhigh, 0, n - 1, 0);
}
public T get(int qlow, int qhigh, int low, int high, int pos) {
if (qlow > low || low > qhigh) {
return NULLVALUE;
} else if (qlow <= low || qhigh >= high) {
return seg[pos];
} else {
int mid = (low + high) / 2;
T leftValue = get(qlow, qhigh, low, mid, 2 * pos + 1);
T rightValue = get(qlow, qhigh, mid + 1, high, 2 * pos + 2);
return optimum(leftValue, rightValue);
}
}
}
// INIT
private static void initCase(int z) {
idf = z;
ans = 0;
}
// PRINT ANSWER
private static void printAns(Object o) {
out.println(o);
}
private static void printAns(Object o, int testCaseNo) {
out.println("Case #" + testCaseNo + ": " + o);
}
private static void printArray(Object[] a) {
for (int i = 0; i < a.length; i++) {
out.print(a[i] + " ");
}
out.println();
}
// SORT SHORTCUTS - QUICK SORT TO MERGE SORT
private static void sort(int[] a) {
int n = a.length;
Integer[] b = new Integer[n];
for (int i = 0; i < n; i++) {
b[i] = a[i];
}
Arrays.sort(b);
for (int i = 0; i < n; i++) {
a[i] = b[i];
}
}
private static void sort(long[] a) {
int n = a.length;
Long[] b = new Long[n];
for (int i = 0; i < n; i++) {
b[i] = a[i];
}
Arrays.sort(b);
for (int i = 0; i < n; i++) {
a[i] = b[i];
}
}
// INPUT SHORTCUTS
private static int[] ina(int n) {
int[] temp = new int[n];
for (int i = 0; i < n; i++) {
temp[i] = in.nextInt();
}
return temp;
}
private static int[][] ina2d(int n, int m) {
int[][] temp = new int[n][m];
for (int i = 0; i < n; i++) {
temp[i] = ina(m);
}
return temp;
}
private static int ini() {
return in.nextInt();
}
private static long inl() {
return in.nextLong();
}
private static double ind() {
return Double.parseDouble(ins());
}
private static String ins() {
return in.readString();
}
// PRINT SHORTCUTS
private static void println(Object... o) {
for (Object x : o) {
out.write(x + "");
}
out.write("\n");
}
private static void pd(Object... o) {
for (Object x : o) {
out.write(x + "");
}
out.flush();
out.write("\n");
}
private static void print(Object... o) {
for (Object x : o) {
out.write(x + "");
}
}
// GRAPH SHORTCUTS
private static HashMap<Integer, ArrayList<Integer>> intree(int n) {
HashMap<Integer, ArrayList<Integer>> g = new HashMap<>();
for (int i = 0; i < n; i++) {
g.put(i, new ArrayList<>());
}
for (int i = 0; i < n - 1; i++) {
int u = ini() - 1;
int v = ini() - 1;
g.get(u).add(v);
g.get(v).add(u);
}
return g;
}
private static HashMap<Integer, ArrayList<Integer>> ingraph(int n, int m) {
HashMap<Integer, ArrayList<Integer>> g = new HashMap<>();
for (int i = 0; i < n; i++) {
g.put(i, new ArrayList<>());
}
for (int i = 0; i < m; i++) {
int u = ini() - 1;
int v = ini() - 1;
g.get(u).add(v);
g.get(v).add(u);
}
return g;
}
private static HashMap<Integer, ArrayList<Integer>> indirectedgraph(int n, int m) {
HashMap<Integer, ArrayList<Integer>> g = new HashMap<>();
for (int i = 0; i < n; i++) {
g.put(i, new ArrayList<>());
}
for (int i = 0; i < m; i++) {
int u = ini() - 1;
int v = ini() - 1;
g.get(u).add(v);
}
return g;
}
private static HashMap<Integer, ArrayList<Edge>> inweightedgraph(int n, int m) {
HashMap<Integer, ArrayList<Edge>> g = new HashMap<>();
for (int i = 0; i < n; i++) {
g.put(i, new ArrayList<>());
}
for (int i = 0; i < m; i++) {
int u = ini() - 1;
int v = ini() - 1;
int w = ini();
Edge edge = new Edge(u, v, w);
g.get(u).add(edge);
g.get(v).add(edge);
}
return g;
}
private static class Edge implements Comparable<Edge> {
private int u, v;
private long w;
public Edge(int a, int b, long c) {
u = a;
v = b;
w = c;
}
public int other(int x) {
return (x == u ? v : u);
}
public int compareTo(Edge edge) {
return Long.compare(w, edge.w);
}
}
private static class Pair {
private int u, v;
public Pair(int a, int b) {
u = a;
v = b;
}
public int hashCode() {
return u + v + u * v;
}
public boolean equals(Object object) {
Pair pair = (Pair) object;
return u == pair.u && v == pair.v;
}
}
private static class Node implements Comparable<Node> {
private int u;
private long dist;
public Node(int a, long b) {
u = a;
dist = b;
}
public int compareTo(Node node) {
return Long.compare(dist, node.dist);
}
}
// MATHS AND NUMBER THEORY SHORTCUTS
private static int gcd(int a, int b) {
// O(log(min(a,b)))
if (b == 0)
return a;
return gcd(b, a % b);
}
private static long modExp(long a, long b) {
if (b == 0)
return 1;
a %= MOD;
long exp = modExp(a, b / 2);
if (b % 2 == 0) {
return (exp * exp) % MOD;
} else {
return (a * ((exp * exp) % MOD)) % MOD;
}
}
private long mul(int a, int b) {
return a * 1L * b;
}
// DSU
private static class DSU {
private int[] id;
private int[] size;
private int n;
public DSU(int n) {
this.n = n;
id = new int[n];
for (int i = 0; i < n; i++) {
id[i] = i;
}
size = new int[n];
Arrays.fill(size, 1);
}
private int root(int u) {
while (u != id[u]) {
id[u] = id[id[u]];
u = id[u];
}
return u;
}
public boolean connected(int u, int v) {
return root(u) == root(v);
}
public void union(int u, int v) {
int p = root(u);
int q = root(v);
if (size[p] >= size[q]) {
id[q] = p;
size[p] += size[q];
} else {
id[p] = q;
size[q] += size[p];
}
}
}
// KMP
private static int countSearch(String s, String p) {
int n = s.length();
int m = p.length();
int[] b = backTable(p);
int j = 0;
int count = 0;
for (int i = 0; i < n; i++) {
if (j == m) {
j = b[j - 1];
count++;
}
while (j != 0 && s.charAt(i) != p.charAt(j)) {
j = b[j - 1];
}
if (s.charAt(i) == p.charAt(j)) {
j++;
}
}
if (j == m)
count++;
return count;
}
private static int[] backTable(String p) {
int m = p.length();
int j = 0;
int[] b = new int[m];
for (int i = 1; i < m; i++) {
while (j != 0 && p.charAt(i) != p.charAt(j)) {
j = b[j - 1];
}
if (p.charAt(i) == p.charAt(j)) {
b[i] = ++j;
}
}
return b;
}
private static class LCA {
private HashMap<Integer, ArrayList<Integer>> g;
private int[] level;
private int[] a;
private int[][] P;
private int n, m;
private int[] xor;
public LCA(HashMap<Integer, ArrayList<Integer>> g, int[] a) {
this.g = g;
this.a = a;
n = g.size();
m = (int) (Math.log(n) / Math.log(2)) + 5;
P = new int[n][m];
xor = new int[n];
level = new int[n];
preprocess();
}
private void preprocess() {
dfs(0, -1);
for (int j = 1; j < m; j++) {
for (int i = 0; i < n; i++) {
if (P[i][j - 1] != -1) {
P[i][j] = P[P[i][j - 1]][j - 1];
}
}
}
}
private void dfs(int u, int p) {
P[u][0] = p;
xor[u] = a[u] ^ (p == -1 ? 0 : xor[p]);
level[u] = (p == -1 ? 0 : level[p] + 1);
for (int v : g.get(u)) {
if (v == p)
continue;
dfs(v, u);
}
}
public int lca(int u, int v) {
if (level[v] > level[u]) {
int temp = v;
v = u;
u = temp;
}
for (int j = m; j >= 0; j--) {
if (level[u] - (1 << j) < level[v]) {
continue;
} else {
u = P[u][j];
}
}
if (u == v)
return u;
for (int j = m - 1; j >= 0; j--) {
if (P[u][j] == -1 || P[u][j] == P[v][j]) {
continue;
} else {
u = P[u][j];
v = P[v][j];
}
}
return P[u][0];
}
private int xor(int u, int v) {
int l = lca(u, v);
return xor[u] ^ xor[v] ^ a[l];
}
}
// FAST INPUT OUTPUT LIBRARY
private static InputReader in = new InputReader(System.in);
private static PrintWriter out = new PrintWriter(System.out);
private static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(InputStream st) {
this.stream = st;
}
public int read() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
}
| Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 11 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | 06c48a6c25291a57bc512d3e44494045 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;
public class SolutionD {
// PRIMARY VARIABLES
private static int n, m;
private static int[] a, b;
private static long ans;
private static int[][] id, dp;
private static int idf;
private static String s, t;
private static HashMap<Integer, ArrayList<Integer>> g;
// CONSTANTS
private static final int MOD = (int) 1e9 + 7;
public static void main(String[] args) {
n = ini();
int q = ini();
a = ina(n);
List<Integer>[] map = new List[n+1];
for(int i=0; i<n; i++) {
int x = a[i];
if (map[x] == null) {
map[x] = new ArrayList<>();
}
map[x].add(i);
}
Random random = new Random();
for(int j=0; j<q; j++) {
int l = ini()-1;
int r = ini()-1;
HashSet<Integer> picked = new HashSet<>();
int maxOcc = 0;
int allowed = (int)Math.ceil((double)(r-l+1)/2);
for(int gen=0; gen<30; gen++) {
int k = random.nextInt(r-l+1);
k += l;
int v = a[k];
if (picked.contains(v)) {
continue;
}
picked.add(v);
List<Integer> list = map[v];
if (list.size() <= allowed) {
continue;
}
int low = 0;
int high = list.size()-1;
while(low<high) {
int mid = (low+high)/2;
if (list.get(mid)>r) {
high = mid;
} else {
low = mid+1;
}
}
int pivot1 = 0;
if (list.get(low)<=r) {
pivot1 = list.size()-1;
} else {
pivot1 = low-1;
}
low = 0;
high = list.size()-1;
while(low<high) {
int mid = low+(high-low+1)/2;
if (list.get(mid)<l) {
low = mid;
} else {
high = mid-1;
}
}
int pivot2 = 0;
if (list.get(low)<l) {
pivot2 = low+1;
}
int occ = pivot1-pivot2+1;
if (occ>maxOcc) {
maxOcc = occ;
}
if (maxOcc>=allowed) {
break;
}
}
allowed = (int)Math.ceil((double)(r-l+1)/2);
if (maxOcc<=allowed) {
println(1);
continue;
}
int other = r-l+1-maxOcc;
int left = maxOcc-(other+1);
println(left+1);
}
out.flush();
out.close();
}
// Segment Tree
private static class SegmentTree<T extends Comparable<T>> {
private int n, m;
private T[] a;
private T[] seg;
private T NULLVALUE;
public SegmentTree(int n, T NULLVALUE) {
this.NULLVALUE = NULLVALUE;
this.n = n;
m = (int)Math.pow(2, 1+(int)Math.ceil(Math.log(n)/Math.log(2)));
seg = (T[]) new Object[m];
}
public SegmentTree(T[] a, int n, T NULLVALUE) {
this.NULLVALUE = NULLVALUE;
this.a = a;
this.n = n;
m = 4 * n;
seg = (T[]) new Object[m];
construct(0, n - 1, 0);
}
private void update(int pos) {
// Range Sum
// seg[pos] = seg[2*pos+1]+seg[2*pos+2];
// Range Min
if (seg[2 * pos + 1].compareTo(seg[2 * pos + 2]) <= 0) {
seg[pos] = seg[2 * pos + 1];
} else {
seg[pos] = seg[2 * pos + 2];
}
}
private T optimum(T leftValue, T rightValue) {
// Range Sum
// return leftValue+rightValue;
// Range Min
if (leftValue.compareTo(rightValue) <= 0) {
return leftValue;
} else {
return rightValue;
}
}
public void construct(int low, int high, int pos) {
if (low == high) {
seg[pos] = a[low];
return;
}
int mid = (low + high) / 2;
construct(low, mid, 2 * pos + 1);
construct(mid + 1, high, 2 * pos + 2);
update(pos);
}
public void add(int index, T value) {
add(index, value, 0, n - 1, 0);
}
private void add(int index, T value, int low, int high, int pos) {
if (low == high) {
seg[pos] = value;
return;
}
int mid = (low + high) / 2;
if (index <= mid) {
add(index, value, low, mid, 2 * pos + 1);
} else {
add(index, value, mid + 1, high, 2 * pos + 2);
}
update(pos);
}
public T get(int qlow, int qhigh) {
return get(qlow, qhigh, 0, n - 1, 0);
}
public T get(int qlow, int qhigh, int low, int high, int pos) {
if (qlow > low || low > qhigh) {
return NULLVALUE;
} else if (qlow <= low || qhigh >= high) {
return seg[pos];
} else {
int mid = (low + high) / 2;
T leftValue = get(qlow, qhigh, low, mid, 2 * pos + 1);
T rightValue = get(qlow, qhigh, mid + 1, high, 2 * pos + 2);
return optimum(leftValue, rightValue);
}
}
}
// INIT
private static void initCase(int z) {
idf = z;
ans = 0;
}
// PRINT ANSWER
private static void printAns(Object o) {
out.println(o);
}
private static void printAns(Object o, int testCaseNo) {
out.println("Case #" + testCaseNo + ": " + o);
}
private static void printArray(Object[] a) {
for (int i = 0; i < a.length; i++) {
out.print(a[i] + " ");
}
out.println();
}
// SORT SHORTCUTS - QUICK SORT TO MERGE SORT
private static void sort(int[] a) {
int n = a.length;
Integer[] b = new Integer[n];
for (int i = 0; i < n; i++) {
b[i] = a[i];
}
Arrays.sort(b);
for (int i = 0; i < n; i++) {
a[i] = b[i];
}
}
private static void sort(long[] a) {
int n = a.length;
Long[] b = new Long[n];
for (int i = 0; i < n; i++) {
b[i] = a[i];
}
Arrays.sort(b);
for (int i = 0; i < n; i++) {
a[i] = b[i];
}
}
// INPUT SHORTCUTS
private static int[] ina(int n) {
int[] temp = new int[n];
for (int i = 0; i < n; i++) {
temp[i] = in.nextInt();
}
return temp;
}
private static int[][] ina2d(int n, int m) {
int[][] temp = new int[n][m];
for (int i = 0; i < n; i++) {
temp[i] = ina(m);
}
return temp;
}
private static int ini() {
return in.nextInt();
}
private static long inl() {
return in.nextLong();
}
private static double ind() {
return Double.parseDouble(ins());
}
private static String ins() {
return in.readString();
}
// PRINT SHORTCUTS
private static void println(Object... o) {
for (Object x : o) {
out.write(x + "");
}
out.write("\n");
}
private static void pd(Object... o) {
for (Object x : o) {
out.write(x + "");
}
out.flush();
out.write("\n");
}
private static void print(Object... o) {
for (Object x : o) {
out.write(x + "");
}
}
// GRAPH SHORTCUTS
private static HashMap<Integer, ArrayList<Integer>> intree(int n) {
HashMap<Integer, ArrayList<Integer>> g = new HashMap<>();
for (int i = 0; i < n; i++) {
g.put(i, new ArrayList<>());
}
for (int i = 0; i < n - 1; i++) {
int u = ini() - 1;
int v = ini() - 1;
g.get(u).add(v);
g.get(v).add(u);
}
return g;
}
private static HashMap<Integer, ArrayList<Integer>> ingraph(int n, int m) {
HashMap<Integer, ArrayList<Integer>> g = new HashMap<>();
for (int i = 0; i < n; i++) {
g.put(i, new ArrayList<>());
}
for (int i = 0; i < m; i++) {
int u = ini() - 1;
int v = ini() - 1;
g.get(u).add(v);
g.get(v).add(u);
}
return g;
}
private static HashMap<Integer, ArrayList<Integer>> indirectedgraph(int n, int m) {
HashMap<Integer, ArrayList<Integer>> g = new HashMap<>();
for (int i = 0; i < n; i++) {
g.put(i, new ArrayList<>());
}
for (int i = 0; i < m; i++) {
int u = ini() - 1;
int v = ini() - 1;
g.get(u).add(v);
}
return g;
}
private static HashMap<Integer, ArrayList<Edge>> inweightedgraph(int n, int m) {
HashMap<Integer, ArrayList<Edge>> g = new HashMap<>();
for (int i = 0; i < n; i++) {
g.put(i, new ArrayList<>());
}
for (int i = 0; i < m; i++) {
int u = ini() - 1;
int v = ini() - 1;
int w = ini();
Edge edge = new Edge(u, v, w);
g.get(u).add(edge);
g.get(v).add(edge);
}
return g;
}
private static class Edge implements Comparable<Edge> {
private int u, v;
private long w;
public Edge(int a, int b, long c) {
u = a;
v = b;
w = c;
}
public int other(int x) {
return (x == u ? v : u);
}
public int compareTo(Edge edge) {
return Long.compare(w, edge.w);
}
}
private static class Pair {
private int u, v;
public Pair(int a, int b) {
u = a;
v = b;
}
public int hashCode() {
return u + v + u * v;
}
public boolean equals(Object object) {
Pair pair = (Pair) object;
return u == pair.u && v == pair.v;
}
}
private static class Node implements Comparable<Node> {
private int u;
private long dist;
public Node(int a, long b) {
u = a;
dist = b;
}
public int compareTo(Node node) {
return Long.compare(dist, node.dist);
}
}
// MATHS AND NUMBER THEORY SHORTCUTS
private static int gcd(int a, int b) {
// O(log(min(a,b)))
if (b == 0)
return a;
return gcd(b, a % b);
}
private static long modExp(long a, long b) {
if (b == 0)
return 1;
a %= MOD;
long exp = modExp(a, b / 2);
if (b % 2 == 0) {
return (exp * exp) % MOD;
} else {
return (a * ((exp * exp) % MOD)) % MOD;
}
}
private long mul(int a, int b) {
return a * 1L * b;
}
// DSU
private static class DSU {
private int[] id;
private int[] size;
private int n;
public DSU(int n) {
this.n = n;
id = new int[n];
for (int i = 0; i < n; i++) {
id[i] = i;
}
size = new int[n];
Arrays.fill(size, 1);
}
private int root(int u) {
while (u != id[u]) {
id[u] = id[id[u]];
u = id[u];
}
return u;
}
public boolean connected(int u, int v) {
return root(u) == root(v);
}
public void union(int u, int v) {
int p = root(u);
int q = root(v);
if (size[p] >= size[q]) {
id[q] = p;
size[p] += size[q];
} else {
id[p] = q;
size[q] += size[p];
}
}
}
// KMP
private static int countSearch(String s, String p) {
int n = s.length();
int m = p.length();
int[] b = backTable(p);
int j = 0;
int count = 0;
for (int i = 0; i < n; i++) {
if (j == m) {
j = b[j - 1];
count++;
}
while (j != 0 && s.charAt(i) != p.charAt(j)) {
j = b[j - 1];
}
if (s.charAt(i) == p.charAt(j)) {
j++;
}
}
if (j == m)
count++;
return count;
}
private static int[] backTable(String p) {
int m = p.length();
int j = 0;
int[] b = new int[m];
for (int i = 1; i < m; i++) {
while (j != 0 && p.charAt(i) != p.charAt(j)) {
j = b[j - 1];
}
if (p.charAt(i) == p.charAt(j)) {
b[i] = ++j;
}
}
return b;
}
private static class LCA {
private HashMap<Integer, ArrayList<Integer>> g;
private int[] level;
private int[] a;
private int[][] P;
private int n, m;
private int[] xor;
public LCA(HashMap<Integer, ArrayList<Integer>> g, int[] a) {
this.g = g;
this.a = a;
n = g.size();
m = (int) (Math.log(n) / Math.log(2)) + 5;
P = new int[n][m];
xor = new int[n];
level = new int[n];
preprocess();
}
private void preprocess() {
dfs(0, -1);
for (int j = 1; j < m; j++) {
for (int i = 0; i < n; i++) {
if (P[i][j - 1] != -1) {
P[i][j] = P[P[i][j - 1]][j - 1];
}
}
}
}
private void dfs(int u, int p) {
P[u][0] = p;
xor[u] = a[u] ^ (p == -1 ? 0 : xor[p]);
level[u] = (p == -1 ? 0 : level[p] + 1);
for (int v : g.get(u)) {
if (v == p)
continue;
dfs(v, u);
}
}
public int lca(int u, int v) {
if (level[v] > level[u]) {
int temp = v;
v = u;
u = temp;
}
for (int j = m; j >= 0; j--) {
if (level[u] - (1 << j) < level[v]) {
continue;
} else {
u = P[u][j];
}
}
if (u == v)
return u;
for (int j = m - 1; j >= 0; j--) {
if (P[u][j] == -1 || P[u][j] == P[v][j]) {
continue;
} else {
u = P[u][j];
v = P[v][j];
}
}
return P[u][0];
}
private int xor(int u, int v) {
int l = lca(u, v);
return xor[u] ^ xor[v] ^ a[l];
}
}
// FAST INPUT OUTPUT LIBRARY
private static InputReader in = new InputReader(System.in);
private static PrintWriter out = new PrintWriter(System.out);
private static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(InputStream st) {
this.stream = st;
}
public int read() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
}
| Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 11 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | aa633a16b11dbf2f5e35aec0e6b131a3 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class SolutionD extends Thread {
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;
}
}
private static final FastReader scanner = new FastReader();
private static final PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) {
solve();
out.close();
}
static int n;
static class Query implements Comparable<Query> {
int l;
int r;
int index;
int bucket;
long result = 0;
public Query(int index, int l, int r) {
this.index = index;
this.l = l;
this.r = r;
bucket = l / (int) Math.sqrt(n);
}
@Override
public int compareTo(Query o) {
if (this.bucket == o.bucket) {
return this.r - o.r;
}
return this.bucket - o.bucket;
}
}
private static void solve() {
n = scanner.nextInt();
int q = scanner.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = scanner.nextInt();
}
Query[] queries = new Query[q];
for (int i = 0; i < q; i++) {
int l = scanner.nextInt() - 1;
int r = scanner.nextInt();
queries[i] = new Query(i, l, r);
if (n == 1) {
out.println(1);
}
}
if (n == 1) {
return;
}
Arrays.sort(queries);
int leftPointer = 0;
int rightPointer = 0;
int[] distr = new int[n+1];
for (Query query: queries) {
while (leftPointer > query.l) {
leftPointer--;
distr[a[leftPointer]]++;
}
while (rightPointer < query.r) {
distr[a[rightPointer]]++;
rightPointer++;
}
while (rightPointer > query.r) {
rightPointer--;
distr[a[rightPointer]]--;
}
while (leftPointer < query.l) {
distr[a[leftPointer]]--;
leftPointer++;
}
query.result = 1;
for (int it = 0; it <= 30; it++) {
int randomIndex = (int) (Math.random() * (rightPointer - leftPointer)) + leftPointer;
int amount = distr[a[randomIndex]];
if (amount > (rightPointer - leftPointer + 1) / 2) {
//5, 10 -> 1 of length 10 with 5 in each
//6, 10 -> 2 of length 5 with 3 in each
//7, 10 -> 4 of length 1,3,3,3 with 1,2,2,2 in each
//8, 10 -> 6 of length 1,1,1,1,3,3 with 1,1,1,1,2,2 in each
//9, 10 -> 8 of length 1,1,1,1,1,1,3 with 1,1,1,1,1,1,2 in each
//10, 10 -> 10 of length 1,1,1,1,1,1,1,1,1,1 with 1 in each
//10,21 -> 1
//11, 21 -> 1
//12, 21 -> 3 of length 3,3,15 with 2,2,8
//13, 21 -> 5 of length 3,3,3,3,9 with 2,2,2,2,5
//15, 21 -> 7 of length 3,3,3,3,3,3,3 with 2,2,2,2,2,2
//1
if ((rightPointer - leftPointer) % 2 == 1) {
query.result = (amount - ((rightPointer - leftPointer) / 2)) * 2L -1;
} else {
query.result = (amount - ((rightPointer - leftPointer) / 2)) * 2L;
}
break;
}
}
}
Arrays.sort(queries, Comparator.comparingLong(o -> o.index));
Arrays.stream(queries).forEach(query -> out.println(query.result));
}
} | Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 11 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | d4cd0838c826f784c883a312a8adb99a | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes |
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Random;
public final class D {
public static void main(String[] args) throws IOException {
final FastReader fs = new FastReader();
final StringBuilder sb = new StringBuilder();
final int n = fs.nextInt();
final int q = fs.nextInt();
final int[] arr = new int[n];
final int[][] edges = new int[n][2];
for (int i = 0; i < n; i++) {
arr[i] = fs.nextInt();
edges[i] = new int[] { arr[i], i };
}
final int[][] g = packG(edges, n + 1);
final Random rand = new Random();
for (int i = 0; i < q; i++) {
final int l = fs.nextInt() - 1;
final int r = fs.nextInt() - 1;
final int len = r - l + 1;
int max = 0;
for (int j = 0; j < 40; j++) {
final int curr = arr[l + rand.nextInt(len)];
final int[] list = g[curr];
final int ll = lowerBound(list, l);
final int rr = upperBound(list, r);
max = Math.max(max, rr - ll + 1);
}
sb.append(Math.max(1, (2 * max) - len));
sb.append('\n');
}
System.out.println(sb);
}
private static int[][] packG(int[][] edges, int n) {
final int[][] g = new int[n][];
final int[] size = new int[n];
final int[] idx = new int[n];
for (int[] edge : edges) {
++size[edge[0]];
}
for (int i = 0; i < n; i++) {
g[i] = new int[size[i]];
}
for (int[] edge : edges) {
g[edge[0]][idx[edge[0]]++] = edge[1];
}
return g;
}
private static int lowerBound(int[] l, int tar) {
int lo = 0, hi = l.length;
while (lo < hi) {
final int mid = lo + hi >>> 1;
if (l[mid] < tar) {
lo = mid + 1;
} else {
hi = mid;
}
}
return lo;
}
private static int upperBound(int[] l, int tar) {
int lo = 0, hi = l.length - 1;
while (lo < hi) {
final int mid = lo + hi + 1 >>> 1;
if (l[mid] > tar) {
hi = mid - 1;
} else {
lo = mid;
}
}
return lo;
}
static final class Utils {
private static class Shuffler {
private static void shuffle(int[] x) {
final Random r = new Random();
for (int i = 0; i <= x.length - 2; i++) {
final int j = i + r.nextInt(x.length - i);
swap(x, i, j);
}
}
private static void shuffle(long[] x) {
final Random r = new Random();
for (int i = 0; i <= x.length - 2; i++) {
final int j = i + r.nextInt(x.length - i);
swap(x, i, j);
}
}
private static void swap(int[] x, int i, int j) {
final int t = x[i];
x[i] = x[j];
x[j] = t;
}
private static void swap(long[] x, int i, int j) {
final long t = x[i];
x[i] = x[j];
x[j] = t;
}
}
public static void shuffleSort(int[] arr) {
Shuffler.shuffle(arr);
Arrays.sort(arr);
}
public static void shuffleSort(long[] arr) {
Shuffler.shuffle(arr);
Arrays.sort(arr);
}
private Utils() {}
}
static class FastReader {
private static final int BUFFER_SIZE = 1 << 16;
private final DataInputStream din;
private final byte[] buffer;
private int bufferPointer, bytesRead;
FastReader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
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 {
final byte[] buf = new byte[1024]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
break;
}
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextSign() throws IOException {
byte c = read();
while ('+' != c && '-' != c) {
c = read();
}
return '+' == c ? 0 : 1;
}
private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() throws IOException {
int b;
//noinspection StatementWithEmptyBody
while ((b = read()) != -1 && isSpaceChar(b)) {}
return b;
}
public char nc() throws IOException {
return (char) skip();
}
public String next() throws IOException {
int b = skip();
final StringBuilder sb = new StringBuilder();
while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = read();
}
return sb.toString();
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
final 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(); }
final 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(); }
final 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 {
din.close();
}
}
}
| Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 11 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | 7aac8f355fa0e5a5236e257bab27ffb7 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes |
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Random;
public final class D {
public static void main(String[] args) throws IOException {
final FastReader fs = new FastReader();
final StringBuilder sb = new StringBuilder();
final int n = fs.nextInt();
final int q = fs.nextInt();
final int[] arr = new int[n];
final int[][] edges = new int[n][2];
for (int i = 0; i < n; i++) {
arr[i] = fs.nextInt();
edges[i] = new int[] { arr[i], i };
}
final int[][] g = packG(edges, n + 1);
final Random rand = new Random();
for (int i = 0; i < q; i++) {
final int l = fs.nextInt() - 1;
final int r = fs.nextInt() - 1;
final int len = r - l + 1;
int max = 0;
for (int j = 0; j < 30; j++) {
final int curr = arr[l + rand.nextInt(len)];
final int[] list = g[curr];
final int ll = lowerBound(list, l);
final int rr = upperBound(list, r);
max = Math.max(max, rr - ll + 1);
}
sb.append(Math.max(1, (2 * max) - len));
sb.append('\n');
}
System.out.println(sb);
}
private static int[][] packG(int[][] edges, int n) {
final int[][] g = new int[n][];
final int[] size = new int[n];
final int[] idx = new int[n];
for (int[] edge : edges) {
++size[edge[0]];
}
for (int i = 0; i < n; i++) {
g[i] = new int[size[i]];
}
for (int[] edge : edges) {
g[edge[0]][idx[edge[0]]++] = edge[1];
}
return g;
}
private static int lowerBound(int[] l, int tar) {
int lo = 0, hi = l.length;
while (lo < hi) {
final int mid = lo + hi >>> 1;
if (l[mid] < tar) {
lo = mid + 1;
} else {
hi = mid;
}
}
return lo;
}
private static int upperBound(int[] l, int tar) {
int lo = 0, hi = l.length - 1;
while (lo < hi) {
final int mid = lo + hi + 1 >>> 1;
if (l[mid] > tar) {
hi = mid - 1;
} else {
lo = mid;
}
}
return lo;
}
static final class Utils {
private static class Shuffler {
private static void shuffle(int[] x) {
final Random r = new Random();
for (int i = 0; i <= x.length - 2; i++) {
final int j = i + r.nextInt(x.length - i);
swap(x, i, j);
}
}
private static void shuffle(long[] x) {
final Random r = new Random();
for (int i = 0; i <= x.length - 2; i++) {
final int j = i + r.nextInt(x.length - i);
swap(x, i, j);
}
}
private static void swap(int[] x, int i, int j) {
final int t = x[i];
x[i] = x[j];
x[j] = t;
}
private static void swap(long[] x, int i, int j) {
final long t = x[i];
x[i] = x[j];
x[j] = t;
}
}
public static void shuffleSort(int[] arr) {
Shuffler.shuffle(arr);
Arrays.sort(arr);
}
public static void shuffleSort(long[] arr) {
Shuffler.shuffle(arr);
Arrays.sort(arr);
}
private Utils() {}
}
static class FastReader {
private static final int BUFFER_SIZE = 1 << 16;
private final DataInputStream din;
private final byte[] buffer;
private int bufferPointer, bytesRead;
FastReader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
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 {
final byte[] buf = new byte[1024]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
break;
}
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextSign() throws IOException {
byte c = read();
while ('+' != c && '-' != c) {
c = read();
}
return '+' == c ? 0 : 1;
}
private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() throws IOException {
int b;
//noinspection StatementWithEmptyBody
while ((b = read()) != -1 && isSpaceChar(b)) {}
return b;
}
public char nc() throws IOException {
return (char) skip();
}
public String next() throws IOException {
int b = skip();
final StringBuilder sb = new StringBuilder();
while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = read();
}
return sb.toString();
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
final 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(); }
final 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(); }
final 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 {
din.close();
}
}
}
| Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 11 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | eddd2bbb9471f32296392fcee4401a5d | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.*;
public class Main {
private static int[] a;
private static Vector<Integer>[] indexSets;
private static void run() throws IOException {
int n = in.nextInt();
int q = in.nextInt();
a = new int[n + 1];
indexSets = new Vector[n + 1];
for (int i = 1; i <= n; i++) {
indexSets[i] = new Vector<>();
}
for (int i = 1; i <= n; i++) {
a[i] = in.nextInt();
Vector<Integer> now = indexSets[a[i]];
now.add(i);
}
int[] randoms = new int[40];
for (int i = 0; i < 40; i++) {
randoms[i] = ((int) (Math.random() * 3 * 1000000));
}
for (int i = 0; i < q; i++) {
int left = in.nextInt();
int right = in.nextInt();
int len = right - left + 1;
int ans = 1;
for (int t = 0; t < 25; t++) {
int test = randoms[t] % len + left;
ans = Math.max(ans, 2 * count(left, right, indexSets[a[test]]) - len);
if (ans != 1) break;
}
out.println(ans);
}
}
private static int count(int left, int right, Vector<Integer> arrayList) {
int left_pos = find(left, arrayList);
int right_pos = find(right, arrayList);
int size = arrayList.size();
while (left_pos < size && arrayList.get(left_pos) < left) left_pos++;
while (right_pos >= 0 && arrayList.get(right_pos) > right) right_pos--;
if (left_pos > right_pos) return 0;
return right_pos - left_pos + 1;
}
private static int find(int pos, Vector<Integer> arrayList) {
int left = 0;
int right = arrayList.size() - 1;
while (left < right) {
int mid = (left + right + 1) >> 1;
int mid_pos = arrayList.get(mid);
if (mid_pos > pos) {
right = mid - 1;
} else {
left = mid;
}
}
return right;
}
public static void main(String[] args) throws IOException {
in = new Reader();
out = new PrintWriter(new OutputStreamWriter(System.out));
// int t = in.nextInt();
// for (int i = 0; i < t; i++) {
// }
run();
out.flush();
in.close();
out.close();
}
private static int gcd(int a, int b) {
if (a == 0 || b == 0)
return 0;
while (b != 0) {
int tmp;
tmp = a % b;
a = b;
b = tmp;
}
return a;
}
static final long mod = 1000000007;
static long pow_mod(long a, long b) {
long result = 1;
while (b != 0) {
if ((b & 1) != 0) result = (result * a) % mod;
a = (a * a) % mod;
b >>= 1;
}
return result;
}
private static long multiplied_mod(long... longs) {
long ans = 1;
for (long now : longs) {
ans = (ans * now) % mod;
}
return ans;
}
@SuppressWarnings("FieldCanBeLocal")
private static Reader in;
private static PrintWriter out;
private static void print_array(int[] array) {
for (int now : array) {
out.print(now);
out.print(' ');
}
out.println();
}
private static void print_array(long[] array) {
for (long now : array) {
out.print(now);
out.print(' ');
}
out.println();
}
static class Reader {
private static final int BUFFER_SIZE = 1 << 16;
private final DataInputStream din;
private final byte[] buffer;
private int bufferPointer, bytesRead;
Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
final byte[] buf = new byte[1024]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
break;
}
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextSign() throws IOException {
byte c = read();
while ('+' != c && '-' != c) {
c = read();
}
return '+' == c ? 0 : 1;
}
private static boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
public int skip() throws IOException {
int b;
// noinspection ALL
while ((b = read()) != -1 && isSpaceChar(b)) {
;
}
return b;
}
public char nc() throws IOException {
return (char) skip();
}
public String next() throws IOException {
int b = skip();
final StringBuilder sb = new StringBuilder();
while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = read();
}
return sb.toString();
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
final 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();
}
final 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();
}
final 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 {
din.close();
}
}
} | Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 11 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | 75dc75330b189156c9b8f01d0863a1ed | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.*;
public class Main {
private static int[] a;
private static Vector<Integer>[] indexSets;
private static void run() throws IOException {
int n = in.nextInt();
int q = in.nextInt();
a = new int[n + 1];
indexSets = new Vector[n + 1];
for (int i = 1; i <= n; i++) {
indexSets[i] = new Vector<>();
}
for (int i = 1; i <= n; i++) {
a[i] = in.nextInt();
Vector<Integer> now = indexSets[a[i]];
now.add(i);
}
int[] randoms = new int[40];
for (int i = 0; i < 40; i++) {
randoms[i] = ((int) (Math.random() * 3 * 1000000));
}
for (int i = 0; i < q; i++) {
int left = in.nextInt();
int right = in.nextInt();
int len = right - left + 1;
int ans = 1;
for (int t = 0; t < 25; t++) {
int test = randoms[t] % len + left;
ans = Math.max(ans, 2 * count(left, right, indexSets[a[test]]) - len);
}
out.println(ans);
}
}
private static int count(int left, int right, Vector<Integer> arrayList) {
int left_pos = find(left, arrayList);
int right_pos = find(right, arrayList);
int size = arrayList.size();
while (left_pos < size && arrayList.get(left_pos) < left) left_pos++;
while (right_pos >= 0 && arrayList.get(right_pos) > right) right_pos--;
if (left_pos > right_pos) return 0;
return right_pos - left_pos + 1;
}
private static int find(int pos, Vector<Integer> arrayList) {
int left = 0;
int right = arrayList.size() - 1;
while (left < right) {
int mid = (left + right + 1) >> 1;
int mid_pos = arrayList.get(mid);
if (mid_pos > pos) {
right = mid - 1;
} else {
left = mid;
}
}
return right;
}
public static void main(String[] args) throws IOException {
in = new Reader();
out = new PrintWriter(new OutputStreamWriter(System.out));
// int t = in.nextInt();
// for (int i = 0; i < t; i++) {
// }
run();
out.flush();
in.close();
out.close();
}
private static int gcd(int a, int b) {
if (a == 0 || b == 0)
return 0;
while (b != 0) {
int tmp;
tmp = a % b;
a = b;
b = tmp;
}
return a;
}
static final long mod = 1000000007;
static long pow_mod(long a, long b) {
long result = 1;
while (b != 0) {
if ((b & 1) != 0) result = (result * a) % mod;
a = (a * a) % mod;
b >>= 1;
}
return result;
}
private static long multiplied_mod(long... longs) {
long ans = 1;
for (long now : longs) {
ans = (ans * now) % mod;
}
return ans;
}
@SuppressWarnings("FieldCanBeLocal")
private static Reader in;
private static PrintWriter out;
private static void print_array(int[] array) {
for (int now : array) {
out.print(now);
out.print(' ');
}
out.println();
}
private static void print_array(long[] array) {
for (long now : array) {
out.print(now);
out.print(' ');
}
out.println();
}
static class Reader {
private static final int BUFFER_SIZE = 1 << 16;
private final DataInputStream din;
private final byte[] buffer;
private int bufferPointer, bytesRead;
Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
final byte[] buf = new byte[1024]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
break;
}
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextSign() throws IOException {
byte c = read();
while ('+' != c && '-' != c) {
c = read();
}
return '+' == c ? 0 : 1;
}
private static boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
public int skip() throws IOException {
int b;
// noinspection ALL
while ((b = read()) != -1 && isSpaceChar(b)) {
;
}
return b;
}
public char nc() throws IOException {
return (char) skip();
}
public String next() throws IOException {
int b = skip();
final StringBuilder sb = new StringBuilder();
while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = read();
}
return sb.toString();
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
final 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();
}
final 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();
}
final 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 {
din.close();
}
}
} | Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 11 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | 0282cbb71548ddaf17601165d97f2bbe | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.*;
public class Main {
private static int[] a;
private static Vector<Integer>[] indexSets;
private static void run() throws IOException {
int n = in.nextInt();
int q = in.nextInt();
a = new int[n + 1];
indexSets = new Vector[n + 1];
for (int i = 1; i <= n; i++) {
indexSets[i] = new Vector<>();
}
for (int i = 1; i <= n; i++) {
a[i] = in.nextInt();
Vector<Integer> now = indexSets[a[i]];
now.add(i);
}
double[] randoms = new double[40];
for (int i = 0; i < 40; i++) {
randoms[i] = Math.random();
}
for (int i = 0; i < q; i++) {
int left = in.nextInt();
int right = in.nextInt();
int len = right - left + 1;
int ans = 1;
for (int t = 0; t < 25; t++) {
int test = ((int) (randoms[t] * 3 * 1000000)) % len + left;
ans = Math.max(ans, 2 * count(left, right, indexSets[a[test]]) - len);
}
out.println(ans);
}
}
private static int count(int left, int right, Vector<Integer> arrayList) {
int left_pos = find(left, arrayList);
int right_pos = find(right, arrayList);
int size = arrayList.size();
while (left_pos < size && arrayList.get(left_pos) < left) left_pos++;
while (right_pos >= 0 && arrayList.get(right_pos) > right) right_pos--;
if (left_pos > right_pos) return 0;
return right_pos - left_pos + 1;
}
private static int find(int pos, Vector<Integer> arrayList) {
int left = 0;
int right = arrayList.size() - 1;
while (left < right) {
int mid = (left + right + 1) >> 1;
int mid_pos = arrayList.get(mid);
if (mid_pos > pos) {
right = mid - 1;
} else {
left = mid;
}
}
return right;
}
public static void main(String[] args) throws IOException {
in = new Reader();
out = new PrintWriter(new OutputStreamWriter(System.out));
// int t = in.nextInt();
// for (int i = 0; i < t; i++) {
// }
run();
out.flush();
in.close();
out.close();
}
private static int gcd(int a, int b) {
if (a == 0 || b == 0)
return 0;
while (b != 0) {
int tmp;
tmp = a % b;
a = b;
b = tmp;
}
return a;
}
static final long mod = 1000000007;
static long pow_mod(long a, long b) {
long result = 1;
while (b != 0) {
if ((b & 1) != 0) result = (result * a) % mod;
a = (a * a) % mod;
b >>= 1;
}
return result;
}
private static long multiplied_mod(long... longs) {
long ans = 1;
for (long now : longs) {
ans = (ans * now) % mod;
}
return ans;
}
@SuppressWarnings("FieldCanBeLocal")
private static Reader in;
private static PrintWriter out;
private static void print_array(int[] array) {
for (int now : array) {
out.print(now);
out.print(' ');
}
out.println();
}
private static void print_array(long[] array) {
for (long now : array) {
out.print(now);
out.print(' ');
}
out.println();
}
static class Reader {
private static final int BUFFER_SIZE = 1 << 16;
private final DataInputStream din;
private final byte[] buffer;
private int bufferPointer, bytesRead;
Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
final byte[] buf = new byte[1024]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
break;
}
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextSign() throws IOException {
byte c = read();
while ('+' != c && '-' != c) {
c = read();
}
return '+' == c ? 0 : 1;
}
private static boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
public int skip() throws IOException {
int b;
// noinspection ALL
while ((b = read()) != -1 && isSpaceChar(b)) {
;
}
return b;
}
public char nc() throws IOException {
return (char) skip();
}
public String next() throws IOException {
int b = skip();
final StringBuilder sb = new StringBuilder();
while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = read();
}
return sb.toString();
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
final 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();
}
final 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();
}
final 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 {
din.close();
}
}
} | Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 11 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | 35c3c3141c3d1df131cb3f17f1eedaa7 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.*;
public class Main {
private static int[] a;
private static ArrayList<Integer>[] indexSets;
private static void run() throws IOException {
int n = in.nextInt();
int q = in.nextInt();
a = new int[n + 1];
indexSets = new ArrayList[n + 1];
for (int i = 1; i <= n; i++) {
indexSets[i] = new ArrayList<>();
}
for (int i = 1; i <= n; i++) {
a[i] = in.nextInt();
ArrayList<Integer> now = indexSets[a[i]];
now.add(i);
}
double[] randoms = new double[40];
for (int i = 0; i < 40; i++) {
randoms[i] = Math.random();
}
for (int i = 0; i < q; i++) {
int left = in.nextInt();
int right = in.nextInt();
int len = right - left + 1;
int ans = 1;
for (int t = 0; t < 25; t++) {
int test = ((int) (randoms[t] * 3 * 1000000)) % len + left;
ans = Math.max(ans, 2 * count(left, right, indexSets[a[test]]) - len);
}
out.println(ans);
}
}
private static int count(int left, int right, ArrayList<Integer> arrayList) {
int left_pos = find(left, arrayList);
int right_pos = find(right, arrayList);
int size = arrayList.size();
while (left_pos < size && arrayList.get(left_pos) < left) left_pos++;
while (right_pos >= 0 && arrayList.get(right_pos) > right) right_pos--;
if (left_pos > right_pos) return 0;
return right_pos - left_pos + 1;
}
private static int find(int pos, ArrayList<Integer> arrayList) {
int left = 0;
int right = arrayList.size() - 1;
while (left < right) {
int mid = (left + right + 1) >> 1;
int mid_pos = arrayList.get(mid);
if (mid_pos > pos) {
right = mid - 1;
} else {
left = mid;
}
}
return right;
}
public static void main(String[] args) throws IOException {
in = new Reader();
out = new PrintWriter(new OutputStreamWriter(System.out));
// int t = in.nextInt();
// for (int i = 0; i < t; i++) {
// }
run();
out.flush();
in.close();
out.close();
}
private static int gcd(int a, int b) {
if (a == 0 || b == 0)
return 0;
while (b != 0) {
int tmp;
tmp = a % b;
a = b;
b = tmp;
}
return a;
}
static final long mod = 1000000007;
static long pow_mod(long a, long b) {
long result = 1;
while (b != 0) {
if ((b & 1) != 0) result = (result * a) % mod;
a = (a * a) % mod;
b >>= 1;
}
return result;
}
private static long multiplied_mod(long... longs) {
long ans = 1;
for (long now : longs) {
ans = (ans * now) % mod;
}
return ans;
}
@SuppressWarnings("FieldCanBeLocal")
private static Reader in;
private static PrintWriter out;
private static void print_array(int[] array) {
for (int now : array) {
out.print(now);
out.print(' ');
}
out.println();
}
private static void print_array(long[] array) {
for (long now : array) {
out.print(now);
out.print(' ');
}
out.println();
}
static class Reader {
private static final int BUFFER_SIZE = 1 << 16;
private final DataInputStream din;
private final byte[] buffer;
private int bufferPointer, bytesRead;
Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
final byte[] buf = new byte[1024]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
break;
}
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextSign() throws IOException {
byte c = read();
while ('+' != c && '-' != c) {
c = read();
}
return '+' == c ? 0 : 1;
}
private static boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
public int skip() throws IOException {
int b;
// noinspection ALL
while ((b = read()) != -1 && isSpaceChar(b)) {
;
}
return b;
}
public char nc() throws IOException {
return (char) skip();
}
public String next() throws IOException {
int b = skip();
final StringBuilder sb = new StringBuilder();
while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = read();
}
return sb.toString();
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
final 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();
}
final 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();
}
final 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 {
din.close();
}
}
} | Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 11 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | a7871cda3adf84cded5778f57a713911 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | // practice with kaiboy, coached by rainboy
import java.io.*;
import java.util.*;
public class CF1514D extends PrintWriter {
CF1514D() { super(System.out); }
static class Scanner {
Scanner(InputStream in) { this.in = in; } InputStream in;
byte[] bb = new byte[1 << 15]; int i, n;
byte getc() {
if (i == n) {
i = n = 0;
try { n = in.read(bb); } catch (IOException e) {}
}
return i < n ? bb[i++] : 0;
}
int nextInt() {
byte c = 0; while (c <= ' ') c = getc();
int a = 0; while (c > ' ') { a = a * 10 + c - '0'; c = getc(); }
return a;
}
}
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF1514D o = new CF1514D(); o.main(); o.flush();
}
int[] eo; int[][] ej;
void append(int i, int j) {
int o = eo[i]++;
if (o >= 2 && (o & o - 1) == 0)
ej[i] = Arrays.copyOf(ej[i], o << 1);
ej[i][o] = j;
}
int count(int[] aa, int n, int a) {
int lower = -1, upper = n;
while (upper - lower > 1) {
int i = (lower + upper) / 2;
if (aa[i] <= a)
lower = i;
else
upper = i;
}
return upper;
}
int count(int[] aa, int n, int l, int r) {
return count(aa, n, r) - count(aa, n, l - 1);
}
int[] st, kk; int n;
void pul(int i) {
int l = i << 1, r = l | 1;
if (st[l] == st[r]) {
st[i] = st[l];
kk[i] = kk[l] + kk[r];
} else {
if (kk[l] < kk[r]) {
int tmp = l; l = r; r = tmp;
}
st[i] = st[l];
kk[i] = kk[l] - kk[r];
}
}
void build(int[] aa) {
for (int i = 0; i < n; i++) {
st[n + i] = aa[i];
kk[n + i] = 1;
}
for (int i = n - 1; i > 0; i--)
pul(i);
}
int query(int l, int r) {
int a = 0, k = 0;
for (l += n, r += n; l <= r; l >>= 1, r >>= 1) {
if ((l & 1) == 1) {
if (a == st[l])
k += kk[l];
else if (k >= kk[l])
k -= kk[l];
else {
a = st[l];
k = kk[l] - k;
}
l++;
}
if ((r & 1) == 0) {
if (a == st[r])
k += kk[r];
else if (k >= kk[r])
k -= kk[r];
else {
a = st[r];
k = kk[r] - k;
}
r--;
}
}
return a;
}
void main() {
n = sc.nextInt();
int q = sc.nextInt();
int[] aa = new int[n];
eo = new int[n + 1]; ej = new int[n + 1][2];
for (int i = 0; i < n; i++) {
int a = sc.nextInt();
aa[i] = a;
append(a, i);
}
st = new int[n * 2]; kk = new int[n * 2];
build(aa);
while (q-- > 0) {
int l = sc.nextInt() - 1;
int r = sc.nextInt() - 1;
int m = r - l + 1;
int a = query(l, r);
int k = count(ej[a], eo[a], l, r);
println(k + k > m ? k + k - m : 1);
}
}
}
| Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 11 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | a67a181a164fa351522b88237b5afc00 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | // practice with kaiboy
import java.io.*;
import java.util.*;
public class CF1514D extends PrintWriter {
CF1514D() { super(System.out); }
static class Scanner {
Scanner(InputStream in) { this.in = in; } InputStream in;
byte[] bb = new byte[1 << 15]; int i, n;
byte getc() {
if (i == n) {
i = n = 0;
try { n = in.read(bb); } catch (IOException e) {}
}
return i < n ? bb[i++] : 0;
}
int nextInt() {
byte c = 0; while (c <= ' ') c = getc();
int a = 0; while (c > ' ') { a = a * 10 + c - '0'; c = getc(); }
return a;
}
}
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF1514D o = new CF1514D(); o.main(); o.flush();
}
int[] eo; int[][] ej;
void append(int i, int j) {
int o = eo[i]++;
if (o >= 2 && (o & o - 1) == 0)
ej[i] = Arrays.copyOf(ej[i], o << 1);
ej[i][o] = j;
}
int count(int[] aa, int n, int a) {
int lower = -1, upper = n;
while (upper - lower > 1) {
int i = (lower + upper) / 2;
if (aa[i] <= a)
lower = i;
else
upper = i;
}
return upper;
}
int count(int[] aa, int n, int l, int r) {
return count(aa, n, r - 1) - count(aa, n, l - 1);
}
void main() {
int n = sc.nextInt();
int q = sc.nextInt();
int[] aa = new int[n];
eo = new int[n + 1]; ej = new int[n + 1][2];
for (int i = 0; i < n; i++) {
int a = sc.nextInt();
aa[i] = a;
append(a, i);
}
Random rand = new Random();
int[] kk = new int[n + 1];
Integer[] qu = new Integer[n];
while (q-- > 0) {
int l = sc.nextInt() - 1;
int r = sc.nextInt();
int m = r - l;
int cnt = 0;
for (int h = 0; h < 60; h++) {
int i = l + rand.nextInt(r - l);
int a = aa[i];
if (kk[a]++ == 0)
qu[cnt++] = a;
}
Arrays.sort(qu, 0, cnt, (a, b) -> kk[b] - kk[a]);
int ans = 1;
for (int h = 0, a; h < cnt && kk[a = qu[h]] > 10; h++) {
int k = count(ej[a], eo[a], l, r);
if (k + k > m) {
ans = k + k - m;
break;
}
}
println(ans);
for (int h = 0; h < cnt; h++) {
int a = qu[h];
kk[a] = 0;
}
}
}
}
| Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 11 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | fa13d6c121af53239225a0dafebaa4bb | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | // practice with kaiboy
import java.io.*;
import java.util.*;
public class CF1514D extends PrintWriter {
CF1514D() { super(System.out); }
static class Scanner {
Scanner(InputStream in) { this.in = in; } InputStream in;
byte[] bb = new byte[1 << 15]; int i, n;
byte getc() {
if (i == n) {
i = n = 0;
try { n = in.read(bb); } catch (IOException e) {}
}
return i < n ? bb[i++] : 0;
}
int nextInt() {
byte c = 0; while (c <= ' ') c = getc();
int a = 0; while (c > ' ') { a = a * 10 + c - '0'; c = getc(); }
return a;
}
}
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF1514D o = new CF1514D(); o.main(); o.flush();
}
int[] eo; int[][] ej;
void append(int i, int j) {
int o = eo[i]++;
if (o >= 2 && (o & o - 1) == 0)
ej[i] = Arrays.copyOf(ej[i], o << 1);
ej[i][o] = j;
}
int count(int[] aa, int n, int a) {
int lower = -1, upper = n;
while (upper - lower > 1) {
int i = (lower + upper) / 2;
if (aa[i] <= a)
lower = i;
else
upper = i;
}
return upper;
}
int count(int[] aa, int n, int l, int r) {
return count(aa, n, r - 1) - count(aa, n, l - 1);
}
void main() {
int n = sc.nextInt();
int q = sc.nextInt();
int[] aa = new int[n];
eo = new int[n + 1]; ej = new int[n + 1][2];
for (int i = 0; i < n; i++) {
int a = sc.nextInt();
aa[i] = a;
append(a, i);
}
Random rand = new Random();
int[] kk = new int[n + 1];
Integer[] qu = new Integer[n];
while (q-- > 0) {
int l = sc.nextInt() - 1;
int r = sc.nextInt();
int m = r - l;
int cnt = 0;
for (int h = 0; h < 100; h++) {
int i = l + rand.nextInt(r - l);
int a = aa[i];
if (kk[a]++ == 0)
qu[cnt++] = a;
}
Arrays.sort(qu, 0, cnt, (a, b) -> kk[b] - kk[a]);
int ans = 1;
for (int h = 0, a; h < cnt && kk[a = qu[h]] > 10; h++) {
int k = count(ej[a], eo[a], l, r);
if (k + k > m) {
ans = k + k - m;
break;
}
}
println(ans);
for (int h = 0; h < cnt; h++) {
int a = qu[h];
kk[a] = 0;
}
}
}
}
| Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 11 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | a535fba9f863a832cc54bc8c3a80c467 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | // practice with kaiboy
import java.io.*;
import java.util.*;
public class CF1514D extends PrintWriter {
CF1514D() { super(System.out); }
static class Scanner {
Scanner(InputStream in) { this.in = in; } InputStream in;
byte[] bb = new byte[1 << 15]; int i, n;
byte getc() {
if (i == n) {
i = n = 0;
try { n = in.read(bb); } catch (IOException e) {}
}
return i < n ? bb[i++] : 0;
}
int nextInt() {
byte c = 0; while (c <= ' ') c = getc();
int a = 0; while (c > ' ') { a = a * 10 + c - '0'; c = getc(); }
return a;
}
}
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF1514D o = new CF1514D(); o.main(); o.flush();
}
int[] eo; int[][] ej;
void append(int i, int j) {
int o = eo[i]++;
if (o >= 2 && (o & o - 1) == 0)
ej[i] = Arrays.copyOf(ej[i], o << 1);
ej[i][o] = j;
}
int count(int[] aa, int n, int a) {
int lower = -1, upper = n;
while (upper - lower > 1) {
int i = (lower + upper) / 2;
if (aa[i] <= a)
lower = i;
else
upper = i;
}
return upper;
}
int count(int[] aa, int n, int l, int r) {
return count(aa, n, r - 1) - count(aa, n, l - 1);
}
void main() {
int n = sc.nextInt();
int q = sc.nextInt();
int[] aa = new int[n];
eo = new int[n + 1]; ej = new int[n + 1][2];
for (int i = 0; i < n; i++) {
int a = sc.nextInt();
aa[i] = a;
append(a, i);
}
Random rand = new Random();
int[] kk = new int[n + 1];
int[] qu = new int[n];
while (q-- > 0) {
int l = sc.nextInt() - 1;
int r = sc.nextInt();
int m = r - l;
int cnt = 0;
for (int h = 0; h < 100; h++) {
int i = l + rand.nextInt(r - l);
int a = aa[i];
if (kk[a]++ == 0)
qu[cnt++] = a;
}
int ans = 1;
for (int h = 0; h < cnt; h++) {
int a = qu[h];
if (kk[a] > 10) {
int k = count(ej[a], eo[a], l, r);
if (k + k > m) {
ans = k + k - m;
break;
}
}
}
println(ans);
for (int h = 0; h < cnt; h++) {
int a = qu[h];
kk[a] = 0;
}
}
}
}
| Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 11 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | a687be8939f17f4cdf47aacc2d35d661 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | import java.io.*;
import java.util.*;
public class CF1514D extends PrintWriter {
CF1514D() { super(System.out); }
static class Scanner {
Scanner(InputStream in) { this.in = in; } InputStream in;
byte[] bb = new byte[1 << 15]; int i, n;
byte getc() {
if (i == n) {
i = n = 0;
try { n = in.read(bb); } catch (IOException e) {}
}
return i < n ? bb[i++] : 0;
}
int nextInt() {
byte c = 0; while (c <= ' ') c = getc();
int a = 0; while (c > ' ') { a = a * 10 + c - '0'; c = getc(); }
return a;
}
}
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF1514D o = new CF1514D(); o.main(); o.flush();
}
int count(int[] aa, int n, int a) {
int lower = -1, upper = n;
while (upper - lower > 1) {
int i = (lower + upper) / 2;
if (aa[i] <= a)
lower = i;
else
upper = i;
}
return upper;
}
int count(int[] aa, int n, int a, int b) {
return count(aa, n, b - 1) - count(aa, n, a - 1);
}
int[] aa, a1, a2, a3;
int[] kk;
int[] eo; int[][] ej;
void append(int i, int j) {
int o = eo[i]++;
if (o >= 2 && (o & o - 1) == 0)
ej[i] = Arrays.copyOf(ej[i], o << 1);
ej[i][o] = j;
}
void build(int h, int l, int r) {
if (r - l == 1) {
a1[h] = aa[l];
return;
}
int k = (r - l) / 4;
for (int i = l; i < r; i++) {
int a = aa[i];
if (a == 0)
continue;
if (++kk[a] <= k)
continue;
if (a1[h] == 0) {
a1[h] = a;
continue;
}
if (a1[h] == a)
continue;
if (a2[h] == 0) {
a2[h] = a;
continue;
}
if (a2[h] == a)
continue;
if (a3[h] == 0) {
a3[h] = a;
continue;
}
}
for (int i = l; i < r; i++) {
int a = aa[i];
kk[a] = 0;
}
int m = (l + r) / 2;
build(h << 1, l, m);
build(h << 1 | 1, m, r);
}
int queryl(int h, int l, int r, int ql, int qr) {
if (r - l == 1)
return h;
int m = (l + r) / 2;
if (qr <= m)
return queryl(h << 1, l, m, ql, qr);
if (m <= ql)
return queryl(h << 1 | 1, m, r, ql, qr);
r = m;
h = h << 1;
while (r - l > 1 && (m = (l + r) / 2) <= ql) {
l = m;
h = h << 1 | 1;
}
return h;
}
int queryr(int h, int l, int r, int ql, int qr) {
if (r - l == 1)
return h;
int m = (l + r) / 2;
if (qr <= m)
return queryr(h << 1, l, m, ql, qr);
if (m <= ql)
return queryr(h << 1 | 1, m, r, ql, qr);
l = m;
h = h << 1 | 1;
while (r - l > 1 && qr <= (m = (l + r) / 2)) {
r = m;
h = h << 1;
}
return h;
}
void main() {
int n = sc.nextInt();
int q = sc.nextInt();
int n_ = 1;
while (n_ < n)
n_ <<= 1;
aa = new int[n_];
a1 = new int[n_ * 2]; a2 = new int[n_ * 2]; a3 = new int[n_ * 2];
kk = new int[n + 1];
eo = new int[n + 1]; ej = new int[n + 1][2];
for (int i = 0; i < n; i++) {
int a = sc.nextInt();
aa[i] = a;
append(a, i);
}
build(1, 0, n_);
while (q-- > 0) {
int l = sc.nextInt() - 1;
int r = sc.nextInt();
int a, c, m = r - l, k = (m + 1) / 2;
int h = queryl(1, 0, n_, l, r);
if ((a = a1[h]) > 0 && (c = count(ej[a], eo[a], l, r)) > k) {
println(c + c - m);
continue;
}
if ((a = a2[h]) > 0 && (c = count(ej[a], eo[a], l, r)) > k) {
println(c + c - m);
continue;
}
if ((a = a3[h]) > 0 && (c = count(ej[a], eo[a], l, r)) > k) {
println(c + c - m);
continue;
}
h = queryr(1, 0, n_, l, r);
if ((a = a1[h]) > 0 && (c = count(ej[a], eo[a], l, r)) > k) {
println(c + c - m);
continue;
}
if ((a = a2[h]) > 0 && (c = count(ej[a], eo[a], l, r)) > k) {
println(c + c - m);
continue;
}
if ((a = a3[h]) > 0 && (c = count(ej[a], eo[a], l, r)) > k) {
println(c + c - m);
continue;
}
println(1);
}
}
}
| Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 11 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | be67477069abae4e69906ce5f5485437 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes |
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.util.Random;
import java.util.*;
public class CutAnsStick implements Runnable {
int[][] counts;
// Use Randomized Algo (Time Complexity[nLog(n) + Q(Log(n)^2)]
void solve() throws IOException {
int n = ri(), q = ri();
int[] arr = iArr(n);
counts = new int[n][];
int[] total = iArr(n);
for (int i = 0; i < n; i++) {
arr[i] = ri() - 1;
total[arr[i]]++;
}
for (int i = 0; i < n; i++) {
if (total[i] > 0) {
counts[i] = new int[total[i]];
}
}
for (int i = 0; i < n; i++) {
int curr = arr[i];
counts[curr][total[curr] - 1] = i;
total[curr]--;
}
for (int i = 0; i < n; i++) {
if (counts[i] != null) {
Arrays.sort(counts[i]);
}
}
while (q-- > 0) {
int l = ri() - 1, r = ri() - 1;
// Get 30 random numbers
Set<Integer> set = new HashSet<>();
for (int i = 0; i < 30; i++) {
set.add(arr[getRandom(l, r)]);
}
// Check the count of each element and find max
int max = 1;
for (int ele : set) {
int[] curr = counts[ele];
int count = upperBound(curr, r) - lowerBound(curr, l);
max = max(max, count);
}
int wid = r - l + 1;
int ans = 0;
int start = 0, end = max;
while (start <= end) {
int mid = (start + end) >> 1; // The number of partitions
int rem = wid - mid;
int leftOver = max - mid;
int allowed = (rem + 1) / 2;
if (allowed >= leftOver) {
ans = mid;
end = mid - 1;
} else
start = mid + 1;
}
ans++;
// Answer is just really max(max - (width - max), 1)
sbr.append(ans).append("\n");
}
print(sbr.toString());
}
int lowerBound(int[] arr, int val) {
int l = -1, r = arr.length;
while (l + 1 < r) {
int mid = (r + l) >> 1;
if (arr[mid] >= val)
r = mid;
else
l = mid;
}
return r;
}
int upperBound(int[] arr, int val) {
int l = -1, r = arr.length;
while (l + 1 < r) {
int mid = (r + l) >> 1;
if (arr[mid] <= val) {
l = mid;
} else {
r = mid;
}
}
return l + 1;
}
/************************************************************************************************************************************************/
// Time Complexity [ O( (N + Q) Sqrt(N) ) ]
void solveMoAlgo() throws IOException {
int n = ri(), q = ri();
int[] arr = iArr(n);
Query[] queries = new Query[q];
for (int i = 0; i < n; i++) {
arr[i] = ri();
}
for (int i = 0; i < q; i++) {
queries[i] = new Query(ri() - 1, ri(), i);
}
int sqr = (int) Math.sqrt(q);
// Sort the queries
Arrays.sort(queries, (o1, o2) -> {
if (o1.l / sqr != o2.l / sqr)
return Integer.compare(o1.l / sqr, o2.l / sqr);
// To make it even more faster
// If div by block is odd then sort the right index in ascending order
// else descending order
if ((o1.l / sqr & 1) == 1)
return Integer.compare(o1.r, o2.r);
return Integer.compare(o2.r, o1.r);
});
int leftPointer = 0, rightPointer = 0;
int[] counts = iArr(n + 1);
for (Query query : queries) {
int l = query.l, r = query.r;
while (leftPointer > query.l) {
leftPointer--;
counts[arr[leftPointer]]++;
}
while (rightPointer < query.r) {
counts[arr[rightPointer]]++;
rightPointer++;
}
while (rightPointer > query.r) {
rightPointer--;
counts[arr[rightPointer]]--;
}
while (leftPointer < query.l) {
counts[arr[leftPointer]]--;
leftPointer++;
}
// Choose 30 random numbers and find max frequency
int maxFreq = 1;
for (int i = 0; i < 30; i++) {
maxFreq = max(maxFreq, counts[arr[getRandom(l, r - 1)]]);
}
query.res = max(1, maxFreq - (r - l - maxFreq));
}
int[] ans = iArr(q);
for (Query qu : queries) {
ans[qu.index] = qu.res;
}
Arrays.stream(ans).forEach(o -> sbr.append(o).append("\n"));
println(sbr.toString());
}
class Query {
int l, r, index, res = 1;
public Query(int l, int r, int i) {
this.l = l;
this.r = r;
this.index = i;
}
}
/************************************************************************************************************************************************/
int[] arr;
//Time complexity [ O(n) + O(Q * (Log(n)) ^ 2)]
void solveSegmentTree() throws IOException {
int n = ri(), q = ri();
int[] total = iArr(n + 1);
arr = iArr(n);
for (int i = 0; i < n; i++) {
arr[i] = ri();
total[arr[i]]++;
}
counts = new int[n + 1][];
for (int i = 1; i < total.length; i++) {
if (total[i] != 0) {
counts[i] = new int[total[i]];
}
}
for (int i = 0; i < n; i++) {
counts[arr[i]][total[arr[i]] - 1] = i;
total[arr[i]]--;
}
for (int[] count : counts) {
if (count != null)
Arrays.sort(count);
}
Seg seg = new Seg(arr);
while (q-- > 0) {
int l = ri() - 1, r = ri() - 1;
int wid = r - l + 1;
int max = seg.query(l, r, 0, n - 1, 0);
sbr.append(max(1, max - (wid - max))).append("\n");
}
print(sbr.toString());
}
int count(int l, int r, int val) {
if(counts[val] == null) return -1;
int up = upperBoundSeg(counts[val], r);
int low = lowerBoundSeg(counts[val], l);
return up - low + 1;
}
int lowerBoundSeg(int[] arr, int val) {
int l = 0, r = arr.length - 1;
while (l < r) {
int mid = (r + l) >> 1;
if (arr[mid] >= val) {
r = mid;
} else
l = mid + 1;
}
return l;
}
int upperBoundSeg(int[] arr, int val) {
int l = 0, r = arr.length - 1;
while (l < r) {
int mid = (r + l + 1) >> 1;
if (arr[mid] <= val) {
l = mid;
} else
r = mid - 1;
}
return l;
}
class Seg {
int[] tree;
int[] arr;
public Seg(int[] arr) {
this.arr = arr;
tree = new int[(getSize(arr.length) * 2 + 1)];
build(0, arr.length - 1, 0);
}
void build(int l, int r, int pos) {
if (l == r) {
tree[pos] = arr[l];
} else {
int mid = l + (r - l)/2;
int p = pos * 2;
build(l, mid, p + 1);
build(mid + 1, r, p + 2);
tree[pos] = (count(l, r, tree[p + 1]) > count(l, r, tree[p + 2])) ? tree[p + 1] : tree[p + 2];
}
}
int query(int l, int r, int start, int end, int pos) {
if (start > r || end < l)
return 0;
if (start >= l && end <= r) {
return count(l, r, tree[pos]);
} else {
int mid = (start + end) >> 1;
pos <<= 1;
return max(query(l, r, start, mid, pos + 1), query(l, r, mid + 1, end, pos + 2));
}
}
int getSize(int len) {
if (len < 2) return 1;
if ((len & (len - 1)) == 0) return len;
while ((len & (len - 1)) != 0) {
len = len & (len - 1);
}
return len << 1;
}
}
/************************************************************************************************************************************************/
public static void main(String[] args) throws IOException {
new Thread(null, new CutAnsStick(), "1").start();
}
static PrintWriter out = new PrintWriter(System.out);
static Reader read = new Reader();
static StringBuilder sbr = new StringBuilder();
static int mod = (int) 1e9 + 7;
static int dmax = Integer.MAX_VALUE;
static long lmax = Long.MAX_VALUE;
static int dmin = Integer.MIN_VALUE;
static long lmin = Long.MIN_VALUE;
@Override
public void run() {
try {
// solve();
// solveMoAlgo();
solveSegmentTree();
out.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
static class Reader {
private byte[] buf = new byte[1024];
private int index;
private InputStream in;
private int total;
public Reader() {
in = System.in;
}
public int scan() throws IOException {
if (total < 0)
throw new InputMismatchException();
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0)
return -1;
}
return buf[index++];
}
public int intNext() throws IOException {
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 doubleNext() throws IOException {
double doub = 0;
int n = scan();
while (isWhiteSpace(n))
n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n) && n != '.') {
if (n >= '0' && n <= '9') {
doub *= 10;
doub += n - '0';
n = scan();
} else
throw new InputMismatchException();
}
if (n == '.') {
n = scan();
double temp = 1;
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
temp /= 10;
doub += (n - '0') * temp;
n = scan();
} else
throw new InputMismatchException();
}
}
return doub * neg;
}
public String read() throws IOException {
StringBuilder sb = new StringBuilder();
int n = scan();
while (isWhiteSpace(n))
n = scan();
while (!isWhiteSpace(n)) {
sb.append((char) n);
n = scan();
}
return sb.toString();
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1)
return true;
return false;
}
}
static void shuffle(int[] aa) {
int n = aa.length;
Random rand = new Random();
for (int i = 1; i < n; i++) {
int j = rand.nextInt(i + 1);
int tmp = aa[i];
aa[i] = aa[j];
aa[j] = tmp;
}
}
static void shuffle(int[][] aa) {
int n = aa.length;
Random rand = new Random();
for (int i = 1; i < n; i++) {
int j = rand.nextInt(i + 1);
int first = aa[i][0];
int second = aa[i][1];
aa[i][0] = aa[j][0];
aa[i][1] = aa[j][1];
aa[j][0] = first;
aa[j][1] = second;
}
}
static void print(Object object) {
out.print(object);
}
static void println(Object object) {
out.println(object);
}
static int[] iArr(int len) {
return new int[len];
}
static long[] lArr(int len) {
return new long[len];
}
static long min(long a, long b) {
return Math.min(a, b);
}
static int min(int a, int b) {
return Math.min(a, b);
}
static long max(Long a, Long b) {
return Math.max(a, b);
}
static int max(int a, int b) {
return Math.max(a, b);
}
static int ri() throws IOException {
return read.intNext();
}
static long rl() throws IOException {
return Long.parseLong(read.read());
}
static String rs() throws IOException {
return read.read();
}
static char rc() throws IOException {
return rs().charAt(0);
}
static double rd() throws IOException {
return read.doubleNext();
}
static int getRandom(int l, int r) {
return l + (int) (Math.random() * (r - l + 1));
}
static int lowerbound(ArrayList<Integer> arr, int target) {
int l = 0;
int r = arr.size() - 1;
int mid;
while (l < r) {
mid = (l + r) >> 1;
if (arr.get(mid) >= target)
r = mid;
else
l = mid + 1;
}
return l;
}
static int upperbound(ArrayList<Integer> arr, int target) {
int l = 0;
int r = arr.size() - 1;
int mid;
while (l < r) {
mid = (l + r + 1) >> 1;
if (arr.get(mid) > target)
r = mid - 1;
else
l = mid;
}
return l;
}
}
| Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 11 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | 461a0663b923f26b8c453c2bb7338bd9 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes |
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.util.Random;
import java.util.*;
public class CutAnsStick implements Runnable {
int[][] counts;
// Use Randomized Algo (Time Complexity[nLog(n) + Q(Log(n)^2)]
void solve() throws IOException {
int n = ri(), q = ri();
int[] arr = iArr(n);
counts = new int[n][];
int[] total = iArr(n);
for (int i = 0; i < n; i++) {
arr[i] = ri() - 1;
total[arr[i]]++;
}
for (int i = 0; i < n; i++) {
if (total[i] > 0) {
counts[i] = new int[total[i]];
}
}
for (int i = 0; i < n; i++) {
int curr = arr[i];
counts[curr][total[curr] - 1] = i;
total[curr]--;
}
for (int i = 0; i < n; i++) {
if (counts[i] != null) {
Arrays.sort(counts[i]);
}
}
while (q-- > 0) {
int l = ri() - 1, r = ri() - 1;
// Get 30 random numbers
Set<Integer> set = new HashSet<>();
for (int i = 0; i < 30; i++) {
set.add(arr[getRandom(l, r)]);
}
// Check the count of each element and find max
int max = 1;
for (int ele : set) {
int[] curr = counts[ele];
int count = upperBound(curr, r) - lowerBound(curr, l);
max = max(max, count);
}
int wid = r - l + 1;
int ans = 0;
int start = 0, end = max;
while (start <= end) {
int mid = (start + end) >> 1; // The number of partitions
int rem = wid - mid;
int leftOver = max - mid;
int allowed = (rem + 1) / 2;
if (allowed >= leftOver) {
ans = mid;
end = mid - 1;
} else
start = mid + 1;
}
ans++;
// Answer is just really max(max - (width - max), 1)
sbr.append(ans).append("\n");
}
print(sbr.toString());
}
int lowerBound(int[] arr, int val) {
int l = -1, r = arr.length;
while (l + 1 < r) {
int mid = (r + l) >> 1;
if (arr[mid] >= val)
r = mid;
else
l = mid;
}
return r;
}
int upperBound(int[] arr, int val) {
int l = -1, r = arr.length;
while (l + 1 < r) {
int mid = (r + l) >> 1;
if (arr[mid] <= val) {
l = mid;
} else {
r = mid;
}
}
return l + 1;
}
/************************************************************************************************************************************************/
// Time Complexity [ O( (N + Q) Sqrt(N) ) ]
void solveMoAlgo() throws IOException {
int n = ri(), q = ri();
int[] arr = iArr(n);
Query[] queries = new Query[q];
for (int i = 0; i < n; i++) {
arr[i] = ri();
}
for (int i = 0; i < q; i++) {
queries[i] = new Query(ri() - 1, ri(), i);
}
int sqr = (int) Math.sqrt(q);
// Sort the queries
Arrays.sort(queries, (o1, o2) -> {
if (o1.l / sqr != o2.l / sqr)
return Integer.compare(o1.l / sqr, o2.l / sqr);
// To make it even more faster
// If div by block is odd then sort the right index in ascending order
// else descending order
if ((o1.l / sqr & 1) == 1)
return Integer.compare(o1.r, o2.r);
return Integer.compare(o2.r, o1.r);
});
int leftPointer = 0, rightPointer = 0;
int[] counts = iArr(n + 1);
for (Query query : queries) {
int l = query.l, r = query.r;
while (leftPointer > query.l) {
leftPointer--;
counts[arr[leftPointer]]++;
}
while (rightPointer < query.r) {
counts[arr[rightPointer]]++;
rightPointer++;
}
while (rightPointer > query.r) {
rightPointer--;
counts[arr[rightPointer]]--;
}
while (leftPointer < query.l) {
counts[arr[leftPointer]]--;
leftPointer++;
}
// Choose 30 random numbers and find max frequency
int maxFreq = 1;
for (int i = 0; i < 30; i++) {
maxFreq = max(maxFreq, counts[arr[getRandom(l, r - 1)]]);
}
query.res = max(1, maxFreq - (r - l - maxFreq));
}
int[] ans = iArr(q);
for (Query qu : queries) {
ans[qu.index] = qu.res;
}
Arrays.stream(ans).forEach(o -> sbr.append(o).append("\n"));
println(sbr.toString());
}
class Query {
int l, r, index, res = 1;
public Query(int l, int r, int i) {
this.l = l;
this.r = r;
this.index = i;
}
}
/************************************************************************************************************************************************/
int[] arr;
void solveSegmentTree() throws IOException {
int n = ri(), q = ri();
int[] total = iArr(n + 1);
arr = iArr(n);
for (int i = 0; i < n; i++) {
arr[i] = ri();
total[arr[i]]++;
}
counts = new int[n + 1][];
for (int i = 1; i < total.length; i++) {
if (total[i] != 0) {
counts[i] = new int[total[i]];
}
}
for (int i = 0; i < n; i++) {
counts[arr[i]][total[arr[i]] - 1] = i;
total[arr[i]]--;
}
for (int[] count : counts) {
if (count != null)
Arrays.sort(count);
}
Seg seg = new Seg(arr);
while (q-- > 0) {
int l = ri() - 1, r = ri() - 1;
int wid = r - l + 1;
int max = seg.query(l, r, 0, n - 1, 0);
sbr.append(max(1, max - (wid - max))).append("\n");
}
print(sbr.toString());
}
int count(int l, int r, int val) {
if(counts[val] == null) return -1;
int up = upperBound(counts[val], r);
int low = lowerBound(counts[val], l);
return up - low;
}
class Seg {
int[] tree;
int[] arr;
public Seg(int[] arr) {
this.arr = arr;
tree = new int[(getSize(arr.length) * 2 + 1)];
build(0, arr.length - 1, 0);
}
void build(int l, int r, int pos) {
if (l == r) {
tree[pos] = arr[l];
} else {
int mid = l + (r - l)/2;
int p = pos * 2;
build(l, mid, p + 1);
build(mid + 1, r, p + 2);
tree[pos] = (count(l, r, tree[p + 1]) > count(l, r, tree[p + 2])) ? tree[p + 1] : tree[p + 2];
}
}
int query(int l, int r, int start, int end, int pos) {
if (start > r || end < l)
return 0;
if (start >= l && end <= r) {
return count(l, r, tree[pos]);
} else {
int mid = (start + end) >> 1;
pos <<= 1;
return max(query(l, r, start, mid, pos + 1), query(l, r, mid + 1, end, pos + 2));
}
}
int getSize(int len) {
if (len < 2) return 1;
if ((len & (len - 1)) == 0) return len;
while ((len & (len - 1)) != 0) {
len = len & (len - 1);
}
return len << 1;
}
}
int lowerBoundSeg(int[] arr, int val) {
int l = 0, r = arr.length - 1;
while (l < r) {
int mid = (r + l) >> 1;
if (arr[mid] >= val) {
r = mid;
} else
l = mid + 1;
}
return l;
}
int upperBoundSeg(int[] arr, int val) {
int l = 0, r = arr.length - 1;
while (l < r) {
int mid = (r + l + 1) >> 1;
if (arr[mid] <= val) {
l = mid;
} else
r = mid - 1;
}
return l;
}
/************************************************************************************************************************************************/
public static void main(String[] args) throws IOException {
new Thread(null, new CutAnsStick(), "1").start();
}
static PrintWriter out = new PrintWriter(System.out);
static Reader read = new Reader();
static StringBuilder sbr = new StringBuilder();
static int mod = (int) 1e9 + 7;
static int dmax = Integer.MAX_VALUE;
static long lmax = Long.MAX_VALUE;
static int dmin = Integer.MIN_VALUE;
static long lmin = Long.MIN_VALUE;
@Override
public void run() {
try {
// solve();
// solveMoAlgo();
solveSegmentTree();
out.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
static class Reader {
private byte[] buf = new byte[1024];
private int index;
private InputStream in;
private int total;
public Reader() {
in = System.in;
}
public int scan() throws IOException {
if (total < 0)
throw new InputMismatchException();
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0)
return -1;
}
return buf[index++];
}
public int intNext() throws IOException {
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 doubleNext() throws IOException {
double doub = 0;
int n = scan();
while (isWhiteSpace(n))
n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n) && n != '.') {
if (n >= '0' && n <= '9') {
doub *= 10;
doub += n - '0';
n = scan();
} else
throw new InputMismatchException();
}
if (n == '.') {
n = scan();
double temp = 1;
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
temp /= 10;
doub += (n - '0') * temp;
n = scan();
} else
throw new InputMismatchException();
}
}
return doub * neg;
}
public String read() throws IOException {
StringBuilder sb = new StringBuilder();
int n = scan();
while (isWhiteSpace(n))
n = scan();
while (!isWhiteSpace(n)) {
sb.append((char) n);
n = scan();
}
return sb.toString();
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1)
return true;
return false;
}
}
static void shuffle(int[] aa) {
int n = aa.length;
Random rand = new Random();
for (int i = 1; i < n; i++) {
int j = rand.nextInt(i + 1);
int tmp = aa[i];
aa[i] = aa[j];
aa[j] = tmp;
}
}
static void shuffle(int[][] aa) {
int n = aa.length;
Random rand = new Random();
for (int i = 1; i < n; i++) {
int j = rand.nextInt(i + 1);
int first = aa[i][0];
int second = aa[i][1];
aa[i][0] = aa[j][0];
aa[i][1] = aa[j][1];
aa[j][0] = first;
aa[j][1] = second;
}
}
static void print(Object object) {
out.print(object);
}
static void println(Object object) {
out.println(object);
}
static int[] iArr(int len) {
return new int[len];
}
static long[] lArr(int len) {
return new long[len];
}
static long min(long a, long b) {
return Math.min(a, b);
}
static int min(int a, int b) {
return Math.min(a, b);
}
static long max(Long a, Long b) {
return Math.max(a, b);
}
static int max(int a, int b) {
return Math.max(a, b);
}
static int ri() throws IOException {
return read.intNext();
}
static long rl() throws IOException {
return Long.parseLong(read.read());
}
static String rs() throws IOException {
return read.read();
}
static char rc() throws IOException {
return rs().charAt(0);
}
static double rd() throws IOException {
return read.doubleNext();
}
static int getRandom(int l, int r) {
return l + (int) (Math.random() * (r - l + 1));
}
static int lowerbound(ArrayList<Integer> arr, int target) {
int l = 0;
int r = arr.size() - 1;
int mid;
while (l < r) {
mid = (l + r) >> 1;
if (arr.get(mid) >= target)
r = mid;
else
l = mid + 1;
}
return l;
}
static int upperbound(ArrayList<Integer> arr, int target) {
int l = 0;
int r = arr.size() - 1;
int mid;
while (l < r) {
mid = (l + r + 1) >> 1;
if (arr.get(mid) > target)
r = mid - 1;
else
l = mid;
}
return l;
}
}
| Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 11 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | 7427f36a0195df706727fd5e3b97b582 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes |
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.util.Random;
import java.util.*;
public class CutAnsStick implements Runnable {
int[][] counts;
// Use Randomized Algo (Time Complexity[nLog(n) + Q(Log(n)^2)]
void solve() throws IOException {
int n = ri(), q = ri();
int[] arr = iArr(n);
counts = new int[n][];
int[] total = iArr(n);
for (int i = 0; i < n; i++) {
arr[i] = ri() - 1;
total[arr[i]]++;
}
for (int i = 0; i < n; i++) {
if (total[i] > 0) {
counts[i] = new int[total[i]];
}
}
for (int i = 0; i < n; i++) {
int curr = arr[i];
counts[curr][total[curr] - 1] = i;
total[curr]--;
}
for (int i = 0; i < n; i++) {
if (counts[i] != null) {
Arrays.sort(counts[i]);
}
}
while (q-- > 0) {
int l = ri() - 1, r = ri() - 1;
// Get 30 random numbers
Set<Integer> set = new HashSet<>();
for (int i = 0; i < 30; i++) {
set.add(arr[getRandom(l, r)]);
}
// Check the count of each element and find max
int max = 1;
for (int ele : set) {
int[] curr = counts[ele];
int count = upperBound(curr, r) - lowerBound(curr, l);
max = max(max, count);
}
int wid = r - l + 1;
int ans = 0;
int start = 0, end = max;
while (start <= end) {
int mid = (start + end) >> 1; // The number of partitions
int rem = wid - mid;
int leftOver = max - mid;
int allowed = (rem + 1) / 2;
if (allowed >= leftOver) {
ans = mid;
end = mid - 1;
} else
start = mid + 1;
}
ans++;
// Answer is just really max(max - (width - max), 1)
sbr.append(ans).append("\n");
}
print(sbr.toString());
}
int lowerBound(int[] arr, int val) {
int l = -1, r = arr.length;
while (l + 1 < r) {
int mid = (r + l) >> 1;
if (arr[mid] >= val)
r = mid;
else
l = mid;
}
return r;
}
int upperBound(int[] arr, int val) {
int l = -1, r = arr.length;
while (l + 1 < r) {
int mid = (r + l) >> 1;
if (arr[mid] <= val) {
l = mid;
} else {
r = mid;
}
}
return l + 1;
}
/************************************************************************************************************************************************/
// Time Complexity [ QLog(Q) + ]
void solveMoAlgo() throws IOException {
int n = ri(), q = ri();
int[] arr = iArr(n);
Query[] queries = new Query[q];
for (int i = 0; i < n; i++) {
arr[i] = ri();
}
for (int i = 0; i < q; i++) {
queries[i] = new Query(ri() - 1, ri(), i);
}
int sqr = (int) Math.sqrt(q);
// Sort the queries
Arrays.sort(queries, (o1, o2) -> {
if (o1.l / sqr != o2.l / sqr)
return Integer.compare(o1.l / sqr, o2.l / sqr);
// To make it even more faster
// If div by block is odd then sort the right index in ascending order
// else descending order
if ((o1.l / sqr & 1) == 1)
return Integer.compare(o1.r, o2.r);
return Integer.compare(o2.r, o1.r);
});
int leftPointer = 0, rightPointer = 0;
int[] counts = iArr(n + 1);
for (Query query : queries) {
int l = query.l, r = query.r;
while (leftPointer > query.l) {
leftPointer--;
counts[arr[leftPointer]]++;
}
while (rightPointer < query.r) {
counts[arr[rightPointer]]++;
rightPointer++;
}
while (rightPointer > query.r) {
rightPointer--;
counts[arr[rightPointer]]--;
}
while (leftPointer < query.l) {
counts[arr[leftPointer]]--;
leftPointer++;
}
// Choose 30 random numbers and find max frequency
int maxFreq = 1;
for (int i = 0; i < 30; i++) {
maxFreq = max(maxFreq, counts[arr[getRandom(l, r - 1)]]);
}
query.res = max(1, maxFreq - (r - l - maxFreq));
}
int[] ans = iArr(q);
for (Query qu : queries) {
ans[qu.index] = qu.res;
}
Arrays.stream(ans).forEach(o -> sbr.append(o).append("\n"));
println(sbr.toString());
}
class Query {
int l, r, index, res = 1;
public Query(int l, int r, int i) {
this.l = l;
this.r = r;
this.index = i;
}
}
/************************************************************************************************************************************************/
public static void main(String[] args) throws IOException {
new Thread(null, new CutAnsStick(), "1").start();
}
static PrintWriter out = new PrintWriter(System.out);
static Reader read = new Reader();
static StringBuilder sbr = new StringBuilder();
static int mod = (int) 1e9 + 7;
static int dmax = Integer.MAX_VALUE;
static long lmax = Long.MAX_VALUE;
static int dmin = Integer.MIN_VALUE;
static long lmin = Long.MIN_VALUE;
@Override
public void run() {
try {
// solve();
solveMoAlgo();
out.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
static class Reader {
private byte[] buf = new byte[1024];
private int index;
private InputStream in;
private int total;
public Reader() {
in = System.in;
}
public int scan() throws IOException {
if (total < 0)
throw new InputMismatchException();
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0)
return -1;
}
return buf[index++];
}
public int intNext() throws IOException {
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 doubleNext() throws IOException {
double doub = 0;
int n = scan();
while (isWhiteSpace(n))
n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n) && n != '.') {
if (n >= '0' && n <= '9') {
doub *= 10;
doub += n - '0';
n = scan();
} else
throw new InputMismatchException();
}
if (n == '.') {
n = scan();
double temp = 1;
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
temp /= 10;
doub += (n - '0') * temp;
n = scan();
} else
throw new InputMismatchException();
}
}
return doub * neg;
}
public String read() throws IOException {
StringBuilder sb = new StringBuilder();
int n = scan();
while (isWhiteSpace(n))
n = scan();
while (!isWhiteSpace(n)) {
sb.append((char) n);
n = scan();
}
return sb.toString();
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1)
return true;
return false;
}
}
static void shuffle(int[] aa) {
int n = aa.length;
Random rand = new Random();
for (int i = 1; i < n; i++) {
int j = rand.nextInt(i + 1);
int tmp = aa[i];
aa[i] = aa[j];
aa[j] = tmp;
}
}
static void shuffle(int[][] aa) {
int n = aa.length;
Random rand = new Random();
for (int i = 1; i < n; i++) {
int j = rand.nextInt(i + 1);
int first = aa[i][0];
int second = aa[i][1];
aa[i][0] = aa[j][0];
aa[i][1] = aa[j][1];
aa[j][0] = first;
aa[j][1] = second;
}
}
static void print(Object object) {
out.print(object);
}
static void println(Object object) {
out.println(object);
}
static int[] iArr(int len) {
return new int[len];
}
static long[] lArr(int len) {
return new long[len];
}
static long min(long a, long b) {
return Math.min(a, b);
}
static int min(int a, int b) {
return Math.min(a, b);
}
static long max(Long a, Long b) {
return Math.max(a, b);
}
static int max(int a, int b) {
return Math.max(a, b);
}
static int ri() throws IOException {
return read.intNext();
}
static long rl() throws IOException {
return Long.parseLong(read.read());
}
static String rs() throws IOException {
return read.read();
}
static char rc() throws IOException {
return rs().charAt(0);
}
static double rd() throws IOException {
return read.doubleNext();
}
static int getRandom(int l, int r) {
return l + (int) (Math.random() * (r - l + 1));
}
static int lowerbound(ArrayList<Integer> arr, int target) {
int l = 0;
int r = arr.size() - 1;
int mid;
while (l < r) {
mid = (l + r) >> 1;
if (arr.get(mid) >= target)
r = mid;
else
l = mid + 1;
}
return l;
}
static int upperbound(ArrayList<Integer> arr, int target) {
int l = 0;
int r = arr.size() - 1;
int mid;
while (l < r) {
mid = (l + r + 1) >> 1;
if (arr.get(mid) > target)
r = mid - 1;
else
l = mid;
}
return l;
}
}
| Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 11 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | 0563d2379f04cec5914a026c16a29943 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes |
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.util.Random;
import java.util.*;
public class CutAnsStick implements Runnable {
int[][] counts;
// Use Randomized Algo (Time Complexity[nLog(n) + Q(Log(n)^2)]
void solve() throws IOException {
int n = ri(), q = ri();
int[] arr = iArr(n);
counts = new int[n][];
int[] total = iArr(n);
for (int i = 0; i < n; i++) {
arr[i] = ri() - 1;
total[arr[i]]++;
}
for (int i = 0; i < n; i++) {
if (total[i] > 0) {
counts[i] = new int[total[i]];
}
}
for (int i = 0; i < n; i++) {
int curr = arr[i];
counts[curr][total[curr] - 1] = i;
total[curr]--;
}
for (int i = 0; i < n; i++) {
if (counts[i] != null) {
Arrays.sort(counts[i]);
}
}
while (q-- > 0) {
int l = ri() - 1, r = ri() - 1;
// Get 30 random numbers
Set<Integer> set = new HashSet<>();
for (int i = 0; i < 30; i++) {
set.add(arr[getRandom(l, r)]);
}
// Check the count of each element and find max
int max = 1;
for (int ele : set) {
int[] curr = counts[ele];
int count = upperBound(curr, r) - lowerBound(curr, l);
max = max(max, count);
}
int wid = r - l + 1;
int ans = 0;
int start = 0, end = max;
while (start <= end) {
int mid = (start + end) >> 1; // The number of partitions
int rem = wid - mid;
int leftOver = max - mid;
int allowed = (rem + 1) / 2;
if (allowed >= leftOver) {
ans = mid;
end = mid - 1;
} else
start = mid + 1;
}
ans++;
// Answer is just really max(max - (width - max), 1)
sbr.append(ans).append("\n");
}
print(sbr.toString());
}
int lowerBound(int[] arr, int val) {
int l = -1, r = arr.length;
while (l + 1 < r) {
int mid = (r + l) >> 1;
if (arr[mid] >= val)
r = mid;
else
l = mid;
}
return r;
}
int upperBound(int[] arr, int val) {
int l = -1, r = arr.length;
while (l + 1 < r) {
int mid = (r + l) >> 1;
if (arr[mid] <= val) {
l = mid;
} else {
r = mid;
}
}
return l + 1;
}
/************************************************************************************************************************************************/
void solveMoAlgo() throws IOException {
int n = ri(), q = ri();
int[] arr = iArr(n);
Query[] queries = new Query[q];
for (int i = 0; i < n; i++) {
arr[i] = ri();
}
for (int i = 0; i < q; i++) {
queries[i] = new Query(ri() - 1, ri(), i);
}
int sqr = (int) Math.sqrt(q);
// Sort the queries
Arrays.sort(queries, (o1, o2) -> {
if (o1.l / sqr != o2.l / sqr)
return Integer.compare(o1.l / sqr, o2.l / sqr);
return Integer.compare(o1.r, o2.r);
});
int leftPointer = 0, rightPointer = 0;
int[] counts = iArr(n + 1);
for (Query query : queries) {
int l = query.l, r = query.r;
while (leftPointer > query.l) {
leftPointer--;
counts[arr[leftPointer]]++;
}
while (rightPointer < query.r) {
counts[arr[rightPointer]]++;
rightPointer++;
}
while (rightPointer > query.r) {
rightPointer--;
counts[arr[rightPointer]]--;
}
while (leftPointer < query.l) {
counts[arr[leftPointer]]--;
leftPointer++;
}
// Choose 30 random numbers and find max frequency
int maxFreq = 1;
for (int i = 0; i < 30; i++) {
maxFreq = max(maxFreq, counts[arr[getRandom(l, r - 1)]]);
}
query.res = max(1, maxFreq - (r - l - maxFreq));
}
int[] ans = iArr(q);
for (Query qu : queries) {
ans[qu.index] = qu.res;
}
Arrays.stream(ans).forEach(o -> sbr.append(o).append("\n"));
println(sbr.toString());
}
class Query {
int l, r, index, res = 1;
public Query(int l, int r, int i) {
this.l = l;
this.r = r;
this.index = i;
}
}
/************************************************************************************************************************************************/
public static void main(String[] args) throws IOException {
new Thread(null, new CutAnsStick(), "1").start();
}
static PrintWriter out = new PrintWriter(System.out);
static Reader read = new Reader();
static StringBuilder sbr = new StringBuilder();
static int mod = (int) 1e9 + 7;
static int dmax = Integer.MAX_VALUE;
static long lmax = Long.MAX_VALUE;
static int dmin = Integer.MIN_VALUE;
static long lmin = Long.MIN_VALUE;
@Override
public void run() {
try {
// solve();
solveMoAlgo();
out.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
static class Reader {
private byte[] buf = new byte[1024];
private int index;
private InputStream in;
private int total;
public Reader() {
in = System.in;
}
public int scan() throws IOException {
if (total < 0)
throw new InputMismatchException();
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0)
return -1;
}
return buf[index++];
}
public int intNext() throws IOException {
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 doubleNext() throws IOException {
double doub = 0;
int n = scan();
while (isWhiteSpace(n))
n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n) && n != '.') {
if (n >= '0' && n <= '9') {
doub *= 10;
doub += n - '0';
n = scan();
} else
throw new InputMismatchException();
}
if (n == '.') {
n = scan();
double temp = 1;
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
temp /= 10;
doub += (n - '0') * temp;
n = scan();
} else
throw new InputMismatchException();
}
}
return doub * neg;
}
public String read() throws IOException {
StringBuilder sb = new StringBuilder();
int n = scan();
while (isWhiteSpace(n))
n = scan();
while (!isWhiteSpace(n)) {
sb.append((char) n);
n = scan();
}
return sb.toString();
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1)
return true;
return false;
}
}
static void shuffle(int[] aa) {
int n = aa.length;
Random rand = new Random();
for (int i = 1; i < n; i++) {
int j = rand.nextInt(i + 1);
int tmp = aa[i];
aa[i] = aa[j];
aa[j] = tmp;
}
}
static void shuffle(int[][] aa) {
int n = aa.length;
Random rand = new Random();
for (int i = 1; i < n; i++) {
int j = rand.nextInt(i + 1);
int first = aa[i][0];
int second = aa[i][1];
aa[i][0] = aa[j][0];
aa[i][1] = aa[j][1];
aa[j][0] = first;
aa[j][1] = second;
}
}
static void print(Object object) {
out.print(object);
}
static void println(Object object) {
out.println(object);
}
static int[] iArr(int len) {
return new int[len];
}
static long[] lArr(int len) {
return new long[len];
}
static long min(long a, long b) {
return Math.min(a, b);
}
static int min(int a, int b) {
return Math.min(a, b);
}
static long max(Long a, Long b) {
return Math.max(a, b);
}
static int max(int a, int b) {
return Math.max(a, b);
}
static int ri() throws IOException {
return read.intNext();
}
static long rl() throws IOException {
return Long.parseLong(read.read());
}
static String rs() throws IOException {
return read.read();
}
static char rc() throws IOException {
return rs().charAt(0);
}
static double rd() throws IOException {
return read.doubleNext();
}
static int getRandom(int l, int r) {
return l + (int) (Math.random() * (r - l + 1));
}
static int lowerbound(ArrayList<Integer> arr, int target) {
int l = 0;
int r = arr.size() - 1;
int mid;
while (l < r) {
mid = (l + r) >> 1;
if (arr.get(mid) >= target)
r = mid;
else
l = mid + 1;
}
return l;
}
static int upperbound(ArrayList<Integer> arr, int target) {
int l = 0;
int r = arr.size() - 1;
int mid;
while (l < r) {
mid = (l + r + 1) >> 1;
if (arr.get(mid) > target)
r = mid - 1;
else
l = mid;
}
return l;
}
}
| Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 11 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | 37342e6fe50d754273df7e919a25a0b7 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes |
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.util.Random;
import java.util.*;
public class CutAnsStick implements Runnable {
int[][] counts;
void solve() throws IOException {
int n = ri(), q = ri();
int[] arr = iArr(n);
counts = new int[n][];
int[] total = iArr(n);
for (int i = 0; i < n; i++) {
arr[i] = ri() - 1;
total[arr[i]]++;
}
for (int i = 0; i < n; i++) {
if (total[i] > 0) {
counts[i] = new int[total[i]];
}
}
for (int i = 0; i < n; i++) {
int curr = arr[i];
counts[curr][total[curr] - 1] = i;
total[curr]--;
}
for (int i = 0; i < n; i++) {
if (counts[i] != null) {
Arrays.sort(counts[i]);
}
}
while (q-- > 0) {
int l = ri() - 1, r = ri() - 1;
// Get 30 random numbers
Set<Integer> set = new HashSet<>();
for (int i = 0; i < 30; i++) {
set.add(arr[getRandom(l, r)]);
}
// Check the count of each element and find max
int max = 1;
for (int ele : set) {
int[] curr = counts[ele];
int count = upperBound(curr, r) - lowerBound(curr, l);
max = max(max, count);
}
int wid = r - l + 1;
// int ans = 0;
// int start = 0, end = max;
// while (start <= end) {
// int mid = (start + end) >> 1; // The number of partitions
// int rem = wid - mid;
// int leftOver = max - mid;
// int allowed = (rem + 1) / 2;
// if (allowed >= leftOver) {
// ans = mid;
// end = mid - 1;
// } else
// start = mid + 1;
// }
// ans++;
sbr.append(max(1, max - (wid - max))).append("\n");
}
print(sbr.toString());
}
int lowerBound(int[] arr, int val) {
int l = -1, r = arr.length;
while (l + 1 < r) {
int mid = (r + l) >> 1;
if (arr[mid] >= val)
r = mid;
else
l = mid;
}
return r;
}
int upperBound(int[] arr, int val) {
int l = -1, r = arr.length;
while (l + 1 < r) {
int mid = (r + l) >> 1;
if (arr[mid] <= val) {
l = mid;
} else {
r = mid;
}
}
return l + 1;
}
/************************************************************************************************************************************************/
public static void main(String[] args) throws IOException {
new Thread(null, new CutAnsStick(), "1").start();
}
static PrintWriter out = new PrintWriter(System.out);
static Reader read = new Reader();
static StringBuilder sbr = new StringBuilder();
static int mod = (int) 1e9 + 7;
static int dmax = Integer.MAX_VALUE;
static long lmax = Long.MAX_VALUE;
static int dmin = Integer.MIN_VALUE;
static long lmin = Long.MIN_VALUE;
@Override
public void run() {
try {
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
static class Reader {
private byte[] buf = new byte[1024];
private int index;
private InputStream in;
private int total;
public Reader() {
in = System.in;
}
public int scan() throws IOException {
if (total < 0)
throw new InputMismatchException();
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0)
return -1;
}
return buf[index++];
}
public int intNext() throws IOException {
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 doubleNext() throws IOException {
double doub = 0;
int n = scan();
while (isWhiteSpace(n))
n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n) && n != '.') {
if (n >= '0' && n <= '9') {
doub *= 10;
doub += n - '0';
n = scan();
} else
throw new InputMismatchException();
}
if (n == '.') {
n = scan();
double temp = 1;
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
temp /= 10;
doub += (n - '0') * temp;
n = scan();
} else
throw new InputMismatchException();
}
}
return doub * neg;
}
public String read() throws IOException {
StringBuilder sb = new StringBuilder();
int n = scan();
while (isWhiteSpace(n))
n = scan();
while (!isWhiteSpace(n)) {
sb.append((char) n);
n = scan();
}
return sb.toString();
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1)
return true;
return false;
}
}
static void shuffle(int[] aa) {
int n = aa.length;
Random rand = new Random();
for (int i = 1; i < n; i++) {
int j = rand.nextInt(i + 1);
int tmp = aa[i];
aa[i] = aa[j];
aa[j] = tmp;
}
}
static void shuffle(int[][] aa) {
int n = aa.length;
Random rand = new Random();
for (int i = 1; i < n; i++) {
int j = rand.nextInt(i + 1);
int first = aa[i][0];
int second = aa[i][1];
aa[i][0] = aa[j][0];
aa[i][1] = aa[j][1];
aa[j][0] = first;
aa[j][1] = second;
}
}
static void print(Object object) {
out.print(object);
}
static void println(Object object) {
out.println(object);
}
static int[] iArr(int len) {
return new int[len];
}
static long[] lArr(int len) {
return new long[len];
}
static long min(long a, long b) {
return Math.min(a, b);
}
static int min(int a, int b) {
return Math.min(a, b);
}
static long max(Long a, Long b) {
return Math.max(a, b);
}
static int max(int a, int b) {
return Math.max(a, b);
}
static int ri() throws IOException {
return read.intNext();
}
static long rl() throws IOException {
return Long.parseLong(read.read());
}
static String rs() throws IOException {
return read.read();
}
static char rc() throws IOException {
return rs().charAt(0);
}
static double rd() throws IOException {
return read.doubleNext();
}
static int getRandom(int l, int r) {
return l + (int) (Math.random() * (r - l + 1));
}
static int lowerbound(ArrayList<Integer> arr, int target) {
int l = 0;
int r = arr.size() - 1;
int mid;
while (l < r) {
mid = (l + r) >> 1;
if (arr.get(mid) >= target)
r = mid;
else
l = mid + 1;
}
return l;
}
static int upperbound(ArrayList<Integer> arr, int target) {
int l = 0;
int r = arr.size() - 1;
int mid;
while (l < r) {
mid = (l + r + 1) >> 1;
if (arr.get(mid) > target)
r = mid - 1;
else
l = mid;
}
return l;
}
}
| Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 11 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | ddffba75daaee551cdf589eda73ef6e8 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes |
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.util.Random;
import java.util.*;
public class CutAnsStick implements Runnable {
int[][] counts;
void solve() throws IOException {
int n = ri(), q = ri();
int[] arr = iArr(n);
counts = new int[n][];
int[] total = iArr(n);
for (int i = 0; i < n; i++) {
arr[i] = ri() - 1;
total[arr[i]]++;
}
for (int i = 0; i < n; i++) {
if (total[i] > 0) {
counts[i] = new int[total[i]];
}
}
for (int i = 0; i < n; i++) {
int curr = arr[i];
counts[curr][total[curr] - 1] = i;
total[curr]--;
}
for (int i = 0; i < n; i++) {
if (counts[i] != null) {
Arrays.sort(counts[i]);
}
}
while (q-- > 0) {
int l = ri() - 1, r = ri() - 1;
// Get 30 random numbers
Set<Integer> set = new HashSet<>();
for (int i = 0; i < 40; i++) {
set.add(arr[getRandom(l, r)]);
}
// Check the count of each element and find max
int max = 1;
for (int ele : set) {
int[] curr = counts[ele];
int count = upperBound(curr, r) - lowerBound(curr, l);
max = max(max, count);
}
int wid = r - l + 1;
int ans = 0;
int start = 0, end = max;
while (start <= end) {
int mid = (start + end) >> 1;
int rem = wid - mid;
int leftOver = max - mid;
int allowed = (rem + 1) / 2;
if (allowed >= leftOver) {
ans = mid;
end = mid - 1;
} else
start = mid + 1;
}
ans++;
sbr.append(ans).append("\n");
}
print(sbr.toString());
}
int lowerBound(int[] arr, int val) {
int l = -1, r = arr.length;
while (l + 1 < r) {
int mid = (r + l) >> 1;
if (arr[mid] >= val)
r = mid;
else
l = mid;
}
return r;
}
int upperBound(int[] arr, int val) {
int l = -1, r = arr.length;
while (l + 1 < r) {
int mid = (r + l) >> 1;
if (arr[mid] <= val) {
l = mid;
} else {
r = mid;
}
}
return l + 1;
}
/************************************************************************************************************************************************/
public static void main(String[] args) throws IOException {
new Thread(null, new CutAnsStick(), "1").start();
}
static PrintWriter out = new PrintWriter(System.out);
static Reader read = new Reader();
static StringBuilder sbr = new StringBuilder();
static int mod = (int) 1e9 + 7;
static int dmax = Integer.MAX_VALUE;
static long lmax = Long.MAX_VALUE;
static int dmin = Integer.MIN_VALUE;
static long lmin = Long.MIN_VALUE;
@Override
public void run() {
try {
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
static class Reader {
private byte[] buf = new byte[1024];
private int index;
private InputStream in;
private int total;
public Reader() {
in = System.in;
}
public int scan() throws IOException {
if (total < 0)
throw new InputMismatchException();
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0)
return -1;
}
return buf[index++];
}
public int intNext() throws IOException {
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 doubleNext() throws IOException {
double doub = 0;
int n = scan();
while (isWhiteSpace(n))
n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n) && n != '.') {
if (n >= '0' && n <= '9') {
doub *= 10;
doub += n - '0';
n = scan();
} else
throw new InputMismatchException();
}
if (n == '.') {
n = scan();
double temp = 1;
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
temp /= 10;
doub += (n - '0') * temp;
n = scan();
} else
throw new InputMismatchException();
}
}
return doub * neg;
}
public String read() throws IOException {
StringBuilder sb = new StringBuilder();
int n = scan();
while (isWhiteSpace(n))
n = scan();
while (!isWhiteSpace(n)) {
sb.append((char) n);
n = scan();
}
return sb.toString();
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1)
return true;
return false;
}
}
static void shuffle(int[] aa) {
int n = aa.length;
Random rand = new Random();
for (int i = 1; i < n; i++) {
int j = rand.nextInt(i + 1);
int tmp = aa[i];
aa[i] = aa[j];
aa[j] = tmp;
}
}
static void shuffle(int[][] aa) {
int n = aa.length;
Random rand = new Random();
for (int i = 1; i < n; i++) {
int j = rand.nextInt(i + 1);
int first = aa[i][0];
int second = aa[i][1];
aa[i][0] = aa[j][0];
aa[i][1] = aa[j][1];
aa[j][0] = first;
aa[j][1] = second;
}
}
static void print(Object object) {
out.print(object);
}
static void println(Object object) {
out.println(object);
}
static int[] iArr(int len) {
return new int[len];
}
static long[] lArr(int len) {
return new long[len];
}
static long min(long a, long b) {
return Math.min(a, b);
}
static int min(int a, int b) {
return Math.min(a, b);
}
static long max(Long a, Long b) {
return Math.max(a, b);
}
static int max(int a, int b) {
return Math.max(a, b);
}
static int ri() throws IOException {
return read.intNext();
}
static long rl() throws IOException {
return Long.parseLong(read.read());
}
static String rs() throws IOException {
return read.read();
}
static char rc() throws IOException {
return rs().charAt(0);
}
static double rd() throws IOException {
return read.doubleNext();
}
static int getRandom(int l, int r) {
return l + (int) (Math.random() * (r - l + 1));
}
}
| Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 11 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | 0d4dae8bb42179ec31dcbcffbc13ba24 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes |
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.util.Random;
import java.util.*;
public class CutAnsStick implements Runnable {
int[][] counts;
void solve() throws IOException {
int n = ri(), q = ri();
int[] arr = iArr(n);
counts = new int[n][];
int[] total = iArr(n);
for (int i = 0; i < n; i++) {
arr[i] = ri() - 1;
total[arr[i]]++;
}
for (int i = 0; i < n; i++) {
if (total[i] > 0) {
counts[i] = new int[total[i]];
}
}
for (int i = 0; i < n; i++) {
int curr = arr[i];
counts[curr][total[curr] - 1] = i;
total[curr]--;
}
for (int i = 0; i < n; i++) {
if (counts[i] != null) {
Arrays.sort(counts[i]);
}
}
while (q-- > 0) {
int l = ri() - 1, r = ri() - 1;
// Get 30 random numbers
Set<Integer> set = new HashSet<>();
for (int i = 0; i < 30; i++) {
set.add(arr[getRandom(l, r)]);
}
// Check the count of each element and find max
int max = 1;
for (int ele : set) {
int[] curr = counts[ele];
int count = upperBound(curr, r) - lowerBound(curr, l);
max = max(max, count);
}
int wid = r - l + 1;
int ans = 0;
int start = 0, end = max;
while (start <= end) {
int mid = (start + end) >> 1;
int rem = wid - mid;
int leftOver = max - mid;
int allowed = (rem + 1) / 2;
if (allowed >= leftOver) {
ans = mid;
end = mid - 1;
} else
start = mid + 1;
}
ans++;
sbr.append(ans).append("\n");
}
print(sbr.toString());
}
int lowerBound(int[] arr, int val) {
int l = -1, r = arr.length;
while (l + 1 < r) {
int mid = (r + l) >> 1;
if (arr[mid] >= val)
r = mid;
else
l = mid;
}
return r;
}
int upperBound(int[] arr, int val) {
int l = -1, r = arr.length;
while (l + 1 < r) {
int mid = (r + l) >> 1;
if (arr[mid] <= val) {
l = mid;
} else {
r = mid;
}
}
return l + 1;
}
/************************************************************************************************************************************************/
public static void main(String[] args) throws IOException {
new Thread(null, new CutAnsStick(), "1").start();
}
static PrintWriter out = new PrintWriter(System.out);
static Reader read = new Reader();
static StringBuilder sbr = new StringBuilder();
static int mod = (int) 1e9 + 7;
static int dmax = Integer.MAX_VALUE;
static long lmax = Long.MAX_VALUE;
static int dmin = Integer.MIN_VALUE;
static long lmin = Long.MIN_VALUE;
@Override
public void run() {
try {
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
static class Reader {
private byte[] buf = new byte[1024];
private int index;
private InputStream in;
private int total;
public Reader() {
in = System.in;
}
public int scan() throws IOException {
if (total < 0)
throw new InputMismatchException();
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0)
return -1;
}
return buf[index++];
}
public int intNext() throws IOException {
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 doubleNext() throws IOException {
double doub = 0;
int n = scan();
while (isWhiteSpace(n))
n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n) && n != '.') {
if (n >= '0' && n <= '9') {
doub *= 10;
doub += n - '0';
n = scan();
} else
throw new InputMismatchException();
}
if (n == '.') {
n = scan();
double temp = 1;
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
temp /= 10;
doub += (n - '0') * temp;
n = scan();
} else
throw new InputMismatchException();
}
}
return doub * neg;
}
public String read() throws IOException {
StringBuilder sb = new StringBuilder();
int n = scan();
while (isWhiteSpace(n))
n = scan();
while (!isWhiteSpace(n)) {
sb.append((char) n);
n = scan();
}
return sb.toString();
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1)
return true;
return false;
}
}
static void shuffle(int[] aa) {
int n = aa.length;
Random rand = new Random();
for (int i = 1; i < n; i++) {
int j = rand.nextInt(i + 1);
int tmp = aa[i];
aa[i] = aa[j];
aa[j] = tmp;
}
}
static void shuffle(int[][] aa) {
int n = aa.length;
Random rand = new Random();
for (int i = 1; i < n; i++) {
int j = rand.nextInt(i + 1);
int first = aa[i][0];
int second = aa[i][1];
aa[i][0] = aa[j][0];
aa[i][1] = aa[j][1];
aa[j][0] = first;
aa[j][1] = second;
}
}
static void print(Object object) {
out.print(object);
}
static void println(Object object) {
out.println(object);
}
static int[] iArr(int len) {
return new int[len];
}
static long[] lArr(int len) {
return new long[len];
}
static long min(long a, long b) {
return Math.min(a, b);
}
static int min(int a, int b) {
return Math.min(a, b);
}
static long max(Long a, Long b) {
return Math.max(a, b);
}
static int max(int a, int b) {
return Math.max(a, b);
}
static int ri() throws IOException {
return read.intNext();
}
static long rl() throws IOException {
return Long.parseLong(read.read());
}
static String rs() throws IOException {
return read.read();
}
static char rc() throws IOException {
return rs().charAt(0);
}
static double rd() throws IOException {
return read.doubleNext();
}
static int getRandom(int l, int r) {
return l + (int) (Math.random() * (r - l + 1));
}
}
| Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 11 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | 6a11ede2e340700ad3457fafd928e0a8 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | import java.awt.*;
import java.io.*;
import java.sql.Array;
import java.util.*;
import java.util.List;
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;
}
}
static final int N=300005;
static final int mod=1000000007;
static FastReader r=new FastReader();
static PrintWriter pw = new PrintWriter(System.out);
static int []a=new int[N];
static final int BLOCK=300;
static int maxx=0;
static int []num=new int[N];
static int []occur=new int[N];
static int []ans;
public static class DataRange{
int l,r;
int id;
public DataRange(int l, int r, int id) {
this.l = l;
this.r = r;
this.id = id;
}
}
public static void add(int x){
int n=num[x];
if(n==maxx) ++maxx;
if(n>=0){
--occur[n];
++occur[n+1];
}
++num[x];
}
public static void del(int x){
int n=num[x];
if(n>0&&n==maxx&&occur[n]==1) --maxx;
if(n>0){
--occur[n];
++occur[n-1];
}
--num[x];
}
public static void main(String[] args) throws IOException {
int n=r.nextInt();
int q=r.nextInt();
ans=new int[q];
// List<DataRange> queries=new ArrayList<>();
DataRange[] queries=new DataRange[q];
for(int i=1;i<=n;++i) a[i]=r.nextInt();
for(int i=0;i<q;++i){
int left=r.nextInt();
int right=r.nextInt();
// queries.add(new DataRange(left,right,i));
queries[i]=new DataRange(left,right,i);
}
Arrays.parallelSort(queries, new Comparator<DataRange>() {
@Override
public int compare(DataRange o1, DataRange o2) {
if(o1.l/BLOCK!=o2.l/BLOCK){
if(o1.l/BLOCK<o2.l/BLOCK) return -1;
else if(o1.l/BLOCK==o2.l/BLOCK)return 0;
return 1;
}
if(o1.r<o2.r) return -1;
else if(o1.r==o2.r) return 0;
return 1;
}
});
// Collections.sort(queries, new Comparator<DataRange>() {
// @Override
// public int compare(DataRange o1, DataRange o2) {
// if(o1.l/BLOCK!=o2.l/BLOCK){
// if(o1.l/BLOCK<o2.l/BLOCK) return -1;
// else if(o1.l/BLOCK==o2.l/BLOCK)return 0;
// return 1;
// }
// if(o1.r<o2.r) return -1;
// else if(o1.r==o2.r) return 0;
// return 1;
// }
// });
int left=1,right=0;
for(int i=0;i<q;++i){
while(left<queries[i].l){
del(a[left]);
++left;
}
while(left>queries[i].l){
--left;
add(a[left]);
}
while(right<queries[i].r){
++right;
add(a[right]);
}
while(right>queries[i].r){
del(a[right]);
--right;
}
int len=queries[i].r-queries[i].l+1;
if(maxx<=len/2) ans[queries[i].id]=1;
else{
// System.out.println("id : "+queries.get(i).id);
// System.out.println("maxx : "+maxx);
int other=len-maxx;
int remain=maxx-other;
ans[queries[i].id]=remain;
}
}
StringBuilder stringBuilder=new StringBuilder();
for(int i=0;i<q;++i){
stringBuilder.append(ans[i]+"\n");
}
pw.print(stringBuilder);
pw.close();
}
}
| Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 11 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | e0ddd521b7dbd7101faea207c64984c3 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | import java.awt.*;
import java.io.*;
import java.sql.Array;
import java.util.*;
import java.util.List;
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;
}
}
static final int N=300005;
static final int mod=1000000007;
static FastReader r=new FastReader();
static PrintWriter pw = new PrintWriter(System.out);
static int []a=new int[N];
static final int BLOCK=400;
static int maxx=0;
static int []num=new int[N];
static int []occur=new int[N];
static int []ans;
public static class DataRange{
int l,r;
int id;
public DataRange(int l, int r, int id) {
this.l = l;
this.r = r;
this.id = id;
}
}
public static void add(int x){
int n=num[x];
if(n==maxx) ++maxx;
if(n>=0){
--occur[n];
++occur[n+1];
}
++num[x];
}
public static void del(int x){
int n=num[x];
if(n>0&&n==maxx&&occur[n]==1) --maxx;
if(n>0){
--occur[n];
++occur[n-1];
}
--num[x];
}
public static void main(String[] args) throws IOException {
int n=r.nextInt();
int q=r.nextInt();
ans=new int[q];
// List<DataRange> queries=new ArrayList<>();
DataRange[] queries=new DataRange[q];
for(int i=1;i<=n;++i) a[i]=r.nextInt();
for(int i=0;i<q;++i){
int left=r.nextInt();
int right=r.nextInt();
// queries.add(new DataRange(left,right,i));
queries[i]=new DataRange(left,right,i);
}
Arrays.parallelSort(queries, new Comparator<DataRange>() {
@Override
public int compare(DataRange o1, DataRange o2) {
if(o1.l/BLOCK!=o2.l/BLOCK){
if(o1.l/BLOCK<o2.l/BLOCK) return -1;
else if(o1.l/BLOCK==o2.l/BLOCK)return 0;
return 1;
}
if(o1.r<o2.r) return -1;
else if(o1.r==o2.r) return 0;
return 1;
}
});
// Collections.sort(queries, new Comparator<DataRange>() {
// @Override
// public int compare(DataRange o1, DataRange o2) {
// if(o1.l/BLOCK!=o2.l/BLOCK){
// if(o1.l/BLOCK<o2.l/BLOCK) return -1;
// else if(o1.l/BLOCK==o2.l/BLOCK)return 0;
// return 1;
// }
// if(o1.r<o2.r) return -1;
// else if(o1.r==o2.r) return 0;
// return 1;
// }
// });
int left=1,right=0;
for(int i=0;i<q;++i){
while(left<queries[i].l){
del(a[left]);
++left;
}
while(left>queries[i].l){
--left;
add(a[left]);
}
while(right<queries[i].r){
++right;
add(a[right]);
}
while(right>queries[i].r){
del(a[right]);
--right;
}
int len=queries[i].r-queries[i].l+1;
if(maxx<=len/2) ans[queries[i].id]=1;
else{
// System.out.println("id : "+queries.get(i).id);
// System.out.println("maxx : "+maxx);
int other=len-maxx;
int remain=maxx-other;
ans[queries[i].id]=remain;
}
}
StringBuilder stringBuilder=new StringBuilder();
for(int i=0;i<q;++i){
stringBuilder.append(ans[i]+"\n");
}
pw.print(stringBuilder);
pw.close();
}
}
| Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 11 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | 8574b4b7108d5ebd172fd6f062591ad6 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | //https://codeforces.com/contest/1514/problem/D
//D. Cut and Stick
import java.util.*;
import java.io.*;
public class CF_1516_D{
static int seg_tree[];
static int a[];
static ArrayList<ArrayList<Integer>> al;
static int count(int start, int end, int val){
return upperbound(al.get(val), end) - lowerbound(al.get(val), start);
}
static void build(int node, int start, int end){
if(start==end)
seg_tree[node] = a[start];
else{
int mid = (start+end)/2;
build(2*node, start, mid);
build(2*node+1, mid+1, end);
if(count(start, end, seg_tree[2*node])>count(start, end, seg_tree[2*node+1]))
seg_tree[node] = seg_tree[2*node];
else
seg_tree[node] = seg_tree[2*node+1];
}
}
static int query(int node, int start, int end, int l, int r){
if(end<l || start>r || r<l)
return 0;
if(l<=start && end<=r)
return count(l, r, seg_tree[node]);
int mid = (start+end)/2;
return Math.max(query(2*node, start, mid, l, r), query(2*node+1, mid+1, end, l, r));
}
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));
StringBuilder sb = new StringBuilder();
StringTokenizer st;
st = new StringTokenizer(br.readLine().trim());
int n = Integer.parseInt(st.nextToken());
int q = Integer.parseInt(st.nextToken());
a = new int[n+1];
al = new ArrayList<ArrayList<Integer>>(); //stores position
for(int i=0;i<=n;i++)
al.add(new ArrayList<Integer>());
st = new StringTokenizer(br.readLine());
for(int i=1;i<=n;i++){
a[i] = Integer.parseInt(st.nextToken());
al.get(a[i]).add(i);
}
seg_tree = new int[4*n+2];
build(1, 1, n);
while(q-->0){
st = new StringTokenizer(br.readLine());
int l = Integer.parseInt(st.nextToken());
int r = Integer.parseInt(st.nextToken());
int m = r-l+1;
int ans = 2*query(1, 1, n, l, r)-m;
ans = Math.max(1, ans);
sb.append(ans).append("\n");
}
pw.print(sb);
pw.flush();
pw.close();
}
static int lowerbound(ArrayList<Integer> a, int i){
int l = -1;
int r = a.size();
while(l+1<r){
int mid = (l+r)>>1;
if(a.get(mid)>=i)
r = mid;
else
l = mid;
}
return r;
}
static int upperbound(ArrayList<Integer> a, int i){
int l = -1;
int r = a.size();
while(l+1<r){
int mid = (l+r)>>1;
if(a.get(mid)<=i)
l = mid;
else
r = mid;
}
return l+1;
}
}
//Randomized solution
//But slow in java :(
/*
import java.util.*;
import java.io.*;
public class CF_1516_D{
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));
StringBuilder sb = new StringBuilder();
StringTokenizer st;
Random random = new Random();
st = new StringTokenizer(br.readLine().trim());
int n = Integer.parseInt(st.nextToken());
int q = Integer.parseInt(st.nextToken());
int a[] = new int[n];
ArrayList<ArrayList<Integer>> al = new ArrayList<ArrayList<Integer>>(); //stores position
for(int i=0;i<n;i++)
al.add(new ArrayList<Integer>());
st = new StringTokenizer(br.readLine());
for(int i=0;i<n;i++){
a[i] = Integer.parseInt(st.nextToken())-1;
al.get(a[i]).add(i);
}
HashMap<String, Integer> hm = new HashMap<String, Integer>();
while(q-->0){
st = new StringTokenizer(br.readLine());
int l = Integer.parseInt(st.nextToken())-1;
int r = Integer.parseInt(st.nextToken())-1;
if(hm.containsKey(l+" "+r)){
sb.append(hm.get(l+" "+r)).append("\n");
continue;
}
int m = r-l+1;
HashSet<Integer> hs = new HashSet<Integer>();
for(int i=0;i<25;i++){
int ran = random.nextInt(r-l+1)+l;
hs.add(a[ran]);
}
int ans = 1;
for(int x : hs){
int upp = upperbound(al.get(x), r);
int low = lowerbound(al.get(x), l);
int no_of_subsequence = 2*(upp-low)-m;
ans = Math.max(ans, no_of_subsequence);
}
hm.put(l+" "+r, ans);
sb.append(ans).append("\n");
}
pw.print(sb);
pw.flush();
pw.close();
}
static int lowerbound(ArrayList<Integer> a, int i){
int l = -1;
int r = a.size();
while(l+1<r){
int mid = (l+r)>>1;
if(a.get(mid)>=i)
r = mid;
else
l = mid;
}
return r;
}
static int upperbound(ArrayList<Integer> a, int i){
int l = -1;
int r = a.size();
while(l+1<r){
int mid = (l+r)>>1;
if(a.get(mid)<=i)
l = mid;
else
r = mid;
}
return l+1;
}
}
*/ | Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 11 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | 84dcbf2fce647823790b2bca85b65e95 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | import java.util.*;
import java.io.*;
public class CF_1516_D{
static int seg_tree[];
static int a[];
static ArrayList<ArrayList<Integer>> al;
static int count(int start, int end, int val){
return upperbound(al.get(val), end) - lowerbound(al.get(val), start);
}
static void build(int node, int start, int end){
if(start==end)
seg_tree[node] = a[start];
else{
int mid = (start+end)/2;
build(2*node, start, mid);
build(2*node+1, mid+1, end);
if(count(start, end, seg_tree[2*node])>count(start, end, seg_tree[2*node+1]))
seg_tree[node] = seg_tree[2*node];
else
seg_tree[node] = seg_tree[2*node+1];
}
}
static int query(int node, int start, int end, int l, int r){
if(end<l || start>r || r<l)
return 0;
if(l<=start && end<=r)
return count(l, r, seg_tree[node]);
int mid = (start+end)/2;
return Math.max(query(2*node, start, mid, l, r), query(2*node+1, mid+1, end, l, r));
}
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));
StringBuilder sb = new StringBuilder();
StringTokenizer st;
st = new StringTokenizer(br.readLine().trim());
int n = Integer.parseInt(st.nextToken());
int q = Integer.parseInt(st.nextToken());
a = new int[n+1];
al = new ArrayList<ArrayList<Integer>>(); //stores position
for(int i=0;i<=n;i++)
al.add(new ArrayList<Integer>());
st = new StringTokenizer(br.readLine());
for(int i=1;i<=n;i++){
a[i] = Integer.parseInt(st.nextToken());
al.get(a[i]).add(i);
}
seg_tree = new int[4*n+2];
build(1, 1, n);
while(q-->0){
st = new StringTokenizer(br.readLine());
int l = Integer.parseInt(st.nextToken());
int r = Integer.parseInt(st.nextToken());
int m = r-l+1;
int ans = 2*query(1, 1, n, l, r)-m;
ans = Math.max(1, ans);
sb.append(ans).append("\n");
}
pw.print(sb);
pw.flush();
pw.close();
}
static int lowerbound(ArrayList<Integer> a, int i){
int l = -1;
int r = a.size();
while(l+1<r){
int mid = (l+r)>>1;
if(a.get(mid)>=i)
r = mid;
else
l = mid;
}
return r;
}
static int upperbound(ArrayList<Integer> a, int i){
int l = -1;
int r = a.size();
while(l+1<r){
int mid = (l+r)>>1;
if(a.get(mid)<=i)
l = mid;
else
r = mid;
}
return l+1;
}
} | Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 11 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | 99425c98543e86669ed0316a36c59153 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | //package Codeforces.Round716Div2;
import java.io.*;
import java.util.*;
public class D_MosAlgo {
static class Query implements Comparable<Query>{
int id;
int start;
int end;
int blockno;
Query(int id, int start, int end, int blockno){
this.id = id;
this.start = start;
this.end = end;
this.blockno = blockno;
}
public int compareTo(Query q){
int c = Integer.compare(this.blockno, q.blockno);
if(c==0){
c = Integer.compare(this.end, q.end);
if(this.blockno%2==0){
return c;
}
else{
return c*-1;
}
}
else return c;
}
}
public static void main(String[] args) throws IOException {
Soumit sc = new Soumit();
int n = sc.nextInt();
int q = sc.nextInt();
int[] arr = sc.nextIntArray(n);
int blocksize = (int) Math.sqrt(n);
Query[] queries = new Query[q];
for(int i=0;i<q;i++){
int l = sc.nextInt()-1;
int r = sc.nextInt()-1;
int blockno = l/blocksize;
queries[i] = new Query(i, l, r, blockno);
}
Arrays.sort(queries);
int ll=0, ul=0;
int[] hash = new int[n+10];
int[] counter = new int[n+10];
hash[arr[0]] = 1;
counter[1] = 1;
int max = 1;
int[] output = new int[q];
for(Query query: queries){
while(ul<query.end){
ul++;
counter[hash[arr[ul]]]--;
hash[arr[ul]]++;
counter[hash[arr[ul]]]++;
max = Math.max(max, hash[arr[ul]]);
}
while(ll>query.start){
ll--;
counter[hash[arr[ll]]]--;
hash[arr[ll]]++;
counter[hash[arr[ll]]]++;
max = Math.max(max, hash[arr[ll]]);
}
while(ul>query.end){
counter[hash[arr[ul]]]--;
hash[arr[ul]]--;
counter[hash[arr[ul]]]++;
while(counter[max]==0)
max--;
ul--;
}
while(ll<query.start){
counter[hash[arr[ll]]]--;
hash[arr[ll]]--;
counter[hash[arr[ll]]]++;
while(counter[max]==0)
max--;
ll++;
}
int rangelength = (query.end-query.start+1);
int restfreq = rangelength-max;
if(restfreq<max){
output[query.id] = max-restfreq;
}
else{
output[query.id] = 1;
}
}
StringBuilder sb = new StringBuilder();
for(int i: output){
sb.append(i).append("\n");
}
System.out.println(sb);
sc.close();
}
static class Soumit {
final private int BUFFER_SIZE = 1 << 18;
final private DataInputStream din;
final private byte[] buffer;
private PrintWriter pw;
private int bufferPointer, bytesRead;
StringTokenizer st;
public Soumit() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Soumit(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public void streamOutput(String file) throws IOException {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
pw = new PrintWriter(bw);
}
public void println(String a) {
pw.println(a);
}
public void print(String a) {
pw.print(a);
}
public String readLine() throws IOException {
byte[] buf = new byte[3000064]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public void sort(int[] arr) {
ArrayList<Integer> arlist = new ArrayList<>();
for (int i : arr)
arlist.add(i);
Collections.sort(arlist);
for (int i = 0; i < arr.length; i++)
arr[i] = arlist.get(i);
}
public void sort(long[] arr) {
ArrayList<Long> arlist = new ArrayList<>();
for (long i : arr)
arlist.add(i);
Collections.sort(arlist);
for (int i = 0; i < arr.length; i++)
arr[i] = arlist.get(i);
}
public int[] nextIntArray(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) throws IOException {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
public double[] nextDoubleArray(int n) throws IOException {
double[] arr = new double[n];
for (int i = 0; i < n; i++) {
arr[i] = nextDouble();
}
return arr;
}
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;*/
if (din != null) din.close();
if (pw != null) pw.close();
}
}
}
| Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 11 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | 35a2da4d8e75adb38e1ec4368e3ac034 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | //package Codeforces.Round716Div2;
import java.io.*;
import java.util.*;
public class D_MosAlgo {
static class Query implements Comparable<Query>{
int id;
int start;
int end;
int blockno;
Query(int id, int start, int end, int blockno){
this.id = id;
this.start = start;
this.end = end;
this.blockno = blockno;
}
public int compareTo(Query q){
int c = Integer.compare(this.blockno, q.blockno);
if(c==0){
return Integer.compare(this.end, q.end);
}
else return c;
}
}
public static void main(String[] args) throws IOException {
Soumit sc = new Soumit();
int n = sc.nextInt();
int q = sc.nextInt();
int[] arr = sc.nextIntArray(n);
int blocksize = (int) Math.sqrt(n);
Query[] queries = new Query[q];
for(int i=0;i<q;i++){
int l = sc.nextInt()-1;
int r = sc.nextInt()-1;
int blockno = l/blocksize;
queries[i] = new Query(i, l, r, blockno);
}
Arrays.sort(queries);
int ll=0, ul=0;
int[] hash = new int[n+10];
int[] counter = new int[n+10];
hash[arr[0]] = 1;
counter[1] = 1;
int max = 1;
int[] output = new int[q];
for(Query query: queries){
while(ul<query.end){
ul++;
counter[hash[arr[ul]]]--;
hash[arr[ul]]++;
counter[hash[arr[ul]]]++;
max = Math.max(max, hash[arr[ul]]);
}
while(ll>query.start){
ll--;
counter[hash[arr[ll]]]--;
hash[arr[ll]]++;
counter[hash[arr[ll]]]++;
max = Math.max(max, hash[arr[ll]]);
}
while(ul>query.end){
counter[hash[arr[ul]]]--;
hash[arr[ul]]--;
counter[hash[arr[ul]]]++;
while(counter[max]==0)
max--;
ul--;
}
while(ll<query.start){
counter[hash[arr[ll]]]--;
hash[arr[ll]]--;
counter[hash[arr[ll]]]++;
while(counter[max]==0)
max--;
ll++;
}
/*System.out.println(Arrays.toString(hash));
System.out.println(Arrays.toString(counter));
System.out.println(query.id+" "+max);*/
int rangelength = (query.end-query.start+1);
int restfreq = rangelength-max;
if(restfreq<max){
output[query.id] = max-restfreq;
}
else{
output[query.id] = 1;
}
}
StringBuilder sb = new StringBuilder();
for(int i: output){
sb.append(i).append("\n");
}
System.out.println(sb);
sc.close();
}
static class Soumit {
final private int BUFFER_SIZE = 1 << 18;
final private DataInputStream din;
final private byte[] buffer;
private PrintWriter pw;
private int bufferPointer, bytesRead;
StringTokenizer st;
public Soumit() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Soumit(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public void streamOutput(String file) throws IOException {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
pw = new PrintWriter(bw);
}
public void println(String a) {
pw.println(a);
}
public void print(String a) {
pw.print(a);
}
public String readLine() throws IOException {
byte[] buf = new byte[3000064]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public void sort(int[] arr) {
ArrayList<Integer> arlist = new ArrayList<>();
for (int i : arr)
arlist.add(i);
Collections.sort(arlist);
for (int i = 0; i < arr.length; i++)
arr[i] = arlist.get(i);
}
public void sort(long[] arr) {
ArrayList<Long> arlist = new ArrayList<>();
for (long i : arr)
arlist.add(i);
Collections.sort(arlist);
for (int i = 0; i < arr.length; i++)
arr[i] = arlist.get(i);
}
public int[] nextIntArray(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) throws IOException {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
public double[] nextDoubleArray(int n) throws IOException {
double[] arr = new double[n];
for (int i = 0; i < n; i++) {
arr[i] = nextDouble();
}
return arr;
}
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;*/
if (din != null) din.close();
if (pw != null) pw.close();
}
}
}
| Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 11 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | 9fcf4d308d44999fe13738a3bfdb78d0 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.function.BiFunction;
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.util.Collections;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author koneko096
*/
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);
DCutAndStick solver = new DCutAndStick();
solver.solve(1, in, out);
out.close();
}
static class DCutAndStick {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int N = in.nextInt(), Q = in.nextInt();
List<Integer>[] pos = new List[N + 1];
for (int i = 0; i <= N; i++) {
pos[i] = new ArrayList<>();
pos[i].add(-1);
}
Pair<Integer, Integer>[] A = new Pair[N];
for (int i = 0; i < N; i++) {
Pair<Integer, Integer> val = Pair.of(in.nextInt(), 1);
A[i] = val;
pos[val.getKey()].add(i);
}
SegmentTree<Pair<Integer, Integer>> st = new SegmentTree<>(N, Pair.of(-1, 0), this::merger);
st.build(A);
while (Q-- > 0) {
int l = in.nextInt() - 1, r = in.nextInt() - 1;
int candidate = st.query(l, r).getKey();
if (candidate < 0) {
out.println(1);
continue;
}
int len = pos[candidate].size();
int lb = BinarySearch.lowerBound(pos[candidate], len, l) - 1;
int ub = BinarySearch.upperBound(pos[candidate], len, r) - 1;
int freq = (ub - lb);
// if (N == MaxN && A[0].getKey() == 1) out.println("Freq: "+freq);
if (freq * 2 <= (r - l + 2)) {
out.println(1);
continue;
}
int good = (r - l + 1) - freq;
freq -= good + 1;
out.println(freq + 1);
}
}
private Pair<Integer, Integer> merger(Pair<Integer, Integer> lhs, Pair<Integer, Integer> rhs) {
if (lhs.getKey().equals(rhs.getKey())) {
return Pair.of(lhs.getKey(), lhs.getValue() + rhs.getValue());
}
if (lhs.getValue().compareTo(rhs.getValue()) > 0) {
return Pair.of(lhs.getKey(), lhs.getValue() - rhs.getValue());
}
return Pair.of(rhs.getKey(), rhs.getValue() - lhs.getValue());
}
}
static class BinarySearch {
public static <T extends Comparable<T>> int lowerBound(List<T> list, int length, T value) {
int low = 0;
int high = length;
while (low < high) {
final int mid = (low + high) / 2;
if (value.compareTo(list.get(mid)) < 1) {
high = mid;
} else {
low = mid + 1;
}
}
return low;
}
public static <T extends Comparable<T>> int upperBound(List<T> list, int length, T value) {
int low = 0;
int high = length;
while (low < high) {
final int mid = (low + high) / 2;
if (value.compareTo(list.get(mid)) < 0) {
high = mid;
} else {
low = mid + 1;
}
}
return low;
}
}
static class InputReader {
private BufferedReader reader;
private 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());
}
}
static class SegmentTree<T> {
private int N;
private List<T> tree;
private T initVal;
private BiFunction<T, T, T> merge;
public SegmentTree(int n, T initVal, BiFunction<T, T, T> merge) {
init(n, initVal, merge);
}
void init(int n, T initVal, BiFunction<T, T, T> merge) {
this.N = n;
this.merge = merge;
this.initVal = initVal;
this.tree = new ArrayList<>(Collections.nCopies(2 * n, initVal));
}
public void build(T[] a) {
for (int i = 0; i < N; i++) {
tree.set(i + N, a[i]);
}
for (int i = N - 1; i > 0; i--) {
tree.set(i, merge.apply(tree.get(2 * i), tree.get(2 * i + 1)));
}
}
public T query(int l, int r) {
T res = initVal;
for (l += N, r += N; l <= r; l >>= 1, r >>= 1) {
if ((l & 1) == 1) res = merge.apply(res, tree.get(l++));
if ((r & 1) == 0) res = merge.apply(res, tree.get(r--));
}
return res;
}
}
static class Pair<K extends Comparable<K>, V extends Comparable<V>> implements Comparable<Pair<K, V>> {
private K key;
private V value;
public K getKey() {
return key;
}
public V getValue() {
return value;
}
public static <K extends Comparable<K>, V extends Comparable<V>> Pair<K, V> of(K key, V value) {
return new Pair<>(key, value);
}
private Pair(K key, V value) {
this.key = key;
this.value = value;
}
public String toString() {
return key + "=" + value;
}
public int hashCode() {
// name's hashCode is multiplied by an arbitrary prime number (13)
// in order to make sure there is a difference in the hashCode between
// these two parameters:
// name: a value: aa
// name: aa value: a
return key.hashCode() * 13 + (value == null ? 0 : value.hashCode());
}
public boolean equals(Object o) {
if (this == o) return true;
if (o instanceof Pair) {
Pair pair = (Pair) o;
if (key != null ? !key.equals(pair.key) : pair.key != null) return false;
if (value != null ? !value.equals(pair.value) : pair.value != null) return false;
return true;
}
return false;
}
public int compareTo(Pair<K, V> o) {
if (this == o) return 0;
int cmp = key.compareTo(o.getKey());
if (cmp != 0) return cmp;
return value.compareTo(o.getValue());
}
}
}
| Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 11 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | 6c58ecbf6f1c688930e2b76d54bbe3c9 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 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 First {
static int bl;
static int[] arr;
static int[] cnt;
static int[] freq;
static int max = 0;
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
int n, q;
n = in.nextInt();
q = in.nextInt();
bl = (int) Math.sqrt(n);
arr = new int[n];
cnt = new int[n+10];
freq= new int[n+10];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
answer1[] queries = new answer1[q];
for (int i = 0; i < q; i++) {
queries[i] = new answer1(in.nextInt(), in.nextInt(), i);
}
Arrays.sort(queries);
int l = 0, r =-1 , a = 0;
int[] ans = new int[q];
for (int i = 0; i < q; i++) {
int L, R, index;
L = queries[i].a -1;
R = queries[i].b -1;
index = queries[i].c;
while (R > r) {
++r;
freq[cnt[arr[r]]]--;
cnt[arr[r]]++;
freq[cnt[arr[r]]]++;
if (cnt[arr[r]] > max) {
max = cnt[arr[r]];
}
}
while (L > l){
freq[cnt[arr[l]]]--;
cnt[arr[l]]--;
freq[cnt[arr[l]]]++;
if (max != 0 && freq[max] == 0) {
max--;
}
l++;
}
while (R < r) {
freq[cnt[arr[r]]]--;
cnt[arr[r]]--;
freq[cnt[arr[r]]]++;
if (max != 0 && freq[max] == 0) {
max--;
}
r--;
}
while (L < l) {
--l;
freq[cnt[arr[l]]]--;
cnt[arr[l]]++;
freq[cnt[arr[l]]]++;
if (cnt[arr[l]] > max) {
max = cnt[arr[l]];
}
}
int size = r-l+1;
if (size >= max*2-1) {
ans[index] = 1;
} else {
size = (r-l+1-max)*2+1;
a = 1+r-l+1-size;
ans[index] = a;
}
}
for (int i = 0; i < q; i++) {
out.println(ans[i]);
}
out.close();
}
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 / gcd(a, b)) * b;
}
static class answer implements Comparable<answer>{
int a;
int b;
public answer(int a, int b) {
this.a = a;
this.b = b;
}
@Override
public int compareTo(answer o) {
return this.a - o.a;
}
}
static class answer1 implements Comparable<answer1>{
int a, b, c;
public answer1(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
@Override
public int compareTo(answer1 o) {
if (this.a/bl != o.a/bl)
return this.a-o.a;
return this.b - o.b;
}
}
static long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static void sort(long[] a) {
ArrayList<Long> l=new ArrayList<>();
for (long i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static final Random random=new Random();
static void shuffleSort(int[] a) {
int n=a.length;
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong(){
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
} | Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 11 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | 2d3c6f46794ebfa529b392bea7f51d02 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | //package Codeforces.Round716Div2;
import java.io.*;
import java.util.*;
public class First {
static class Query implements Comparable<Query>{
int id;
int start;
int end;
int blockno;
Query(int id, int start, int end, int blockno){
this.id = id;
this.start = start;
this.end = end;
this.blockno = blockno;
}
public int compareTo(Query q){
int c = Integer.compare(this.blockno, q.blockno);
if(c==0){
return Integer.compare(this.end, q.end);
}
else return c;
}
}
public static void main(String[] args) throws IOException {
v sc = new v();
int n = sc.nextInt();
int q = sc.nextInt();
int[] arr = sc.nextIntArray(n);
int blocksize = (int) Math.sqrt(n);
Query[] queries = new Query[q];
for(int i=0;i<q;i++){
int l = sc.nextInt()-1;
int r = sc.nextInt()-1;
int blockno = l/blocksize;
queries[i] = new Query(i, l, r, blockno);
}
Arrays.sort(queries);
int ll=0, ul=0;
int[] hash = new int[n+10];
int[] counter = new int[n+10];
hash[arr[0]] = 1;
counter[1] = 1;
int max = 1;
int[] output = new int[q];
for(Query query: queries){
while(ul<query.end){
ul++;
counter[hash[arr[ul]]]--;
hash[arr[ul]]++;
counter[hash[arr[ul]]]++;
max = Math.max(max, hash[arr[ul]]);
}
while(ll>query.start){
ll--;
counter[hash[arr[ll]]]--;
hash[arr[ll]]++;
counter[hash[arr[ll]]]++;
max = Math.max(max, hash[arr[ll]]);
}
while(ul>query.end){
counter[hash[arr[ul]]]--;
hash[arr[ul]]--;
counter[hash[arr[ul]]]++;
while(counter[max]==0)
max--;
ul--;
}
while(ll<query.start){
counter[hash[arr[ll]]]--;
hash[arr[ll]]--;
counter[hash[arr[ll]]]++;
while(counter[max]==0)
max--;
ll++;
}
/*System.out.println(Arrays.toString(hash));
System.out.println(Arrays.toString(counter));
System.out.println(query.id+" "+max);*/
int rangelength = (query.end-query.start+1);
int restfreq = rangelength-max;
if(restfreq<max){
output[query.id] = max-restfreq;
}
else{
output[query.id] = 1;
}
}
StringBuilder sb = new StringBuilder();
for(int i: output){
sb.append(i).append("\n");
}
System.out.println(sb);
sc.close();
}
static class v {
final private int BUFFER_SIZE = 1 << 18;
final private DataInputStream din;
final private byte[] buffer;
private PrintWriter pw;
private int bufferPointer, bytesRead;
StringTokenizer st;
public v() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public v(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public void streamOutput(String file) throws IOException {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
pw = new PrintWriter(bw);
}
public void println(String a) {
pw.println(a);
}
public void print(String a) {
pw.print(a);
}
public String readLine() throws IOException {
byte[] buf = new byte[3000064]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public void sort(int[] arr) {
ArrayList<Integer> arlist = new ArrayList<>();
for (int i : arr)
arlist.add(i);
Collections.sort(arlist);
for (int i = 0; i < arr.length; i++)
arr[i] = arlist.get(i);
}
public void sort(long[] arr) {
ArrayList<Long> arlist = new ArrayList<>();
for (long i : arr)
arlist.add(i);
Collections.sort(arlist);
for (int i = 0; i < arr.length; i++)
arr[i] = arlist.get(i);
}
public int[] nextIntArray(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) throws IOException {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
public double[] nextDoubleArray(int n) throws IOException {
double[] arr = new double[n];
for (int i = 0; i < n; i++) {
arr[i] = nextDouble();
}
return arr;
}
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;*/
if (din != null) din.close();
if (pw != null) pw.close();
}
}
}
| Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 11 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | 3cb3b9e6e9d10631eddd1edd79572074 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 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,"_",1<<27)
{
public void run()
{
try
{
solve();
}
catch(Exception e)
{
e.printStackTrace();
System.exit(1);
}
}
}.start();
}
static int occ[][], freq[];
static void solve() throws IOException {
scan = new FastReader();
pw = new PrintWriter(System.out, true);
StringBuilder sb = new StringBuilder();
int t = 1;
while (t-->0) {
int n = ni(), q = ni();
int arr[] = new int[n];
occ = new int[n+1][];
freq = new int[n+1];
for(int i=0;i<n;i++) {
arr[i] = ni();
++freq[arr[i]];
}
for(int i=1;i<=n;i++) {
occ[i] = new int [freq[i]];
freq[i] = 0;
}
for(int i=0;i<n;i++) {
int x = arr[i];
occ[x][freq[x]++] = i;
}
while (q-->0) {
int l = ni(), r = ni();
l--;
r--;
int tries = 40, abundant = -1, ab_freq = -1;
HashSet<Integer> considered = new HashSet<>();
while (tries-->0) {
int idx = getRandomIntegerRange(l,r);
if (considered.contains(arr[idx])) {
continue;
}
considered.add(arr[idx]);
int occ = getLeK(arr[idx], r) - getLeK(arr[idx], l-1);
if(occ > (r-l+1+1)/2) {
abundant = arr[idx];
ab_freq = occ;
break;
}
}
if(abundant==-1) {
sb.append(1);
}
else {
sb.append(ab_freq - (r-l+1 - ab_freq));
}
sb.append("\n");
}
}
psb(sb);
pw.flush();
pw.close();
}
static int getLeK(int val, int k) {
if(freq[val]==0 || occ[val][0] > k) {
return 0;
}
int low = 0, high = freq[val] - 1, ans = 0, mid;
while (low<=high) {
mid = (low+high)>>1;
if(occ[val][mid]<=k) {
ans = mid;
low = ++mid;
}
else {
high = --mid;
}
}
return (ans+1);
}
static int getRandomIntegerRange(int l, int r) {
return l+getRandomInteger0(r-l);
}
static int getRandomInteger0(int x) {
return (int)(random()*(x+1));
}
static void assert_in_range(String varName, int n, int l, int r) {
if (n >=l && n<=r) return;
System.out.println(varName + " is not in range. Actual: "+n+" l : "+l+" r: "+r);
System.exit(1);
}
static void assert_in_range(String varName, long n, long l, long r) {
if (n>=l && n<=r) return;
System.out.println(varName + " is not in range. Actual: "+n+" l : "+l+" r: "+r);
System.exit(1);
}
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 | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 11 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | 3e47c7c6e04320be3809b9b9fef18de3 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class D {
public static void main(String[] args) {
solve();
}
private static Reader reader = null;
private static Writer writer = null;
public static int getInt() {
int read;
int res = 0;
boolean isNegative = false;// 是不是负数
try {
while ((read = reader.read()) != -1) {
if ((char) read == '-') {
res = 0;
isNegative = true;
break;
} else if (isNumber((char) read)) {
res = read - '0';
break;
}
}
while ((read = reader.read()) != -1) {
char ch = (char) read;
if (isNumber(ch)) {
res = res * 10 + (read - '0');
} else {
break;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (isNegative == true) {
res = -1 * res;
}
return res;
}
public static boolean isBlank(char ch) {
if (ch == '\r' || ch == '\n' || ch == ' ') {
return true;
}
return false;
}
public static boolean isNumber(char ch) {
if (ch <= '9' && ch >= '0') {
return true;
}
return false;
}
static int[] gs;
static int block,bj,blockSum;
private static void solve(){
reader = new InputStreamReader(System.in);
writer = new OutputStreamWriter(System.out);
int n,q;
n=getInt();
q=getInt();
gs=new int[n+1];
int[] a=new int[n];
for(int i=0;i<n;i++){
a[i]=getInt();
}
block=(int)Math.sqrt(n+1);
blockSum=(n+block-1)/block;
List<Point>[] dp=new List[blockSum+1];
for(int i=0;i<dp.length;i++)dp[i]=new ArrayList<>();
bj=0;
List<Point>flag=new ArrayList<>();
for(int i=0;i<q;i++){
Point point=new Point();
point.l=getInt();
point.r=getInt();
point.l--;
point.r--;
point.id=i;
if(getBlock(point.l)==getBlock(point.r)){
flag.add(point);
}
else{
dp[getBlock(point.l)].add(point);
}
}
int[] ans=new int[q];
for(int i=0;i<flag.size();i++){
Point point = flag.get(i);
for(int j=point.l;j<=point.r;j++){
add(a[j]);
}
ans[point.id]=getAns(point.l,point.r,gs[bj]);
for(int j=point.l;j<=point.r;j++){
del(a[j]);
}
bj=0;
}
for(int i=1;i<=blockSum;i++){
dp[i].sort((x,y)->{
return x.r-y.r;
});
int l=i*block;
bj=0;
for(int j=0;j<dp[i].size();j++){
Point point = dp[i].get(j);
while(l<=point.r){
add(a[l]);
l++;
}
int ks=bj;
for(int x=point.l;x<i*block;x++){
add(a[x]);
}
ans[point.id]=getAns(point.l,point.r,gs[bj]);
for(int x=point.l;x<i*block;x++){
del(a[x]);
}
bj=ks;
}
if(l<=n)
for(int j=i*block;j<l;j++){
del(a[j]);
}
}
for(int i=0;i<q;i++){
try {
writer.write(ans[i]+"\n");
} catch (IOException e) {
e.printStackTrace();
}
}
try {
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
private static int getBlock(int l){
return l/block+1;
}
private static class Point{
int l;
int r;
int id;
}
private static void add(int val){
gs[val]++;
if(gs[bj]<gs[val])bj=val;
}
private static void del(int val){
gs[val]--;
}
private static int getAns(int l,int r,int s){
int len=r-l+1;
if(len/2>=s)return 1;
return 2*s-len;
}
}
| Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 11 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output | |
PASSED | b78fd8fcc5ab3ab9a076f22fb597b3e0 | train_110.jsonl | 1618839300 | Baby Ehab has a piece of Cut and Stick with an array $$$a$$$ of length $$$n$$$ written on it. He plans to grab a pair of scissors and do the following to it: pick a range $$$(l, r)$$$ and cut out every element $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $$$x$$$, then no value occurs strictly more than $$$\lceil \frac{x}{2} \rceil$$$ times in it.He didn't pick a range yet, so he's wondering: for $$$q$$$ ranges $$$(l, r)$$$, what is the minimum number of pieces he needs to partition the elements $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ into so that the partitioning is beautiful.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | 512 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
DCutAndStick solver = new DCutAndStick();
solver.solve(1, in, out);
out.close();
}
static class DCutAndStick {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt(), q = in.nextInt();
int[] arr = in.nextIntArray(n);
DCutAndStick.Query[] queries = new DCutAndStick.Query[q];
for (int i = 0; i < q; i++) {
queries[i] = new DCutAndStick.Query(in.nextInt() - 1, in.nextInt() - 1, i);
}
DCutAndStick.Query.s = (int) Math.sqrt(arr.length);
Arrays.sort(queries);
int L = 0, R = -1;
int[] count = new int[n + 1], count2 = new int[n + 1];
int[] res = new int[q];
int mc = 0;
for (DCutAndStick.Query x : queries) {
while (R < x.right) {
++R;
int val = arr[R];
count[val]++;
int t = count[val];
count2[t - 1]--;
count2[t]++;
mc = Math.max(mc, t);
}
while (L > x.left) {
--L;
int val = arr[L];
count[val]++;
int t = count[val];
count2[t - 1]--;
count2[t]++;
mc = Math.max(mc, t);
}
while (L < x.left) {
int val = arr[L];
count[val]--;
int t = count[val];
count2[t + 1]--;
count2[t]++;
while (count2[mc] == 0) mc--;
L++;
}
while (R > x.right) {
int val = arr[R];
count[val]--;
int t = count[val];
count2[t + 1]--;
count2[t]++;
while (count2[mc] == 0) mc--;
R--;
}
res[x.idx] = Math.max(2 * mc - (x.right - x.left + 1), 1);
}
for (int a : res) out.println(a);
}
static class Query implements Comparable<DCutAndStick.Query> {
static int s;
int left;
int right;
int idx;
Query(int a, int b, int c) {
left = a;
right = b;
idx = c;
}
public int compareTo(DCutAndStick.Query q) {
if (left / s != q.left / s)
return left / s - q.left / s;
return right - q.right;
}
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void println(int i) {
writer.println(i);
}
}
static class InputReader {
BufferedReader reader;
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[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; ++i) array[i] = nextInt();
return array;
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["6 2\n1 3 2 3 3 2\n1 6\n2 5"] | 3 seconds | ["1\n2"] | NoteIn the first query, you can just put the whole array in one subsequence, since its length is $$$6$$$, and no value occurs more than $$$3$$$ times in it.In the second query, the elements of the query range are $$$[3,2,3,3]$$$. You can't put them all in one subsequence, since its length is $$$4$$$, and $$$3$$$ occurs more than $$$2$$$ times. However, you can partition it into two subsequences: $$$[3]$$$ and $$$[2,3,3]$$$. | Java 11 | standard input | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | d6c228bc6e4c17894d9e723ff980844f | The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the range of this query. | 2,000 | For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists. | standard output |
Subsets and Splits