exec_outcome
stringclasses 1
value | code_uid
stringlengths 32
32
| file_name
stringclasses 111
values | prob_desc_created_at
stringlengths 10
10
| prob_desc_description
stringlengths 63
3.8k
| prob_desc_memory_limit
stringclasses 18
values | source_code
stringlengths 117
65.5k
| lang_cluster
stringclasses 1
value | prob_desc_sample_inputs
stringlengths 2
802
| prob_desc_time_limit
stringclasses 27
values | prob_desc_sample_outputs
stringlengths 2
796
| prob_desc_notes
stringlengths 4
3k
⌀ | lang
stringclasses 5
values | prob_desc_input_from
stringclasses 3
values | tags
listlengths 0
11
| src_uid
stringlengths 32
32
| prob_desc_input_spec
stringlengths 28
2.37k
⌀ | difficulty
int64 -1
3.5k
⌀ | prob_desc_output_spec
stringlengths 17
1.47k
⌀ | prob_desc_output_to
stringclasses 3
values | hidden_unit_tests
stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PASSED
|
f9e0c6251cad533b8b5c31187fd74af1
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Main {
static Scanner sc = new Scanner(System.in);
static PrintWriter out = new PrintWriter(System.out);
static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
// long mod = 998244353;
// long mod = (long)1e9+7;
long mod = 998244353;
public static void main(String[] args) throws Exception {
Main main = new Main();
// int t = sc.nextInt();
int t = 1;
for(int i=1; i<=t; i++){
main.solve();
}
out.flush();
}
void solve() throws Exception {
int n = neInt(), k = neInt();
int[] a = new int[n+1];
for(int i=1; i<=n; i++){
a[i] = neInt();
}
int lo = 1, hi = n+1;
while(lo+1<hi){
int mid = (hi+lo)/2;
if(valid(a, n, k, mid)) lo = mid;
else hi = mid;
}
out.println(lo);
}
boolean valid(int[] a, int n, int k, int target){
int[] mini = new int[]{n+2, n+2};
int sum = 0;
Deque<Integer> list = new LinkedList<>();
list.add(0);
for(int i=1; i<=n; i++){
if(a[i]>=target) sum += 1;
else sum -= 1;
list.add(sum);
if(list.size()>k){
int idx = i-k, j = idx%2;
int val = list.pollFirst();
mini[j] = Math.min(mini[j], val);
}
if(i>=k){
if(sum - mini[i%2]>0) return true;
if(sum - mini[1-i%2]>=0) return true;
}
}
return false;
}
String neS(){
return sc.next();
}
int neInt(){
return Integer.parseInt(sc.next());
}
long neLong(){
return Long.parseLong(sc.next());
}
int paIn(String s){return Integer.parseInt(s);}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 8
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
35656e48f30c632ff40d5ee3a1634c18
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
FastScanner in = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
new Main().run(in, out);
out.close();
}
public static long mod = 17352642619633L;
int N;
int[] a;
int K;
void run(FastScanner in, PrintWriter out) {
N = in.nextInt();
K = in.nextInt();
a = new int[N];
b = new int[N];
int max = 0;
int[] sorted = new int[N];
for (int i = 0; i < N; i++) {
a[i] = in.nextInt();
max = Math.max(a[i], max);
sorted[i] = a[i];
}
if (K == 1) {
out.println(max);
return;
}
Arrays.sort(sorted);
int lo = 0;
int hi = N;
while (lo < hi) {
int m = (lo+hi)>>1;
if (can(sorted[m])) {
lo = m+1;
} else {
hi = m;
}
}
out.println(sorted[lo-1]);
}
// check there exists median of at least m
int[] b;
boolean can(int m) {
for (int i = 0; i < N; i++) {
b[i] = a[i] >= m ? 1 : -1;
}
// is there a positive subarray with length >= K?
LinkedList<int[]> psums = new LinkedList<>();
int psum = 0;
psums.offerLast(new int[] {0, -1});
for (int i = 0; i < N; i++) {
psum += b[i];
if (psums.isEmpty() || psum < psums.peekLast()[0]) {
psums.offerLast(new int[] {psum, i});
}
}
int maxlen = 0;
for (int i = N-1; i >= 0 && !psums.isEmpty(); i--) {
while (!psums.isEmpty() && psums.peekLast()[1] >= i) psums.pollLast();
while (!psums.isEmpty() && psum - psums.peekLast()[0] > 0) {
int[] t = psums.pollLast();
maxlen = Math.max(maxlen, i-t[1]);
}
psum -= b[i];
}
return maxlen >= K;
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
st = null;
}
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());
}
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 8
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
08f20aa83c963ae9402b88904f1495ae
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 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);
}
void work() {
int n=ni(),k=ni();
int[] A=nia(n);
int l=1,r=n+1;
while(l<r){
int m=(l+r)/2;
if(check(m,A,k)){
l=m+1;
}else{
r=m;
}
}
out.println(l-1);
}
private boolean check(int m, int[] A,int k) {
int n=A.length;
int[] sum=new int[n];
for(int i=0;i<n;i++){
if(A[i]>=m){
sum[i]=1;
}else{
sum[i]=-1;
}
if(i>0)sum[i]+=sum[i-1];
}
int s1=0,s2=0;
for(int i=k-1;i<n;i++){
s1=sum[i];
if(i-k>=0){
s2=Math.min(s2,sum[i-k]);
}
if(s1-s2>0){
return true;
}
}
return false;
}
//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,i});
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();
}
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
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 8
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
26b301075d21f8e65e5e518cf913bf3a
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
/**
* BaZ :D
*/
import java.util.*;
import java.io.*;
import static java.lang.Math.*;
public class Main
{
static MyScanner scan;
static PrintWriter pw;
static long MOD = 1_000_000_007;
static long INF = 2_000_000_000_000_000_000L;
static long inf = 2_000_000_000;
public static void main(String[] args) {
new Thread(null, null, "BaZ", 1 << 27) {
public void run() {
try {
solve();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}.start();
}
static int n,k,arr[];
static void solve() throws java.lang.Exception {
//initIo(true, "");
initIo(false, "");
StringBuilder sb = new StringBuilder();
n = ni();
k = ni();
arr = new int[n];
for(int i=0;i<n;i++) {
arr[i] = ni();
}
int low = 0, high = n+1, mid, ans = low;
while (low<=high) {
mid = (low+high)>>1;
if(check(mid)) {
ans = mid;
low = ++mid;
}
else {
high = --mid;
}
}
pl(ans);
pw.flush();
pw.close();
}
static boolean check(int mid) {
//pl("mid: "+mid);
int t[] = new int[n];
for(int i=0;i<n;i++) {
if(arr[i]>=mid) {
t[i] = 1;
}
else {
t[i] = -1;
}
}
int pref[] = new int[n];
for(int i=0;i<n;i++) {
pref[i] = t[i];
if(i>0) {
pref[i]+=pref[i-1];
}
}
//pa("pref", pref);
int suff_max_pref_sum[] = new int[n];
for(int i=n-1;i>=0;--i) {
suff_max_pref_sum[i] = pref[i];
if(i+1<n) {
suff_max_pref_sum[i] = max(suff_max_pref_sum[i+1], suff_max_pref_sum[i]);
}
}
//pa("suff_max_pref_sum", suff_max_pref_sum);
for(int i=0;i+k-1<n;i++) {
int req = (i==0 ? 0 : pref[i-1]) + 1;
if(suff_max_pref_sum[i+k-1]>=req) {
//pl("ret true at "+i);
return true;
}
}
return false;
}
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 void initIo(boolean isFileIO, String suffix) throws IOException {
scan = new MyScanner(isFileIO, suffix);
if(isFileIO) {
pw = new PrintWriter("/Users/amandeep/Desktop/output"+suffix+".txt");
}
else {
pw = new PrintWriter(System.out, true);
}
}
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 String ne() throws IOException
{
return scan.next();
}
static String nel() throws IOException
{
return scan.nextLine();
}
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 arrayName, boolean arr[])
{
pl(arrayName+" : ");
for(boolean 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 void pa(String arrayName, boolean[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(boolean o : arr[i])
p(o);
pl();
}
}
static class MyScanner
{
BufferedReader br;
StringTokenizer st;
MyScanner(boolean readingFromFile, String suffix) throws IOException
{
if(readingFromFile) {
br = new BufferedReader(new FileReader("/Users/amandeep/Desktop/input"+suffix+".txt"));
}
else {
br = new BufferedReader(new InputStreamReader(System.in));
}
}
String nextLine()throws IOException
{
return br.readLine();
}
String next() throws IOException
{
if(st==null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
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());
}
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 8
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
686386571aaf4727e98dd554f3156c1e
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.io.*;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.TimeUnit;
public class d1486 implements Runnable{
public static void main(String[] args) {
try{
new Thread(null, new d1486(), "process", 1<<26).start();
}
catch(Exception e){
System.out.println(e);
}
}
public void run() {
FastReader scan = new FastReader();
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
//PrintWriter out = new PrintWriter("file.out");
Task solver = new Task();
//int t = scan.nextInt();
int t = 1;
for(int i = 1; i <= t; i++) solver.solve(i, scan, out);
out.close();
}
static class Task {
static final int oo = Integer.MAX_VALUE;
static final long OO = Long.MAX_VALUE;
public void solve(int testNumber, FastReader sc, PrintWriter out) {
int N = sc.nextInt();
int K = sc.nextInt();
int[] arr = sc.readArray(N);
int[] clone = arr.clone();
Arrays.sort(clone);
int ans = -1;
int lo = 0, hi = N-1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (test(arr, K, clone[mid])) {
lo = mid+1;
ans = mid;
} else {
hi = mid -1;
}
}
out.println(clone[ans]);
}
boolean test(int[] arr, int K, int ans) {
//dbg("TESTING: " + ans);
int[] pSum = new int[arr.length];
pSum[0] = (arr[0] >= ans) ? 1 : -1;
for(int i = 1; i < arr.length; i++) {
pSum[i] = pSum[i-1] + ((arr[i] >= ans) ? 1: -1);
}
//dbg(pSum);
TreeSet<Integer> set = new TreeSet<>();
set.add(0);
for(int i = 0, j = K-1; j < arr.length; i++, j++) {
if(set.lower(pSum[j]) != null) {
//dbg("SUCCESS: " + ans);
return true;
}
set.add(pSum[i]);
}
//dbg("FAIL: " + ans);
return false;
}
}
static long modInverse(long N, long MOD) {
return binpow(N, MOD - 2, MOD);
}
static long modDivide(long a, long b, long MOD) {
a %= MOD;
return (binpow(b, MOD-2, MOD) * a) % MOD;
}
static long binpow(long a, long b, long m) {
a %= m;
long res = 1;
while (b > 0) {
if ((b & 1) == 1)
res = res * a % m;
a = a * a % m;
b >>= 1;
}
return res;
}
static int[] reverse(int a[])
{
int[] b = new int[a.length];
for (int i = 0, j = a.length; i < a.length; i++, j--) {
b[j - 1] = a[i];
}
return b;
}
static long[] reverse(long a[])
{
long[] b = new long[a.length];
for (int i = 0, j = a.length; i < a.length; i++, j--) {
b[j - 1] = a[i];
}
return b;
}
static void shuffle(Object[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
Object temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
static void shuffle(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;
}
}
static void shuffle(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;
}
}
static class tup implements Comparable<tup>, Comparator<tup>{
int a, b;
tup(int a,int b){
this.a=a;
this.b=b;
}
public tup() {
}
@Override
public int compareTo(tup o){
return Integer.compare(b,o.b);
}
@Override
public int compare(tup o1, tup o2) {
return Integer.compare(o1.b, o2.b);
}
@Override
public int hashCode() {
return Objects.hash(a, b);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
tup other = (tup) obj;
return a==other.a && b==other.b;
}
@Override
public String toString() {
return a + " " + b;
}
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws FileNotFoundException {
br = new BufferedReader(new FileReader(new File(s)));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] readArray(int size) {
int[] a = new int[size];
for(int i = 0; i < size; i++) {
a[i] = nextInt();
}
return a;
}
long[] readLongArray(int size) {
long[] a = new long[size];
for(int i = 0; i < size; i++) {
a[i] = nextLong();
}
return a;
}
}
static void dbg(int[] arr) {
System.out.println(Arrays.toString(arr));
}
static void dbg(long[] arr) {
System.out.println(Arrays.toString(arr));
}
static void dbg(boolean[] arr) {
System.out.println(Arrays.toString(arr));
}
static void dbg(Object... args) {
for (Object arg : args)
System.out.print(arg + " ");
System.out.println();
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 8
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
be8fdce4e3f212606a237fd463feabae
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 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;
private static int N = 0;
public static void process() throws IOException {
int n = sc.nextInt(),k = sc.nextInt();
int arr[] = sc.readArray(n);
int l = 1,r = Integer.MAX_VALUE/100;
int ans = -1;
while(l<=r) {
int mid = (l+r)/2;
int temp[] = new int[n];
int sum = 0;
for(int i=0; i<n; i++) {
if(arr[i] >= mid)sum++;
else sum--;
temp[i] = sum;
}
int min = 0;
boolean flag = false;
for(int i=0; i<n-k+1; i++) {
if(i == 0)min = 0;
else min = min(min,temp[i-1]);
if(temp[i+k-1] - min > 0) {
flag = true;
break;
}
}
if(flag) {
ans = mid;
l = mid+1;
}
else {
r = mid-1;
}
}
System.out.println(ans);
}
//=============================================================================
//--------------------------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 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
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 8
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
fe26c478987d63f4430718ad133c1914
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class D {
public static void main(String[] args) {
FastScanner sc = new FastScanner();
int n = sc.nextInt();
int k = sc.nextInt();
int[] arr = new int[n];
for(int i = 0; i < n; i++){
arr[i] = sc.nextInt();
}
int a = 1, b = n+1;
while(b - a > 1) {
int c = (a+b)/2;
//check if you can make the median >= c
int[] d = new int[n+1];
for(int i = 1; i <= n; i++){
d[i] = d[i-1];
if(arr[i-1] >= c) d[i]++;
else d[i]--;
}
int[] pref = new int[n+1], suff = new int[n+1];
for(int i = 1; i < n; i++){
pref[i] = Math.min(pref[i-1], d[i]);
}
suff[n] = d[n];
for(int i = n-1; i >= 0; i--){
suff[i] = Math.max(suff[i+1], d[i]);
}
boolean based = false;
for(int i = 0, j = k; j <= n; i++, j++){
if(suff[j] - pref[i] >= 1) based = true;
}
if(based) a = c;
else b = c;
}
System.out.println(a);
}
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 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 8
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
0b60e8a3cba4ba675a8270c5df42761a
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Main {
static long startTime = System.currentTimeMillis();
// for global initializations and methods starts here
// global initialisations and methods end here
static void run() {
boolean tc = false;
AdityaFastIO r = new AdityaFastIO();
//FastReader r = new FastReader();
try (OutputStream out = new BufferedOutputStream(System.out)) {
//long startTime = System.currentTimeMillis();
int testcases = tc ? r.ni() : 1;
int tcCounter = 1;
// Hold Here Sparky------------------->>>
// Solution Starts Here
start:
while (testcases-- > 0) {
int n = r.ni();
int k = r.ni();
int[] arr = new int[n + 1];
for (int i = 1; i <= n; i++) arr[i] = r.ni();
int high = Arrays.stream(arr).max().getAsInt();
int low = Arrays.stream(arr).min().getAsInt();
int[] dp = new int[n + 1];
while (high > low) {
int mid = (low + high + 1) >> 1;
boolean ff = false;
int min = n;
for (int j = 1; j <= n; j++) {
dp[j] = dp[j - 1];
if (arr[j] >= mid) dp[j]++;
else dp[j]--;
if (j >= k) {
min = Math.min(min, dp[j - k]);
ff |= dp[j] > min;
}
}
if (ff) low = mid;
else high = mid - 1;
}
out.write((low + " ").getBytes());
out.write(("\n").getBytes());
}
// Solution Ends Here
} catch (IOException e) {
e.printStackTrace();
}
}
static class AdityaFastIO {
final private int BUFFER_SIZE = 1 << 16;
private final DataInputStream din;
private final byte[] buffer;
private int bufferPointer, bytesRead;
public BufferedReader br;
public StringTokenizer st;
public AdityaFastIO() {
br = new BufferedReader(new InputStreamReader(System.in));
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public AdityaFastIO(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String word() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public String line() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public String readLine() throws IOException {
byte[] buf = new byte[100000001]; // 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 ni() 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 nl() 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 nd() 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 Exception {
run();
}
static long mod = 998244353;
static long modInv(long base, long e) {
long result = 1;
base %= mod;
while (e > 0) {
if ((e & 1) > 0) result = result * base % mod;
base = base * base % mod;
e >>= 1;
}
return result;
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String word() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
String line() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int ni() {
return Integer.parseInt(word());
}
long nl() {
return Long.parseLong(word());
}
double nd() {
return Double.parseDouble(word());
}
}
static int MOD = (int) (1e9 + 7);
static long powerLL(long x, long n) {
long result = 1;
while (n > 0) {
if (n % 2 == 1) result = result * x % MOD;
n = n / 2;
x = x * x % MOD;
}
return result;
}
static long powerStrings(int i1, int i2) {
String sa = String.valueOf(i1);
String sb = String.valueOf(i2);
long a = 0, b = 0;
for (int i = 0; i < sa.length(); i++) a = (a * 10 + (sa.charAt(i) - '0')) % MOD;
for (int i = 0; i < sb.length(); i++) b = (b * 10 + (sb.charAt(i) - '0')) % (MOD - 1);
return powerLL(a, b);
}
static long gcd(long a, long b) {
if (a == 0) return b;
else return gcd(b % a, a);
}
static long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
static long lower_bound(List<Long> list, long k) {
int s = 0;
int e = list.size();
while (s != e) {
int mid = (s + e) >> 1;
if (list.get(mid) < k) s = mid + 1;
else e = mid;
}
if (s == list.size()) return -1;
return s;
}
static int upper_bound(List<Long> list, long k) {
int s = 0;
int e = list.size();
while (s != e) {
int mid = (s + e) >> 1;
if (list.get(mid) <= k) s = mid + 1;
else e = mid;
}
if (s == list.size()) return -1;
return s;
}
static void addEdge(ArrayList<ArrayList<Integer>> graph, int edge1, int edge2) {
graph.get(edge1).add(edge2);
graph.get(edge2).add(edge1);
}
public static class Pair implements Comparable<Pair> {
int first;
int second;
public Pair(int first, int second) {
this.first = first;
this.second = second;
}
public String toString() {
return "(" + first + "," + second + ")";
}
public int compareTo(Pair o) {
// TODO Auto-generated method stub
if (this.first != o.first)
return (int) (this.first - o.first);
else return (int) (this.second - o.second);
}
}
public static class PairC<X, Y> implements Comparable<PairC> {
X first;
Y second;
public PairC(X first, Y second) {
this.first = first;
this.second = second;
}
public String toString() {
return "(" + first + "," + second + ")";
}
public int compareTo(PairC o) {
// TODO Auto-generated method stub
return o.compareTo((PairC) first);
}
}
static boolean isCollectionsSorted(List<Long> list) {
if (list.size() == 0 || list.size() == 1) return true;
for (int i = 1; i < list.size(); i++) if (list.get(i) <= list.get(i - 1)) return false;
return true;
}
static boolean isCollectionsSortedReverseOrder(List<Long> list) {
if (list.size() == 0 || list.size() == 1) return true;
for (int i = 1; i < list.size(); i++) if (list.get(i) >= list.get(i - 1)) return false;
return true;
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 8
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
23ee3032217da01fd4bf4c6215271906
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import com.sun.org.apache.regexp.internal.RE;
import java.util.*;
public class Main {
static int N = (int)2e5+10;
static Scanner scan = new Scanner(System.in);
static int[] a = new int[N];
static int[] sum =new int[N];
static int n;
static int k;
static boolean check(int x){
sum[0] = 0;
int minn = N;
for(int i=1;i<=n;i++){
if(a[i]>=x){
sum[i] = sum[i-1]+1;
}else{
sum[i] = sum[i-1]-1;
}
if(i>=k){
minn = Math.min(minn,sum[i-k]);
}
if(sum[i] - minn >0){
return true;
}
}
return false;
}
public static void slove(){
n = scan.nextInt();
k = scan.nextInt();
for(int i=1;i<=n;i++)
a[i] = scan.nextInt();
int l = 1 , r = N;
while(l<r){
int mid = l + r + 1 >>1;
if(check(mid)){
l = mid ;
}else{
r = mid - 1;
}
}
System.out.println(l);
}
public static void main(String[] args) {
//int T = scan.nextInt();
//while(T-->0){
slove();
//}
}
}
class Node{
int x;
int y;
public Node(int x, int y) {
this.x = x;
this.y = y;
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 8
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
5fc0a926531af0d90a4f0bd66b9908fb
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Main {
static int mod = (int) 1e9 + 7;
static int[][] matMul(int[][] A, int[][] B, int p, int q, int r) // C(p x r) = A(p x q) x (q x r) -- O(p x q x r)
{
int[][] C = new int[p][r];
for (int i = 0; i < p; ++i)
for (int j = 0; j < r; ++j)
for (int k = 0; k < q; ++k) {
C[i][j] += (A[i][k] * 1l * B[k][j]) % mod;
C[i][j] %= mod;
}
return C;
}
/*
* 4. Square Matrix Exponentiation
*/
static int[][] matPow(int[][] base, long p) {
int n = base.length;
int[][] ans = new int[n][n];
for (int i = 0; i < n; i++)
ans[i][i] = 1;
while (p != 0) {
if ((p & 1) == 1)
ans = matMul(ans, base, n, n, n);
base = matMul(base, base, n, n, n);
p >>= 1;
}
return ans;
}
public static void main(String args[]) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int t = 1;
while (t-- > 0) {
int n = sc.nextInt();
k = sc.nextInt();
int[] d = new int[n];
for (int i = 0; i < n; i++) {
d[i] = sc.nextInt();
}
int s = 1;
int e = n;
int ans = -1;
while (s <= e) {
int mid = s + e >> 1;
if (check(d, mid)) {
s = mid + 1;
ans = mid;
} else {
e = mid - 1;
}
}
pw.println(ans);
}
pw.flush();
}
static int k;
static boolean check(int[] a, int mid) {
int[] arr = new int[a.length + 1];
int[] min = new int[a.length + 1];
for (int i = 0; i < arr.length-1; i++) {
if (a[i] >= mid) {
arr[i + 1] = 1 + arr[i];
} else {
arr[i + 1] = -1 + arr[i];
}
min[i + 1] = Math.min(min[i], arr[i + 1]);
}
// System.out.println(Arrays.toString(arr)+" "+mid);
// System.out.println(Arrays.toString(min)+" "+mid);
boolean f = false;
for (int i = k; i < min.length; i++) {
int ans = arr[i]-min[i - k];
// System.out.println(ans);
f |= ans > 0;
}
return f;
}
///////////////////////////////////////////////////////////////////////////////////////////
static class tri {
int x, y, z;
public tri(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
}
static class pair implements Comparable<pair> {
int x, y;
boolean w, l;
PriorityQueue<Long> pq;
public pair(boolean a, boolean b) {
w = a;
l = b;
}
pair(int s, int d) {
x = s;
y = d;
}
@Override
public int compareTo(pair p) {
return Long.compare(x, p.x);
}
@Override
public String toString() {
return x + " " + y;
}
}
static long mod(long ans, int mod) {
return (ans % mod + mod) % mod;
}
static long gcd(long a, long b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
static long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
public static int log(int n, int base) {
int ans = 0;
while (n + 1 > base) {
ans++;
n /= base;
}
return ans;
}
static long pow(long b, long e) {
long ans = 1;
while (e > 0) {
if ((e & 1) == 1)
ans = ((ans * 1l * b));
e >>= 1;
{
}
b = ((b * 1l * b));
}
return ans;
}
static long powmod(long r, long e, int mod) {
long ans = 1;
r %= mod;
while (e > 0) {
if ((e & 1) == 1)
ans = (int) ((ans * 1l * r) % mod);
e >>= 1;
r = (int) ((r * 1l * r) % mod);
}
return ans;
}
static int ceil(int a, int b) {
int ans = a / b;
return a % b == 0 ? ans : ans + 1;
}
static long ceil(long a, long b) {
long ans = a / b;
return a % b == 0 ? ans : ans + 1;
}
static HashMap<Integer, Integer> compress(int a[]) {
TreeSet<Integer> ts = new TreeSet<>();
HashMap<Integer, Integer> hm = new HashMap<>();
for (int x : a)
ts.add(x);
for (int x : ts) {
hm.put(x, hm.size() + 1);
}
return hm;
}
// Returns nCr % p
static int C[];
static int nCrModp(int n, int r, int p) {
if (r > n - r)
r = n - r;
if (C[r] != 0)
return C[r];
// The array C is going to store last
// row of pascal triangle at the end.
// And last entry of last row is nCr
C[0] = 1; // Top row of Pascal Triangle
// One by constructs remaining rows of Pascal
// Triangle from top to bottom
for (int i = 1; i <= n; i++) {
// Fill entries of current row using previous
// row values
for (int j = Math.min(i, r); j > 0; j--)
// nCj = (n-1)Cj + (n-1)C(j-1);
C[j] = (C[j] + C[j - 1]) % p;
}
return C[r];
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public int[] intArr(int n) throws IOException {
int a[] = new int[n];
for (int i = 0; i < a.length; i++) {
a[i] = nextInt();
}
return a;
}
public long[] longArr(int n) throws IOException {
long a[] = new long[n];
for (int i = 0; i < a.length; i++) {
a[i] = nextLong();
}
return a;
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public boolean ready() throws IOException {
return br.ready();
}
}
public static void shuffle(int[] times2) {
int n = times2.length;
for (int i = 0; i < n; i++) {
int r = i + (int) (Math.random() * (n - i));
int tmp = times2[i];
times2[i] = times2[r];
times2[r] = tmp;
}
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 8
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
5c505895d6eb92446fd8aa00dc0c2f1a
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Main {
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
public static void main(String[] args) throws Exception {
String [] s = in.readLine().split(" ");
int n = Integer.parseInt(s[0]);
int k = Integer.parseInt(s[1]);
s = in.readLine().split(" ");
int [] a = new int [n+1];
for(int i=0;i<n;i++) a[i] = Integer.parseInt(s[i]);
int l = 1, r = n+1;
while(r-l>1) {
int [] b = new int [n];
int m = (l+r)/2;
for(int i=0;i<n;i++)
if(a[i]>=m) b[i] = 1;
else b[i] = -1;
for(int i=1;i<n;i++) b[i] += b[i-1];
int max = b[k-1];
int min = 0;
for(int i=k;i<n;i++) {
min = Math.min(min, b[i-k]);
max = Math.max(max, b[i]-min);
}
if(max>0) l = m;
else r = m;
}
out.println(l);
out.flush();
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 8
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
1145e3703847a4fba68b25f3fdb58de6
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
public class Main {
static Scanner in = new Scanner(System.in);
// static Scanner in = new Scanner( new File("javain.txt"));
public static void main(String[] args) throws FileNotFoundException {
if(args.length > 0){
in = new Scanner( new File("javain.txt"));
}
for(int i = 0; i < 1; i++){
solve();
}
}
public static void solve(){
int n = in.nextInt();
int k = in.nextInt();
int [] nums = new int[n];
for(int i = 0; i < n; i++){
nums[i] = in.nextInt();
}
int [] sum = new int[n + 1];
int l = 1, r = n;
while(l <= r){
int mid = (l + r) / 2;
for(int i = 0; i < n; i++){
if(nums[i] >= mid){
sum[i + 1] = sum[i] + 1;
}else{
sum[ i + 1] = sum[i] - 1;
}
}
int min = 200000, max = -200000;
for(int i = k; i <= n; i++){
min = Math.min(min, sum[i - k]);
max = Math.max(max, sum[i] - min);
}
if(max > 0){
l = mid + 1;
}else{
r = mid - 1;
}
}
System.out.println(r);
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 8
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
46f20891d0caa65cbaf7423c1244f2e0
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Formatter;
import java.util.Random;
/**
* Coder: SumitRaut
* Date: 27-02-2021 14:23
*/
public class Main {
public static void main(String[] args) throws IOException {
Fs = new FastReader();
out = new PrintWriter(System.out);
int n = Fs.nextInt(), k = Fs.nextInt();
int a[] = Fs.readArray(n);
int l = 0, r = n;
while (l < r) {
int md = (l + r + 1) >> 1;
boolean f = false;
int P[] = new int[n + 1], Mn[] = new int[n + 1];
for (int i = 1; i <= n; ++i) {
P[i] = P[i - 1] + (a[i-1]>=md?1:-1);
if (i >= k && P[i] - Mn[i - k] > 0) {
f = true;
break;
}
Mn[i] = Math.min(P[i], Mn[i - 1]);
}
if (f) l = md;
else r = md - 1;
}
out.println(r);
out.close();
}
static PrintWriter out;
static FastReader Fs;
static final Random random = new Random();
static void ruffleSort(int[] a) {
int n = a.length;
for (int i = 0; i < n; ++i) {
int oi = random.nextInt(n), tmp = a[oi];
a[oi] = a[i];
a[i] = tmp;
}
Arrays.sort(a);
}
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 nextLine() throws IOException {
byte[] buf = new byte[64]; // 64 line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
if (cnt != 0) {
break;
} else {
continue;
}
}
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public String next() throws IOException {
byte[] buf = new byte[64]; // 64 line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == ' ' || c == '\n') {
if (cnt != 0) {
break;
} else {
continue;
}
}
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;
}
public int[] readArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; ++i)
a[i] = nextInt();
return a;
}
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
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 8
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
434c78b0555b33b834119538d1011e1e
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
public class Main {
static class point {
long val, time, t3;
point(long val, long time, int t3) {
this.val = val;
this.time = time;
this.t3 = t3;
}
}
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') {
if (cnt != 0) {
break;
}
else {
continue;
}
}
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();
}
}
static class comp implements Comparator<point> {
public int compare(point a, point b) {
if (a.val == b.val) {
return Long.compare(b.time, a.time);
}
return Long.compare(a.val, b.val);
}
}
static class TreeNode {
int val;
TreeNode left,right;
TreeNode(int val){
this.val=val;left=null;right=null;
}
}
static TreeNode maxx(int start,int end,int[] arr){
if(start>end){
return null;
}
int ind=0;
int max=-1;
for(int j=start;j<=end;j++){
if(arr[j]>max){
max=arr[j];
ind=j;
}
}
TreeNode jj=new TreeNode(arr[ind]);
jj.left=maxx(start,ind-1,arr);
jj.right=maxx(ind+1,end,arr);
return jj;
}
static void dfs(TreeNode root,int dep){
if(root==null){
return;
}
ans[hashMap.get(root.val)]=dep;
dfs(root.left,dep+1);
dfs(root.right,dep+1);
}
static int[] ans;
static HashMap<Integer,Integer> hashMap;
static class pont{
int val,index;
pont(int val,int index){
this.val=val;
this.index=index;
}
}
static class compr implements Comparator<pont>{
public int compare(pont a,pont b){
return a.val-b.val;
}
}
static class poin{
int src;
long val;
poin(int src,long val){
this.src=src;
this.val=val;
}
}
public static void main(String[] args) throws IOException {
Scanner scanner=new Scanner(System.in);
int n=scanner.nextInt();int k=scanner.nextInt();
int[] arr=new int[n];
int min=Integer.MAX_VALUE,max=Integer.MIN_VALUE;
for(int j=0;j<n;j++){
arr[j]=scanner.nextInt();
min=Math.min(min,arr[j]);
max=Math.max(max,arr[j]);
}
int[] ar=new int[n];
int anss=min;
while(min<=max){
int mid=min+(max-min)/2;
for(int j=0;j<n;j++){
if(arr[j]>=mid){
ar[j]=1;
}else{
ar[j]=-1;
}
}
HashMap<Integer,Integer> has=new HashMap<>();
int sum=0;
boolean ff=false;
for(int j=0;j<n;j++){
sum=sum+ar[j];
if(j+1>=k && sum>0){
ff=true;
break;
}
if(sum<=0 && has.get(sum-1)!=null && j-has.get(sum-1)>=k){
ff=true;break;
}
has.putIfAbsent(sum,j);
}
if(ff){
anss=mid;
min=mid+1;
}else{
max=mid-1;
}
}
System.out.println(anss);
// int t=s.nextInt();
// int t=1;
// for(int jj=0;jj<t;jj++){
// int n=s.nextInt();
// HashMap<Integer,HashMap<Integer,Integer>> has=new HashMap<>();
// int m=s.nextInt();
// int x=s.nextInt();
// int y=s.nextInt();
// long[] ti=new long[m];
// long[] ki=new long[m];
// HashMap<Integer,HashSet<Integer>> hash=new HashMap<>();
// for(int i=0;i<=n;i++){
// has.put(i,new HashMap<>());
// hash.put(i,new HashSet<>());
// }
// for(int i=0;i<m;i++){
// int a=s.nextInt();
// int b=s.nextInt();
//// if(has.get(a)==null){
//// has.put(a,new HashMap<>());
//// }
//// if(has.get(b)==null){
//// has.put(b,new HashMap<>());
//// }
// has.get(a).put(b,i);
// has.get(b).put(a,i);
// ti[i]=s.nextLong();
// ki[i]=s.nextLong();
// }
//
// long[] vis=new long[n+1];
// Arrays.fill(vis,Long.MAX_VALUE);
// vis[x]=0;
// Queue<poin> qu=new LinkedList<>();
// qu.add(new poin(x,0));
// long ans=Long.MAX_VALUE;
// while(!qu.isEmpty()){
// poin te=qu.poll();
// if(te.src==y){
// ans=Math.min(ans,te.val);continue;
// }
// for(Integer v:has.get(te.src).keySet()){
// long ll=(ki[has.get(te.src).get(v)]+(te.val%ki[has.get(te.src).get(v)]))%ki[has.get(te.src).get(v)]+ti[has.get(te.src).get(v)];
//// if(te.val>ki[has.get(te.src).get(v)]){
//// long ij=(long)Math.ceil((double)te.val/(double)ki[has.get(te.src).get(v)]);
//// ll=(long)((long)ij*(long)ki[has.get(te.src).get(v)]);
//// }else{
//// // long ij=(long)Math.ceil((double)ki[has.get(te.src).get(v)]/(double)te.val);
//// if(te.val==0){
//// ll=0;
//// }else{
//// ll=(long)((long)(long)ki[has.get(te.src).get(v)]);}
//// }
//// ll=(long)((long)ll+(long)ti[has.get(te.src).get(v)]);
//// long ll= (long)Math.max((long)((long)te.val+(long)ti[has.get(te.src).get(v)]), (long)((long)ki[has.get(te.src).get(v)]*(long)Math.floor((double)ki[has.get(te.src).get(v)]/(double)(te.val+ti[has.get(te.src).get(v)]))));
//// if( !hash.get(v).contains(te.src) ){
//// vis[v]=ll;
//// hash.get(v).add(te.src);
//// qu.add(new poin( v,vis[v]));
//// }
// if(vis[v]>=ll){
// vis[v]=ll;
//// hash.get(v).add(te.src);
// qu.add(new poin( v,vis[v]));
//
// }
// }
// }
// if(ans==Long.MAX_VALUE){
// System.out.println(-1);
// }else{
// System.out.println(ans);}
// }
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 8
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
bc5ec4cd6e99211dc18a24900ac746c6
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.stream.IntStream;
import java.util.Arrays;
import java.io.IOException;
import java.util.OptionalInt;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
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;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
DMaxMedian solver = new DMaxMedian();
solver.solve(1, in, out);
out.close();
}
static class DMaxMedian {
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int n = in.nextInt();
int k = in.nextInt();
int[] a = new int[n];
Arrays.setAll(a, i -> in.nextInt());
int l = Arrays.stream(a).min().getAsInt();
int r = Arrays.stream(a).max().getAsInt();
int[] num = new int[n];
int ans = l;
while (l <= r) {
int mid = (l + r) / 2;
Arrays.setAll(num, i -> (a[i] >= mid ? 1 : -1));
if (check(num, k)) {
ans = mid;
l = mid + 1;
} else {
r = mid - 1;
}
}
out.println(ans);
}
private boolean check(int[] num, int k) {
int len = num.length;
int[] sum = new int[len + 1];
for (int i = 0; i < len; i++) {
sum[i + 1] = sum[i] + num[i];
}
int min = 0;
for (int i = k; i <= len; i++) {
int index = i - k;
min = Math.min(sum[index], min);
if (sum[i] - min > 0) return true;
}
return false;
}
}
static class FastScanner {
private BufferedReader in;
private StringTokenizer st;
public FastScanner(InputStream stream) {
in = new BufferedReader(new InputStreamReader(stream));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 8
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
be4aff2ba780e637b083021034493ff5
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class maxmedian {
public static void main(String[] args) throws IOException {
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(f.readLine());
int n = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken());
int[] arr = new int[n];
st = new StringTokenizer(f.readLine());
for(int i = 0; i < n; i ++) {
arr[i] = Integer.parseInt(st.nextToken());
}
int low = 1;
int high = n;
while(low < high) {
int mid = (low + high + 1) / 2;
int[] conditional = new int[n];
for(int i = 0; i < n; i ++) {
if(arr[i] >= mid) conditional[i] = 1;
else conditional[i] = -1;
}
int[] psum = new int[n];
psum[0] = conditional[0];
for(int i = 1; i < n; i++) {
psum[i] = psum[i - 1] + conditional[i];
}
int min = 0;
boolean yes = false;
for(int i = k - 1; i < n; i ++) {
if(i != k - 1) min = Math.min(psum[i - k], min);
if(psum[i] - min > 0) yes = true;
}
if(yes) {
low = mid;
}
else high = mid - 1;
}
System.out.println(low);
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 8
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
c6b3e7953266e542a370fdf987b516e0
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.io.*;
import java.util.*;
/*
polyakoff
*/
public class Main {
static FastReader in;
static PrintWriter out;
static Random rand = new Random();
static final int oo = (int) 1e9 + 10;
static final long OO = (long) 2e18 + 10;
static final int MOD = (int) 1e9 + 7;
static void solve() {
int n = in.nextInt();
int k = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
int[] prefSum = new int[n + 1];
int[] minPref = new int[n + 1];
int low = 1, high = n;
while (low < high) {
int mid = (low + high + 1) / 2;
boolean is = false;
for (int i = 0; i < n; i++) {
prefSum[i + 1] = prefSum[i] + (a[i] >= mid ? 1 : -1);
minPref[i + 1] = Math.min(minPref[i], prefSum[i + 1]);
if (i + 1 >= k && prefSum[i + 1] > minPref[i + 1 - k])
is = true;
}
if (is)
low = mid;
else
high = mid - 1;
}
out.println(low);
}
public static void main(String[] args) {
in = new FastReader();
out = new PrintWriter(System.out);
int T = 1;
// T = in.nextInt();
while (T-- > 0)
solve();
out.flush();
out.close();
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
FastReader() {
this(System.in);
}
FastReader(String file) throws FileNotFoundException {
this(new FileInputStream(file));
}
FastReader(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String next() {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(nextLine());
}
return st.nextToken();
}
String nextLine() {
String line;
try {
line = br.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return line;
}
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 8
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
dff8c282cd5225faa3a47e2e04113f83
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
//package com.company;
import java.io.*;
import java.util.*;
public class Main {
static FastReader sc = new FastReader();
static PrintWriter out = new PrintWriter(System.out);
private static int N = 200005;
private static int[] a = new int[N];
private static int[] b = new int[N];
private static int n = 0, k = 0;
private static boolean check(int mid){
for(int i = 1 ; i <= n ; ++i) b[i] = b[i - 1] + (a[i] >= mid ? 1 : -1);
int lr = N , rs = 0;
for(int i = k ; i <= n ; ++i){
lr = Math.min(lr , b[i - k]);
rs = Math.max(rs , b[i] - lr);
}
return rs <= 0;
}
public static void main(String[] args) throws IOException{
// write your code here
n = sc.nextInt(); k = sc.nextInt();
for(int i = 1 ; i <= n ; ++i) a[i] = sc.nextInt();
int l = 1 , r = N;
while(l < r){
int mid = l + r + 1 >> 1;
if(check(mid)) r = mid - 1;
else l = mid;
}
out.print(l);
out.flush();
}
}
/** 读取int和double的类 */
class FastReader {
BufferedReader br;
StringTokenizer st; public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
} } return st.nextToken(); } int nextInt() {
return Integer.parseInt(next());
} long nextLong() {
return Long.parseLong(next());
} double nextDouble() {
return Double.parseDouble(next());
}String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 8
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
25460dc785c10b2a21e7ed8069c9d2a5
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.util.*;
import java.awt.font.TextMeasurer;
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception {
int n=sc.nextInt();
int k=sc.nextInt();
Integer[]a=sc.nextIntegerArray(n);
Integer[]b=a.clone();
Arrays.sort(b);
int low=0;
int high=n-1;
int mid=(low+high)/2;
while(low<=high) {
boolean can=false;
int[]c=new int[n];
for(int i=0;i<n;i++) {
if(a[i]<b[mid]) {
c[i]=-1;
}else {
c[i]=1;
}
}
TreeSet<Integer>ts=new TreeSet<Integer>();
ts.add(0);
for(int i=1;i<n;i++) {
c[i]+=c[i-1];
}
for(int i=k-1;i<n;i++) {
if(c[i]-ts.first()>0) {
can=true;
}
ts.add(c[i-k+1]);
}
if(can) {
low=mid+1;
}else {
high=mid-1;
}
mid=(low+high)/2;
}
pw.println(b[high]);
pw.close();
}
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 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();
}
}
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 tuble implements Comparable<tuble> {
int x;
int y;
int z;
public tuble(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public String toString() {
return x + " " + y + " " + z;
}
public int compareTo(tuble other) {
if (this.x == other.x) {
if (this.y == other.y) {
return this.z - other.z;
}
return this.y - other.y;
} else {
return this.x - other.x;
}
}
}
static long mod = 1000000007;
static Random rn = new Random();
static Scanner sc = new Scanner(System.in);
static PrintWriter pw = new PrintWriter(System.out);
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 8
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
abe77143ba75bfa0a9f7d1ca5c089672
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.io.*;
import java.util.StringTokenizer;
public class Solution {
private static boolean TESTS = false;
private final Input in;
private final PrintStream out;
public Solution(final Input in, final PrintStream out) {
this.in = in;
this.out = out;
}
public void solve() {
for (int test = 1, tests = TESTS ? in.nextInt() : 1; test <= tests; test++) {
final int n = in.nextInt();
final int k = in.nextInt();
final int[] a = in.nextInts(n);
final int[] b = new int[n];
int l = 1;
int r = n;
while (l < r) {
final int m = (l + r + 1) >>> 1;
for (int i = 0; i < n; i++) {
b[i] = a[i] < m ? -1 : 1;
if (i > 0) {
b[i] += b[i - 1];
}
}
int min = 0;
int max = b[k - 1];
for (int i = k; i < n; i++) {
min = Math.min(min, b[i - k]);
max = Math.max(max, b[i] - min);
}
if (max > 0) {
l = m;
} else {
r = m - 1;
}
}
out.println(l);
}
}
public static void main(final String[] args) {
final Input in = new Input();
final PrintStream out = new PrintStream(new BufferedOutputStream(System.out));
try {
new Solution(in, out).solve();
} finally {
out.flush();
}
}
private static final class Input {
private final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
private StringTokenizer tokenizer = new StringTokenizer("");
public String nextString() {
try {
while (!tokenizer.hasMoreTokens()) {
final String line = reader.readLine();
tokenizer = new StringTokenizer(line, " ");
}
return tokenizer.nextToken();
} catch (final IOException e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(nextString());
}
public long nextLong() {
return Long.parseLong(nextString());
}
public double nextDouble() {
return Double.parseDouble(nextString());
}
public int[] nextInts(final int size) {
final int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = nextInt();
}
return array;
}
public long[] nextLongs(final int size) {
final long[] array = new long[size];
for (int i = 0; i < size; i++) {
array[i] = nextLong();
}
return array;
}
public double[] nextDoubles(final int size) {
final double[] array = new double[size];
for (int i = 0; i < size; i++) {
array[i] = nextDouble();
}
return array;
}
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 8
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
6d22c250b69df1f8c99a031d6bc55e57
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.io.*;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.locks.LockSupport;
public class Main {
static class Task {
public static String roundS(double result, int scale) {
String fmt = String.format("%%.%df", scale);
return String.format(fmt, result);
// DecimalFormat df = new DecimalFormat("0.000000");
// double result = Double.parseDouble(df.format(result));
}
int rt(int x) {
if (x != fa[x]) {
int to = rt(fa[x]);
dp[x] ^= dp[fa[x]];
fa[x] = to;
return to;
}
return x;
}
void combine(int x, int y, int val) {
int rt1 = rt(x);
int rt2 = rt(y);
if (rt1 == rt2) return;
fa[rt1] = rt2;
dp[rt1] = dp[x] ^ dp[y] ^ val;
g--;
}
int fa[], dp[];
int g;
static int MAXN = 10000;
static Random rd = new Random(348957438574659L);
static int[] ch[],val,size,rnd,cnt;
static int len=0,rt=0;
// return new node, the node below s
static int rotate(int s,int d){
// child
int x=ch[s][d^1];
// give me grandson
ch[s][d^1] = ch[x][d];
// child become father
ch[x][d]=s;
// update size, update new son first
update(s);
update(x);
return x;
}
static void update(int s){
size[s] = size[ch[s][0]] + size[ch[s][1]] + cnt[s];
}
// 0 for left, 1 for right
static int cmp(int x,int num) {
if (val[x] == num) return -1;
return num < val[x] ? 0 : 1;
}
static int insert(int s,int num) {
if(s==0){
s=++len;
val[s]=num;size[s]=1;rnd[s]=rd.nextInt();cnt[s] = 1;
}else{
int d=cmp(s,num);
if(d!=-1) {
ch[s][d]=insert(ch[s][d],num);
// father's random should be greater
if(rnd[s]<rnd[ch[s][d]]) {
s=rotate(s,d^1);
}else {
update(s);
}
}else{
++cnt[s];++size[s];
}
}
return s;
}
static int del(int s,int num) {
int d = cmp(s, num);
if (d != -1) {
ch[s][d] = del(ch[s][d], num);
update(s);
}else if (ch[s][0] * ch[s][1] == 0) {
if(--cnt[s]==0){
s = ch[s][0] + ch[s][1];
}
} else {
int k = rnd[ch[s][0]] < rnd[ch[s][1]] ? 0 : 1;
// k points to smaller random value,then bigger one up
s = rotate(s, k);
// now the node with value num become the child
ch[s][k] = del(ch[s][k], num);
update(s);
}
return s;
}
static int getKth(int s, int k){
int lz = size[ch[s][0]];
if(k>=lz+1&&k<=lz+cnt[s]){
return val[s];
}else if(k<=lz){
return getKth(ch[s][0], k);
}else{
return getKth(ch[s][1], k-lz-cnt[s]);
}
}
static int getRank(int s,int value){
if(s==0)return 1;
if(value==val[s])return size[ch[s][0]] + 1;
if(value<val[s])return getRank(ch[s][0],value);
return getRank(ch[s][1],value)+size[ch[s][0]] + cnt[s];
}
static int getPre(int data){
int ans= -1;
int p=rt;
while(p>0){
if(data>val[p]){
if(ans==-1 || val[p]>val[ans])
ans=p;
p=ch[p][1];
}
else p=ch[p][0];
}
return ans!=-1?val[ans]:(-2147483647);
}
static int getNext(int data){
int ans= -1;
int p=rt;
while(p>0){
if(data<val[p]){
if(ans==-1 || val[p]<val[ans])
ans=p;
p=ch[p][0];
}
else p=ch[p][1];
}
return ans!=-1?val[ans]:2147483647;
}
static boolean find(int s,int num){
while(s!=0){
int d=cmp(s,num);
if(d==-1) return true;
else s=ch[s][d];
}
return false;
}
static int ans = -10000000;
static boolean findX(int s,int num){
while(s!=0){
if(val[s]<=num){
ans = num;
}
int d=cmp(s,num);
if(d==-1) return true;
else {
s = ch[s][d];
}
}
return false;
}
long gcd(long a,long b){
if(b==0) return a;
return gcd(b,a%b);
}
void linear_sort(int arr[]){
int d = 65536;
ArrayDeque bucket[] = new ArrayDeque[d];
for(int j=0;j<d;++j){
bucket[j] = new ArrayDeque();
}
for(int u:arr){
bucket[u%d].offer(u);
}
int pos = 0;
for(int j=0;j<d;++j){
while(bucket[j].size()>0) {
arr[pos++] = (int)bucket[j].pollFirst();
}
}
for(int u:arr){
bucket[u/d].offer(u);
}
pos = 0;
for(int j=0;j<d;++j){
while(bucket[j].size()>0) {
arr[pos++] = (int)bucket[j].pollFirst();
}
}
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
// int a[] = {4,3,2,45,1,2,3,4,56,7,2,1,2};
// linear_sort(a);
// for(int u:a){
// out.println(u);
// }
int t = 1;
//
//
outer:for(int j=0;j<t;++j){
int n = in.nextInt();
int k = in.nextInt();
int a[] = in.nextArray(n);
int lo =1;int hi = n;
while(lo<hi){
int mi = (lo+hi+1)>>1;
int s[ ] = new int[n+1];
for(int i=0;i<n;++i){
s[i+1] = a[i]>=mi?1:-1;
}
for(int i=1;i<=n;++i){
s[i] += s[i-1];
}
int low = -1;
int ok = 0;
for(int i=1;i<=n;++i){
if(i>=k&&(low==-1||s[i-k]<s[low])){
low = i-k;
}
if(low!=-1 && s[i]-s[low]>0){
ok = 1;
break;
}
}
if(ok==1){
lo = mi;
}else{
hi = mi-1;
}
}
out.println(lo);
}
// while(true) {
// int n = in.nextInt();
//
// int m =in.nextInt();
//
// fa = new int[n];
// dp = new int[n];
// for(int i=0;i<n;++i){
// fa[i] = i;
// }
// g = n;
// int c = 0;
// int as[] = new int[n];
// int bs[] = new int[n];
// char xs[] = new char[n];
//
// int at = -1;
// Set<Integer> st = new HashSet<>();
//
// for (int i = 0; i < n; ++i) {
// String line = in.next();
// int p = 0;
// int a = 0;
// while(Character.isDigit(line.charAt(p))){
// a = a*10 + (line.charAt(p)-'0'); p++;
// }
// char x = line.charAt(p++);
//
// int b = 0;
// while(p<line.length()){
// b = b*10 + (line.charAt(p)-'0'); p++;
// }
//
// as[i] = a;
// xs[i] = x;
// bs[i] = b;
//
// if(x=='='){
// int r1 = rt(a); int r2 = rt(b);
// if(r1==r2){
// if(dp[a]!=dp[b]){
// c++;
// at = i;
// }
// }else {
// combine(a, b, 0);
// }
// }else if(x=='<'){
// int r1 = rt(a); int r2 = rt(b);
// if(r1==r2){
// if(dp[a]>=dp[b]){
// c++;
// at = i;
// }
// }else {
// combine(a, b, -1);
// }
// }else{
// int r1 = rt(a); int r2 = rt(b);
// if(r1==r2){
// if(dp[a]<=dp[b]){
// c++;
// at = i;
// }
// }else {
// combine(a, b, 1);
// }
// }
//
//
// }
// if(g==1||c>=2){
// out.println("Impossible");
// continue;
// }
//
//
// for(int xuan: st){
//
//
//
//
// }
//
//
//
//
//
//
// }
}
static long mul(long a, long b, long p)
{
long res=0,base=a;
while(b>0)
{
if((b&1L)>0)
res=(res+base)%p;
base=(base+base)%p;
b>>=1;
}
return res;
}
static long mod_pow(long k,long n,long p){
long res = 1L;
long temp = k%p;
while(n!=0L){
if((n&1L)==1L){
res = mul(res,temp,p);
}
temp = mul(temp,temp,p);
n = n>>1L;
}
return res%p;
}
public static double roundD(double result, int scale){
BigDecimal bg = new BigDecimal(result).setScale(scale, RoundingMode.UP);
return bg.doubleValue();
}
}
private static void solve() {
InputStream inputStream = System.in;
// InputStream inputStream = null;
// try {
// inputStream = new FileInputStream(new File("D:\\chrome_download\\travel_restrictions_input.txt"));
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// }
OutputStream outputStream = System.out;
// OutputStream outputStream = null;
// File f = new File("D:\\chrome_download\\travel_restrictions_output.txt");
// try {
// f.createNewFile();
// } catch (IOException e) {
// e.printStackTrace();
// }
// try {
// outputStream = new FileOutputStream(f);
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// }
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task task = new Task();
task.solve(1, in, out);
out.close();
}
public static void main(String[] args) {
// new Thread(null, () -> solve(), "1", (1 << 10 ) ).start();
solve();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String nextLine() {
String line = null;
try {
line = reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return line;
}
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 char nextChar() {
return next().charAt(0);
}
public int[] nextArray(int n) {
int res[] = new int[n];
for (int i = 0; i < n; ++i) {
res[i] = nextInt();
}
return res;
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 8
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
d7993a03b1735828a917af8e589c73a6
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.io.*;
import java.util.*;
import java.lang.*;
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);
solve(in, out);
out.close();
}
static int L,R,top,bottom;
static int cnt,edge;
public static void solve(InputReader sc, PrintWriter pw) {
// int t=sc.nextInt();
int t=1;
u:while(t-->0){
int n=sc.nextInt();
int k=sc.nextInt();
int []arr=new int [n];
for(int i=0;i<n;i++)
arr[i]=sc.nextInt();
int []brr=new int[n];
int l=1,r=n,m,min;
boolean flag;
while(l<=r){
m=(r-l)/2+l;
min=Integer.MAX_VALUE;
flag=false;
for(int i=0;i<n;i++){
brr[i]=(i>0?brr[i-1]:0)+((arr[i]>=m)?1:-1);
if(i>=k-1){
min=Math.min(min,i>=k?brr[i-k]:0);
if(brr[i]-min>0){
flag=true;
break;
}
}
}
if(flag)
l=m+1;
else
r=m-1;
}
pw.println(r);
}
}
public static int ask(int l, int r, InputReader sc){
System.out.println("? "+l+" "+r);
System.out.flush();
return sc.nextInt();
}
public static void sort(long []arr){
ArrayList<Long> list=new ArrayList<>();
for(int i=0;i<arr.length;i++)
list.add(arr[i]);
Collections.sort(list);
for(int i=0;i<arr.length;i++)
arr[i]=list.get(i);
}
public static void swap(char []chrr, int i, int j){
char temp=chrr[i];
chrr[i]=chrr[j];
chrr[j]=temp;
}
public static int num(int n){
int a=0;
while(n>0){
a+=(n&1);
n>>=1;
}
return a;
}
static class Pair{
int a, b;
Pair(int a,int b){
this.a=a;
this.b=b;
}
}
// public int compareTo(Pair p){
// return (b-p.b);
// }
// public int hashCode(){
// int hashcode = (a+" "+b).hashCode();
// return hashcode;
// }
// public boolean equals(Object obj){
// if (obj instanceof Pair) {
// Pair p = (Pair) obj;
// return (p.a==this.a && p.b == this.b);
// }
// return false;
// }
static boolean isPrime(int n) {
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static int gcd(int a, int b) {
if (b == 0)
return a;
return a>b?gcd(b, a % b):gcd(a, b % a);
}
static long fast_pow(long base,long n,long M){
if(n==0)
return 1;
if(n==1)
return base;
long halfn=fast_pow(base,n/2,M);
if(n%2==0)
return ( halfn * halfn ) % M;
else
return ( ( ( halfn * halfn ) % M ) * base ) % M;
}
static long modInverse(long n,long M){
return fast_pow(n,M-2,M);
}
public static void feedArr(long []arr,InputReader sc){
for(int i=0;i<arr.length;i++)
arr[i]=sc.nextLong();
}
public static void feedArr(double []arr,InputReader sc){
for(int i=0;i<arr.length;i++)
arr[i]=sc.nextDouble();
}
public static void feedArr(int []arr,InputReader sc){
for(int i=0;i<arr.length;i++)
arr[i]=sc.nextInt();
}
public static void feedArr(String []arr,InputReader sc){
for(int i=0;i<arr.length;i++)
arr[i]=sc.next();
}
public static String printArr(int []arr){
StringBuilder sbr=new StringBuilder();
for(int i:arr)
sbr.append(i+" ");
return sbr.toString();
}
public static String printArr(long []arr){
StringBuilder sbr=new StringBuilder();
for(long i:arr)
sbr.append(i+" ");
return sbr.toString();
}
public static String printArr(String []arr){
StringBuilder sbr=new StringBuilder();
for(String i:arr)
sbr.append(i+" ");
return sbr.toString();
}
public static String printArr(double []arr){
StringBuilder sbr=new StringBuilder();
for(double i:arr)
sbr.append(i+" ");
return sbr.toString();
}
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
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 8
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
c4f04186090c7e7621cc693742a2a344
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class D {
public static void main(String[] args) {
FastScanner in = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int t = 1;//in.nextInt();
while(t-->0) {
int n = in.nextInt(), k = in.nextInt();
int a[] = in.readArray(n);
int low = 1, high = 2000_00;
int mid;
while(low<=high){
mid = (low+high)/2;
int b[] = new int[n];
for(int i=0;i<n;i++){
if(a[i]<mid) b[i] = -1;
else b[i] = 1;
}
int prefixSum[] = new int[n]; prefixSum[0] = b[0];
for(int i=1;i<n;i++) prefixSum[i] = prefixSum[i-1] + b[i];
int minPrefix[] = new int[n]; minPrefix[0] = b[0];
for(int i=1;i<n;i++) minPrefix[i] = Math.min(minPrefix[i-1],prefixSum[i]);
boolean valid = false;
for(int i=k-1;i<n;i++){
if(prefixSum[i]>0) valid = true;
if(i-k>-1&&prefixSum[i]-minPrefix[i-k]>0) valid = true;
if(valid) break;
}
if(valid) low = mid+1;
else high = mid-1;
}
out.println(high);
}
out.flush();
}
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) {}
return st.nextToken();
}
String nextLine(){
try{ return br.readLine(); }
catch(IOException e) { } return "";
}
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] = nextInt();
return a;
}
}
static final Random random = new Random();
static void ruffleSort(int[] a){
int n = a.length;
for(int i=0;i<n;i++){
int j = random.nextInt(n), temp = a[j];
a[j] = a[i]; a[i] = temp;
}
Arrays.sort(a);
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 8
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
357c1d7eaa0ec368b7922f6c08433843
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
//created by Whiplash99
import java.io.*;
import java.util.*;
public class D
{
private static boolean check(int[] a, int N, int K, int val)
{
int[] arr=new int[N]; int i;
for(i=0;i<N;i++) arr[i]=a[i]<val?-1:1;
int[] pref=new int[N+1];
int cur=0;
for(i=0;i<N;i++)
{
cur+=arr[i]; pref[i+1]=Math.min(pref[i],cur);
if(i<K-1) continue;
if(cur-pref[i+1-K]>0) return true;
}
return false;
}
private static int bSearch(int[] a, int N, int K)
{
int l=1,r=N,mid,ans=-1;
while (l<=r)
{
mid=(l+r)/2;
if(check(a,N,K,mid))
{
ans=mid;
l=mid+1;
}
else r=mid-1;
}
return ans;
}
public static void main(String[] args) throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int i,N;
String[] s=br.readLine().trim().split(" ");
N=Integer.parseInt(s[0]);
int K=Integer.parseInt(s[1]);
int[] a=new int[N];
s=br.readLine().trim().split(" ");
for(i=0;i<N;i++) a[i]=Integer.parseInt(s[i]);
System.out.println(bSearch(a,N,K));
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 8
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
418146a8559d28c15ab30c4225f5756e
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.List;
import java.util.*;
public class realfast implements Runnable
{
private static final int INF = (int) 1e9;
long in= 1000000007;
long fac[]= new long[1000001];
long inv[]=new long[1000001];
public void solve() throws IOException
{
//int t = readInt();
int n = readInt();
int k = readInt();
int arr[]=new int[n+1];
ArrayList<Integer> mat=new ArrayList<Integer>();
// int seg[]=new int[8*n+8];
int pre[]=new int[n+1];
for(int i =1;i<=n;i++)
{
arr[i]=readInt();
mat.add(arr[i]);
}
Collections.sort(mat);
int left =0;
int right=n-1;
int max[]=new int[2*n+10];
int ans=-1;
while(left<=right)
{
// Arrays.fill(seg,-1);
int mid = left+(right-left)/2;
int gal = (int)mat.get(mid);
pre[0]=n+1;
// out.println(gal);
for(int i=1;i<=n;i++)
{
if(arr[i]<gal)
pre[i]= pre[i-1]-1;
else
pre[i]= pre[i-1]+1;
}
// int max[]=new int [2*n+1];
Arrays.fill(max,0);
int start =-1;
for(int i=n;i>=1;i--)
{
//int pal = pre[i];
if(pre[i]<=start)
{
continue;
}
for(int j=start+1;j<=pre[i];j++)
{
max[j]=i;
}
start=pre[i];
}
int val =0;
for(int i=0;i<n;i++)
{
int ll = max[pre[i]+1]-i;
val=Math.max(val,ll);
}
if(val>=k)
{
left=mid+1;
ans= mid;
}
else
right=mid-1;
}
out.println(mat.get(ans));
}
public int value (int seg[], int left , int right ,int index, int l, int r)
{
if(left>right)
{
return -100000000;
}
if(right<l||left>r)
return -100000000;
if(left>=l&&right<=r)
return seg[index];
int mid = left+(right-left)/2;
int val = value(seg,left,mid,2*index+1,l,r);
int val2 = value(seg,mid+1,right,2*index+2,l,r);
return Math.max(val,val2);
}
public int gcd(int a , int b )
{
if(a<b)
{
int t =a;
a=b;
b=t;
}
if(a%b==0)
return b ;
return gcd(b,a%b);
}
public long pow(long n , long p,long m)
{
if(p==0)
return 1;
long val = pow(n,p/2,m);;
val= (val*val)%m;
if(p%2==0)
return val;
else
return (val*n)%m;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static void main(String[] args) {
new Thread(null, new realfast(), "", 128 * (1L << 20)).start();
}
private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
private BufferedReader reader;
private StringTokenizer tokenizer;
private PrintWriter out;
@Override
public void run() {
try {
if (ONLINE_JUDGE || !new File("input.txt").exists()) {
reader = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else {
reader = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
}
solve();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
reader.close();
} catch (IOException e) {
// nothing
}
out.close();
}
}
private String readString() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
@SuppressWarnings("unused")
private int readInt() throws IOException {
return Integer.parseInt(readString());
}
@SuppressWarnings("unused")
private long readLong() throws IOException {
return Long.parseLong(readString());
}
@SuppressWarnings("unused")
private double readDouble() throws IOException {
return Double.parseDouble(readString());
}
}
class edge implements Comparable<edge>{
int u ;
int v;
edge(int u, int v)
{
this.u=u;
this.v=v;
}
public int compareTo(edge e)
{
return this.v-e.v;
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 8
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
99387974322ebefbb7f4732526bc7265
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Div708 {
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////// /////////
//////// /////////
//////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOOOOO SSSSSSS EEEEEEEEEEEEE /////////
//////// HHHH HHHH EEEEEEEEEEEEE MMMMMM MMMMMM OOO OOO SSSS SSS EEEEEEEEEEEEE /////////
//////// HHHH HHHH EEEEE MMMM MMM MMM MMMM OOO OOO SSSS SSS EEEEE /////////
//////// HHHH HHHH EEEEE MMMM MMMMMM MMMM OOO OOO SSSS EEEEE /////////
//////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSSSSSS EEEEE /////////
//////// HHHHHHHHHHHHHHHH EEEEEEEEEEE MMMM MMMM OOO OOO SSSSSS EEEEEEEEEEE /////////
//////// HHHHHHHHHHHHHHHH EEEEEEEEEEE MMMM MMMM OOO OOO SSSSSSS EEEEEEEEEEE /////////
//////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSSS EEEEE /////////
//////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSS SSSS EEEEE /////////
//////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOO OOO SSS SSSS EEEEEEEEEEEEE /////////
//////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOOOOO SSSSSSS EEEEEEEEEEEEE /////////
//////// /////////
//////// /////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static int[] memo, a;
static int[] nxt;
static int limit, n;
static int dp(int i) {
if (i == n)
return 0;
if (memo[i] != -2 * n)
return memo[i];
int ans = 0;
ans = Math.max(ans, (a[i] >= limit ? 1 : -1) + dp(i + 1));
return memo[i] = ans;
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
n = sc.nextInt();
int k = sc.nextInt();
a = sc.nextIntArr(n);
memo = new int[n];
int low = 1;
int hi = n;
int res = 1;
while (low <= hi) {
int mid = low + hi >> 1;
limit = mid;
for (int i = 0; i < n; i++)
memo[i] = -2 * n;
int[] suf = new int[n + 1];
boolean ans = false;
for (int i = n - 1; i >= 0; i--) {
suf[i] += suf[i + 1] + (a[i] >= limit ? 1 : -1);
if (i + k <= n) {
int cur = suf[i] - suf[i + k];
cur += dp(i + k);
if (cur > 0) {
ans = true;
break;
}
}
}
if (ans) {
low = mid + 1;
res = mid;
} else hi = mid - 1;
}
pw.println(res);
pw.flush();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int[] nextIntArr(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 8
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
f6d4cb7772f0e003a247efd27ff39426
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
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.*;
/*
getOrDefault
valueOf
char[] arr=st.nextToken().toCharArray();
System.out.println();
List<Integer> l=new ArrayList<>();
List<int[]> l=new ArrayList<>();
Set<Integer> set=new HashSet<>();
Map<Integer,Integer> map=new HashMap<>();
Map<Integer,List<Integer>> map=new HashMap<>();
for(int i=1;i<=n;i++) map.put(i,new ArrayList<>());
Map<Integer,List<int[]>> map=new HashMap<>();
Deque<Integer> d=new ArrayDeque<>();
PriorityQueue<Integer> pq=new PriorityQueue<>();
st = new StringTokenizer(infile.readLine());
int x=Integer.parseInt(st.nextToken());
int y=Integer.parseInt(st.nextToken());
int z=Integer.parseInt(st.nextToken());
*/
public class Solution{
//static int[][] dir={{0,1},{0,-1},{1,0},{-1,0}};
//static Map<Integer,Integer> map=new HashMap<>();
//static Map<Integer,List<Integer>> map=new HashMap<>();
//static Map<Integer,List<int[]>> map=new HashMap<>();
//static List<int[]> l=new ArrayList<>();
//static List<Integer> l=new ArrayList<>();
//static PriorityQueue<Integer> pq=new PriorityQueue<>();
//static Deque<Integer> d=new ArrayDeque<>();
//static Set<Integer> set=new HashSet<>();
//static StringBuilder sb=new StringBuilder();
static BufferedReader infile;
static StringTokenizer st;
static int n;static int k;
static int[] a;
static int[] b;
static int[] preb;
public static void main(String []args) throws Exception
{
/*
infile = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(infile.readLine());
int T=Integer.parseInt(st.nextToken());
for(int zz=1;zz<=T;zz++) solve(zz);
*/
solve();
}
public static void solve() throws Exception{
infile = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(infile.readLine());
n=Integer.parseInt(st.nextToken());
k=Integer.parseInt(st.nextToken());
a=new int[n+1]; b=new int[n+1]; preb=new int[n+1];
st = new StringTokenizer(infile.readLine());
for(int i=1;i<=n;i++) a[i]=Integer.parseInt(st.nextToken());
int lo=1; int hi=200000;
while(lo<hi){
int mid=(lo+hi+1)/2;
if(valid(mid)) lo=mid;
else hi=mid-1;
}
System.out.println(lo);
}
public static boolean valid(int mid){
for(int i=0;i<=n;i++){
b[i]=0; preb[i]=0;
}
b[1] = a[1]>=(mid)?1:-1;
for(int i=1;i<=n;i++){
int x=a[i]>=(mid)?1:-1;
preb[i]=preb[i-1]+x;
b[i]=Math.min(preb[i],b[i-1]);
if(i>=k){
if(preb[i]-b[i-k]>0){
if(mid==1) System.out.println(i+" "+preb[i]+" "+b[i-k]);
return true;
}
}
}
return false;
}
/*
public static void solve(int zz) throws Exception{
st = new StringTokenizer(infile.readLine());
int n=Integer.parseInt(st.nextToken());
int m=Integer.parseInt(st.nextToken());
//char[] arr=st.nextToken().toCharArray();
System.out.println("Case #"+zz+": "+res);
}
*/
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 17
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
228c9a2a957845d3a0dad5cb2fba6ec7
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.util.*;
public class MaxMedian {
public static void main(String... strings) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int k = scanner.nextInt();
int[] a = new int[n];
for(int i = 0 ;i < n;i++){
a[i]=scanner.nextInt();
}
solve(k,n,a);
}
public static void solve(int k, int n, int[] a) {
int l = 1;
int r = n+1 ;
while(r!=l+1){
/*System.out.println("r "+ r);
System.out.println("l "+ l);*/
int m = (r+l)/2;
//System.out.println("m : "+m);
int []b = new int [n];
for(int i=0;i<n;i++){
if(a[i]>=m){
b[i]=1;
}else{
b[i]=-1;
}
}
for(int i=1;i<n;i++){
b[i]+=b[i-1];
}
/*for(int i=0;i<n;i++){
System.out.print("b[i] " +bb[i]);
}
System.out.println();*/
int min=0;
int max=b[k-1];
for(int i=k;i<n;i++){
min=Math.min(b[i-(k)], min);
//System.out.println("j "+j +" b[j] "+b[j]);
max=Math.max(max, b[i]-min);
}
if(max>0){
l=m;
}else{
r=m;
}
}
System.out.println(l);
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
331dbace4c20b5163bc80601ecb7dcf3
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
import java.util.zip.CheckedInputStream;
public class MaxMedian {
static boolean isMedian(int[] arr, int median, int k, int n) {
int[] diff = new int[n];
int[] prefix = new int[n + 1];
for(int i = 0; i < n; ++i)
if(median <= arr[i]) diff[i] = 1;
else diff[i] = -1;
for(int i = 1; i <= n; ++i)
prefix[i] = prefix[i - 1] + diff[i - 1];
int min = Integer.MAX_VALUE;
for(int i = k; i <= n; ++i) {
min = Math.min(min, prefix[i - k]);
if(prefix[i] - min > 0)
return true;
}
return false;
}
public static void main(String[] args) {
FastScanner fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int n = fs.nextInt(), k = fs.nextInt();
int[] arr = fs.readArray(n);
int l = 1, r = n;
int ans = 1;
while(l <= r) {
int m = (l + r) / 2;
if(isMedian(arr, m, k, n)) {
ans = m;
l = m + 1;
} else {
r = m - 1;
}
}
System.out.println(ans);
}
static void ruffleSort(int[] a) {
int n = a.length;
Random r = new Random();
for(int i = 0; i < a.length; ++i) {
int oi = r.nextInt(n), t = a[i];
a[i] = a[oi];
a[oi] = t;
}
Arrays.sort(a);
}
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());
}
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
f854e43dbb99cdc87101e071858082ea
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
import java.util.zip.CheckedInputStream;
public class MaxMedian {
static boolean isMedian(int[] arr, int median, int k, int n) {
int[] diff = new int[n];
int[] prefix = new int[n + 1];
for(int i = 0; i < n; ++i)
if(median <= arr[i]) diff[i] = 1;
else diff[i] = -1;
for(int i = 1; i <= n; ++i)
prefix[i] = prefix[i - 1] + diff[i - 1];
int min = 0;
for(int i = k; i <= n; ++i) {
min = Math.min(min, prefix[i - k]);
if(prefix[i] - min > 0)
return true;
}
return false;
}
public static void main(String[] args) {
FastScanner fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int n = fs.nextInt(), k = fs.nextInt();
int[] arr = fs.readArray(n);
int l = 1, r = n;
int ans = 1;
while(l <= r) {
int m = (l + r) / 2;
if(isMedian(arr, m, k, n)) {
ans = m;
l = m + 1;
} else {
r = m - 1;
}
}
System.out.println(ans);
}
static void ruffleSort(int[] a) {
int n = a.length;
Random r = new Random();
for(int i = 0; i < a.length; ++i) {
int oi = r.nextInt(n), t = a[i];
a[i] = a[oi];
a[oi] = t;
}
Arrays.sort(a);
}
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());
}
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
263747c89686a51528f62bf98d7af3ac
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.util.Scanner;
public class G_PRO {
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
//所有数组都从1开始
int n = cin.nextInt();
int k = cin.nextInt();
int[] a = new int[n + 1];
int maxValue = 0;
for (int i = 1; i <= n; i++) {
a[i] = cin.nextInt();
maxValue = Math.max(a[i], maxValue);
}
int[] b = new int[n + 1];
int[] sum = new int[n + 1];
int min = 0, max = maxValue, x = maxValue;
boolean ok;
while (max - min > 1) {
ok = false;
int minSumj = 0;
for (int j = 1; j <= n && !ok; j++) {
if (a[j] >= x)
b[j] = 1;
else b[j] = -1;
sum[j] = sum[j - 1] + b[j];
if (j >= k) {
minSumj = Math.min(sum[j - k], minSumj);
ok = (sum[j] - minSumj > 0);
}
}
if (ok) {
min = x;
x = (max + min) / 2;
} else {
max = x;
x = (max + min) / 2;
}
}
System.out.println(x);
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
3a3cd575a72d232107c6ec4888e61e8f
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
//package credit;
import java.io.*;
import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class x{
static boolean v[];
static int ans[];
int size[];
static int count=0;
static int dsu=0;
static int c=0;
static int e9=1000000007;
int min=Integer.MAX_VALUE;
int max=Integer.MIN_VALUE;
long max1=Long.MIN_VALUE;
long min1=Long.MAX_VALUE;
boolean aBoolean=true;
boolean y=false;
long m=0;
static boolean t1=false;
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
int parent[];
int rank[];
int n=0;
ArrayList<ArrayList<Integer>> arrayLists;
boolean v1[];
static boolean t2=false;
boolean r=false;
int fib[];
int fib1[];
int ind[];
int min3=Integer.MAX_VALUE;
public static void main(String[] args) throws IOException {
x g = new x();
g.go();
}
public void go() throws IOException {
FastReader scanner = new FastReader();
// Scanner scanner = new Scanner(System.in);
// BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(System.in));
// String s;
PrintWriter printWriter = new PrintWriter(System.out);
int t =1;
for (int i = 0; i < t; i++) {
int n=scanner.nextInt();
int k=scanner.nextInt();
long arr[]=new long[n];
//0 1 2 3 4 5 6 7 8 9
for (int j =0; j <n; j++) {
arr[j]=scanner.nextLong();
}
int s=1;
int e=n;
int max=Integer.MIN_VALUE;
int ans1=0;
while(s<=e){
int m=(s+(e-s)/2);
int y=0;
int min=Integer.MAX_VALUE;
boolean r=false;
long ans[]=new long[n+1];
for(int j = 0; j < n; j++) {
if (arr[j] >= m) {
y += 1;
} else {
y += (-1);
}
ans[j+1]=y;
}
for (int j =k; j <=n; j++) {
min = (int) Math.min(min, ans[j - (k)]);
if(ans[j]-min>=1){
r=true;
break;
}
}
if(r){
ans1=m;
s=m+1;
}else{
e=m-1;
}
}
printWriter.println(ans1);
}
printWriter.flush();
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
a6ef5526a7fabe3f626de235850dd7d0
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Random;
import java.util.StringTokenizer;
public final class D {
public static void main(String[] args) {
final FastScanner fs = new FastScanner();
final int n = fs.nextInt();
final int k = fs.nextInt();
final int[] arr = fs.nextIntArray(n);
int lo = 1;
int hi = n;
while (lo < hi) {
final int mid = (lo + hi + 1) >>> 1;
final int[] pre = new int[n + 1];
final int[] minPre = new int[n + 1];
for (int i = 1; i <= n; i++) {
pre[i] = pre[i - 1] + (arr[i - 1] >= mid ? 1 : -1);
minPre[i] = Math.min(minPre[i - 1], pre[i]);
}
boolean ok = false;
for (int i = k; i <= n; i++) {
if (pre[i] > minPre[i - k]) {
ok = true;
break;
}
}
if (!ok) {
hi = mid - 1;
} else {
lo = mid;
}
}
System.out.println(lo);
}
static final class Utils {
public static void shuffleSort(int[] x) {
shuffle(x);
Arrays.sort(x);
}
public static void shuffleSort(long[] x) {
shuffle(x);
Arrays.sort(x);
}
public 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);
}
}
public 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);
}
}
public static void swap(int[] x, int i, int j) {
final int t = x[i];
x[i] = x[j];
x[j] = t;
}
public static void swap(long[] x, int i, int j) {
final long t = x[i];
x[i] = x[j];
x[j] = t;
}
private Utils() {}
}
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
private String next() {
while (!st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
//noinspection CallToPrintStackTrace
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
int[] nextIntArray(int n) {
final int[] a = new int[n];
for (int i = 0; i < n; i++) { a[i] = nextInt(); }
return a;
}
long[] nextLongArray(int n) {
final long[] a = new long[n];
for (int i = 0; i < n; i++) { a[i] = nextLong(); }
return a;
}
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
921d7fccc3e012c9e6a9c2fe4ab3fb63
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Random;
import java.util.StringTokenizer;
public final class D {
public static void main(String[] args) {
final FastScanner fs = new FastScanner();
final int n = fs.nextInt();
final int k = fs.nextInt();
final int[] arr = fs.nextIntArray(n);
int lo = 1;
int hi = n;
while (lo < hi) {
final int mid = (lo + hi + 1) >>> 1;
final int[] pre = new int[n + 1];
final int[] minPre = new int[n + 1];
for (int i = 1; i <= n; i++) {
pre[i] = pre[i - 1] + (arr[i - 1] >= mid ? 1 : -1);
minPre[i] = Math.min(minPre[i - 1], pre[i]);
}
boolean ok = false;
for (int i = k; i <= n; i++) {
if (pre[i] > minPre[i - k]) {
ok = true;
break;
}
}
if (!ok) {
hi = mid - 1;
} else {
lo = mid;
}
}
System.out.println(lo);
}
static final class Utils {
public static void shuffleSort(int[] x) {
shuffle(x);
Arrays.sort(x);
}
public static void shuffleSort(long[] x) {
shuffle(x);
Arrays.sort(x);
}
public 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);
}
}
public 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);
}
}
public static void swap(int[] x, int i, int j) {
final int t = x[i];
x[i] = x[j];
x[j] = t;
}
public static void swap(long[] x, int i, int j) {
final long t = x[i];
x[i] = x[j];
x[j] = t;
}
private Utils() {}
}
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
private String next() {
while (!st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
//noinspection CallToPrintStackTrace
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
int[] nextIntArray(int n) {
final int[] a = new int[n];
for (int i = 0; i < n; i++) { a[i] = nextInt(); }
return a;
}
long[] nextLongArray(int n) {
final long[] a = new long[n];
for (int i = 0; i < n; i++) { a[i] = nextLong(); }
return a;
}
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
e226d72b00f09d9333a87a7ac512f4f2
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class MaxMedian {
static int n, k;
static int[] arr;
public static void main(String[] args) throws IOException{
BufferedReader file = new BufferedReader(new InputStreamReader(System.in));
//BufferedReader file = new BufferedReader(new FileReader("MaxMedian.in"));
//PrintWriter outfile = new PrintWriter (new BufferedWriter(new FileWriter("MaxMedian.out")));
StringTokenizer st = new StringTokenizer(file.readLine());
n = Integer.parseInt(st.nextToken());
k = Integer.parseInt(st.nextToken());
arr = new int[n];
st = new StringTokenizer(file.readLine());
for (int i=0; i<n; i++){
arr[i] = Integer.parseInt(st.nextToken());
}
int low = 0;
int high = (int)1e9;
while (low < high){
int mid = (low + high + 1)/2;
if (check(mid)){
low = mid;
}else{
high = mid-1;
}
}
System.out.println(low);
}
public static boolean check(int med){
long[] b = new long[n]; // -1 or 1
for (int i=0; i<n; i++){
b[i] = (arr[i] >= med) ? 1 : -1;
}
// Try to find the largest subarray sum with length at least k
long[] ps = new long[n+1]; // Prefix sum
long[] minPrefix = new long[n+1]; // Tracks the min prefix sums up to index i
long max = Long.MIN_VALUE;
for (int i=0; i<n; i++){
ps[i+1] = (long)(ps[i] + b[i]);
minPrefix[i+1] = Math.min(minPrefix[i], ps[i+1]);
if (i >= k-1){
max = Math.max(max, ps[i+1]);
}
if (i >= k){
// We have enough in our "window" to subtract out some elements
if (minPrefix[i-k+1] < 0){
max = Math.max(max, (long)(ps[i+1]-minPrefix[i-k+1]));
}
}
}
return max > 0;
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
37db6203acb48d813abe94ad239988e6
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.util.Arrays;
import java.util.Scanner;
public class D {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
int k = scn.nextInt();
int[] arr = new int[n];
int[] sortedArr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = scn.nextInt();
sortedArr[i] = arr[i] ;
}
Arrays.sort(sortedArr);
if (k == 1) {
System.out.println(sortedArr[n - 1]);
return;
}
int low = 0;
int high = n - 1;
while (low <= high) {
int mid = (low + high) >>> 1;
if (isAtleast(sortedArr[mid], arr, k))
low = mid + 1;
else
high = mid - 1;
}
System.out.println(sortedArr[high]);
}
static boolean isAtleast(int value, int[] arr, int k) {
int[] a = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
if (arr[i] >= value)
a[i] = 1;
else
a[i] = -1;
}
long ans = maxSegmentWithK(a, k);
return ans >= 1;
}
static long maxSegmentWithK(int[] arr, int k) {
long[] prefixMaxSum = new long[arr.length];
long maxSum = 0;
for (int i = 0; i < arr.length; i++) {
maxSum = Long.max(maxSum + arr[i], arr[i]);
prefixMaxSum[i] = maxSum;
}
long kSum = 0;
for (int i = 0; i < k; i++) kSum += arr[i];
long globalMax = kSum;
for (int i = k; i < arr.length; i++) {
kSum += arr[i] - arr[i - k];
globalMax = Long.max(globalMax, kSum + prefixMaxSum[i - k]);
globalMax = Long.max(globalMax, kSum);
}
return globalMax;
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
174bde41f15b1ea14d63351f859f56ca
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.io.*;
import java.util.*;
import java.math.*;
public class Main {
static int bs(int start,int end,int[] l,int k) {
// System.out.println(start+" "+end);
if(end<start) {
return -1000000000;
}
int mid=(start+end)/2;
int n=l.length;
int[] temp=new int[n];
int[] mn=new int[n+1];
int mx=-1000000000;
int sum=0;
boolean flag=false;
for(int i=0;i<n;i++) {
if(l[i]>=mid) {
temp[i]=1;
}
else{
temp[i]=-1;
}
// System.out.print(temp[i]+" ");
}
// System.out.println();
// System.out.print(mn[1]+" ");
for(int i=0;i<n;i++) {
sum+=temp[i];
mn[i+1]=Math.min(mn[i],sum);
if ((i-k+1)>-1) {
mx=Math.max(mx,sum-mn[i-k+1]);
}
// System.out.print(mn[i+1]+" ");
}
// System.out.println();
// System.out.println(mx);
if(mx>0) {
flag=true;
}
if(flag) {
return Math.max(mid, bs(mid+1,end,l,k));
}
else {
return bs(start,mid-1,l,k);
}
}
public static void main(String[] args) throws IOException
{
FastScanner f = new FastScanner();
int t=1;
// t=f.nextInt();
PrintWriter out=new PrintWriter(System.out);
int mod=1000000007;
while(t>0) {
t--;
int n=f.nextInt();
int k=f.nextInt();
int[] l=f.readArray(n);
System.out.println(bs(1,n,l,k));
}
out.close();
}
static void sort(int [] a) {
ArrayList<Integer> q = new ArrayList<>();
for (int i: a) q.add(i);
Collections.sort(q);
for (int i = 0; i < a.length; i++) a[i] = q.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());
}
long[] readLongArray(int n) {
long[] a=new long[n];
for (int i=0; i<n; i++) a[i]=nextLong();
return a;
}
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
fee1f85940a2623df3e3ef0aef7bdb82
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.io.*;
import java.util.*;
import java.math.*;
public class Main {
static int bs(int start,int end,int[] l,int k) {
// System.out.println(start+" "+end);
if(end<start) {
return -1000000000;
}
int mid=(start+end)/2;
int n=l.length;
int[] temp=new int[n];
int[] mn=new int[n+1];
int mx=-1000000000;
int sum=0;
boolean flag=false;
for(int i=0;i<n;i++) {
if(l[i]>=mid) {
temp[i]=1;
}
else{
temp[i]=-1;
}
// System.out.print(temp[i]+" ");
}
// System.out.println();
mn[1]=Math.min(0, temp[0]);
sum=temp[0];
// mx=temp[0];
// System.out.print(mn[1]+" ");
for(int i=1;i<n;i++) {
sum+=temp[i];
mn[i+1]=Math.min(mn[i],sum);
if ((i-k+1)>-1) {
mx=Math.max(mx,sum-mn[i-k+1]);
}
// System.out.print(mn[i+1]+" ");
}
// System.out.println();
// System.out.println(mx);
if(mx>0) {
flag=true;
}
if(flag) {
return Math.max(mid, bs(mid+1,end,l,k));
}
else {
return bs(start,mid-1,l,k);
}
}
public static void main(String[] args) throws IOException
{
FastScanner f = new FastScanner();
int t=1;
// t=f.nextInt();
PrintWriter out=new PrintWriter(System.out);
int mod=1000000007;
while(t>0) {
t--;
int n=f.nextInt();
int k=f.nextInt();
int[] l=f.readArray(n);
if(n==1) {
System.out.println(l[0]);
}
else {
System.out.println(bs(1,n+1,l,k));
}
}
out.close();
}
static void sort(int [] a) {
ArrayList<Integer> q = new ArrayList<>();
for (int i: a) q.add(i);
Collections.sort(q);
for (int i = 0; i < a.length; i++) a[i] = q.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());
}
long[] readLongArray(int n) {
long[] a=new long[n];
for (int i=0; i<n; i++) a[i]=nextLong();
return a;
}
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
660de630b2a5596d6494af7b9ef3f03d
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.math.BigInteger;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map.Entry;
import java.util.PriorityQueue;
import java.util.Random;
import java.util.Scanner;
import java.util.TreeSet;
public final class CF_703_D2_D {
static boolean verb=true;
static void log(Object X){if (verb) System.err.println(X);}
static void log(Object[] X){if (verb) {for (Object U:X) System.err.print(U+" ");System.err.println("");}}
static void log(int[] X){if (verb) {for (int U:X) System.err.print(U+" ");System.err.println("");}}
static void log(int[] X,int L){if (verb) {for (int i=0;i<L;i++) System.err.print(X[i]+" ");System.err.println("");}}
static void log(long[] X){if (verb) {for (long U:X) System.err.print(U+" ");System.err.println("");}}
static void logWln(Object X){if (verb) System.err.print(X);}
static void info(Object o){ System.out.println(o);}
static void output(Object o){outputWln(""+o+"\n"); }
static void outputWln(Object o){try {out.write(""+ o);} catch (Exception e) {}}
// Global vars
static BufferedWriter out;
static InputReader reader;
static long powerMod(long b,long e,long m){
long x=1;
while (e>0) {
if (e%2==1)
x=(b*x)%m;
b=(b*b)%m;
e=e/2;
}
return x;
}
static void test() {
log("testing");
Random r=new Random();
int NTESTS=1000000000;
int NMAX=100;
//int MMAX=10000;
int VMAX=100;
for( int t=0;t<NTESTS;t++) {
}
log("done");
}
static int sign(int x) {
if (x>0)
return 1;
if (x==0)
return 0;
return -1;
}
static class Segment implements Comparable<Segment>{
int a;
int b;
public int compareTo(Segment X) {
if (a!=X.a)
return a-X.a;
if (b!=X.b)
return b-X.b;
return 0;
}
public Segment(int a, int b) {
this.a = a;
this.b = b;
}
}
static int order;
static int BYA=0;
static int BYB=1;
static class Composite implements Comparable<Composite>{
int v;
int idx;
public int compareTo(Composite X) {
if (v!=X.v)
return X.v-v;
return idx-X.idx;
}
public Composite(int v, int idx) {
this.v = v;
this.idx = idx;
}
public String toString() {
return "["+v+","+idx+"]";
}
}
static class BIT {
int[] tree;
int N;
BIT(int N){
tree=new int[N+1];
this.N=N;
}
void add(int idx,int val){
idx++;
while (idx<=N){
tree[idx]+=val;
idx+=idx & (-idx);
}
}
int read(int idx){
idx++;
int sum=0;
while (idx>0){
sum+=tree[idx];
idx-=idx & (-idx);
}
return sum;
}
}
static ArrayList<ArrayList<Integer>> generatePermutations(ArrayList<Integer> items){
ArrayList<ArrayList<Integer>> globalRes=new ArrayList<ArrayList<Integer>>();
if (items.size()>1) {
for (Integer item:items){
ArrayList<Integer> itemsTmp=new ArrayList<Integer>(items);
itemsTmp.remove(item);
ArrayList<ArrayList<Integer>> res=generatePermutations(itemsTmp);
for (ArrayList<Integer> list:res){
list.add(item);
}
globalRes.addAll(res);
}
}
else {
Integer item=items.get(0);
ArrayList<Integer> list=new ArrayList<Integer>();
list.add(item);
globalRes.add(list);
}
return globalRes;
}
static class Node {
int v;
int cn;
Node prev;
Node next;
public Node(int v, int cn) {
this.v = v;
this.cn = cn;
}
}
static boolean canDo(int v,int k,int[] a,int[] sum) {
//log("can Do:"+v);
int n=a.length;
int cur=0;
for (int i=0;i<n;i++) {
int b=-1;
if (a[i]>=v)
b=1;
cur+=b;
sum[i]=cur;
}
int[] max=new int[n];
int mx=-n;
int st=n-1;
for (int i=n-1;i>=0;i--) {
if (sum[i]>=mx) {
max[st--]=i;
mx=sum[i];
}
}
//log(b);
//log(sum);
//log(max);
int e=st+1;
//log("e:"+e+" n:"+n);
for (int i=0;i+k<=n;i++) {
while (e<n && max[e]<i+k-1)
e++;
if (e<n) {
int j=max[e];
int bob=sum[j];
if (i>0)
bob-=sum[i-1];
if (bob>0) {
//log("found with i:"+i+" j:"+j+" bob:"+bob);
//log("ok");
return true;
}
}
}
//log("ko");
return false;
}
static void process() throws Exception {
out = new BufferedWriter(new OutputStreamWriter(System.out));
reader=new InputReader(System.in);
Locale.setDefault(Locale.US);
int n=reader.readInt();
int k=reader.readInt();
int[] a=new int[n];
int[] b=new int[n];
for (int i=0;i<n;i++) {
a[i]=reader.readInt()-1;
b[i]=a[i];
}
Arrays.sort(b);
//log(b);
int pos=b[(n-1)/2];
int[] sum=new int[n];
int lo=pos;
int hi=n;
while (lo+1<hi) {
int mid=(lo+hi)/2;
boolean s=canDo(mid,k,a,sum);
if (s)
lo=mid;
else
hi=mid;
}
output(lo+1);
try {
out.close();
}
catch (Exception EX){}
}
public static void main(String[] args) throws Exception {
process();
}
static final class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
private int read() throws IOException {
if (curChar >= numChars) {
curChar = 0;
numChars = stream.read(buf);
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public final String readString() throws IOException {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res=new StringBuilder();
do {
res.append((char)c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public final int readInt() throws IOException {
int c = read();
boolean neg=false;
while (isSpaceChar(c)) {
c = read();
}
char d=(char)c;
//log("d:"+d);
if (d=='-') {
neg=true;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
//log("res:"+res);
if (neg)
return -res;
return res;
}
public final long readLong() throws IOException {
int c = read();
boolean neg=false;
while (isSpaceChar(c)) {
c = read();
}
char d=(char)c;
//log("d:"+d);
if (d=='-') {
neg=true;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
//log("res:"+res);
if (neg)
return -res;
return res;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
67357643a8029f9ad33684286ceab097
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.math.BigInteger;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map.Entry;
import java.util.PriorityQueue;
import java.util.Random;
import java.util.Scanner;
import java.util.TreeSet;
public final class CF_703_D2_D {
static boolean verb=true;
static void log(Object X){if (verb) System.err.println(X);}
static void log(Object[] X){if (verb) {for (Object U:X) System.err.print(U+" ");System.err.println("");}}
static void log(int[] X){if (verb) {for (int U:X) System.err.print(U+" ");System.err.println("");}}
static void log(int[] X,int L){if (verb) {for (int i=0;i<L;i++) System.err.print(X[i]+" ");System.err.println("");}}
static void log(long[] X){if (verb) {for (long U:X) System.err.print(U+" ");System.err.println("");}}
static void logWln(Object X){if (verb) System.err.print(X);}
static void info(Object o){ System.out.println(o);}
static void output(Object o){outputWln(""+o+"\n"); }
static void outputWln(Object o){try {out.write(""+ o);} catch (Exception e) {}}
// Global vars
static BufferedWriter out;
static InputReader reader;
static long powerMod(long b,long e,long m){
long x=1;
while (e>0) {
if (e%2==1)
x=(b*x)%m;
b=(b*b)%m;
e=e/2;
}
return x;
}
static void test() {
log("testing");
Random r=new Random();
int NTESTS=1000000000;
int NMAX=100;
//int MMAX=10000;
int VMAX=100;
for( int t=0;t<NTESTS;t++) {
}
log("done");
}
static int sign(int x) {
if (x>0)
return 1;
if (x==0)
return 0;
return -1;
}
static class Segment implements Comparable<Segment>{
int a;
int b;
public int compareTo(Segment X) {
if (a!=X.a)
return a-X.a;
if (b!=X.b)
return b-X.b;
return 0;
}
public Segment(int a, int b) {
this.a = a;
this.b = b;
}
}
static int order;
static int BYA=0;
static int BYB=1;
static class Composite implements Comparable<Composite>{
int v;
int idx;
public int compareTo(Composite X) {
if (v!=X.v)
return X.v-v;
return idx-X.idx;
}
public Composite(int v, int idx) {
this.v = v;
this.idx = idx;
}
public String toString() {
return "["+v+","+idx+"]";
}
}
static class BIT {
int[] tree;
int N;
BIT(int N){
tree=new int[N+1];
this.N=N;
}
void add(int idx,int val){
idx++;
while (idx<=N){
tree[idx]+=val;
idx+=idx & (-idx);
}
}
int read(int idx){
idx++;
int sum=0;
while (idx>0){
sum+=tree[idx];
idx-=idx & (-idx);
}
return sum;
}
}
static ArrayList<ArrayList<Integer>> generatePermutations(ArrayList<Integer> items){
ArrayList<ArrayList<Integer>> globalRes=new ArrayList<ArrayList<Integer>>();
if (items.size()>1) {
for (Integer item:items){
ArrayList<Integer> itemsTmp=new ArrayList<Integer>(items);
itemsTmp.remove(item);
ArrayList<ArrayList<Integer>> res=generatePermutations(itemsTmp);
for (ArrayList<Integer> list:res){
list.add(item);
}
globalRes.addAll(res);
}
}
else {
Integer item=items.get(0);
ArrayList<Integer> list=new ArrayList<Integer>();
list.add(item);
globalRes.add(list);
}
return globalRes;
}
static class Node {
int v;
int cn;
Node prev;
Node next;
public Node(int v, int cn) {
this.v = v;
this.cn = cn;
}
}
static boolean canDo(int v,int k,int[] a) {
//log("can Do:"+v);
int n=a.length;
int[] b=new int[n];
for (int i=0;i<n;i++) {
if (a[i]>=v)
b[i]=1;
else
b[i]=-1;
}
int[] sum=new int[n];
int cur=0;
for (int i=0;i<n;i++) {
cur+=b[i];
sum[i]=cur;
}
int[] max=new int[n];
int mx=-n;
int st=n-1;
for (int i=n-1;i>=0;i--) {
if (sum[i]>=mx) {
max[st--]=i;
mx=sum[i];
}
}
//log(b);
//log(sum);
//log(max);
int e=st+1;
//log("e:"+e+" n:"+n);
for (int i=0;i+k<=n;i++) {
while (e<n && max[e]<i+k-1)
e++;
if (e<n) {
int j=max[e];
int bob=sum[j];
if (i>0)
bob-=sum[i-1];
if (bob>0) {
//log("found with i:"+i+" j:"+j+" bob:"+bob);
//log("ok");
return true;
}
}
}
//log("ko");
return false;
}
static void process() throws Exception {
out = new BufferedWriter(new OutputStreamWriter(System.out));
reader=new InputReader(System.in);
Locale.setDefault(Locale.US);
int n=reader.readInt();
int k=reader.readInt();
int[] a=new int[n];
int[] b=new int[n];
for (int i=0;i<n;i++) {
a[i]=reader.readInt()-1;
b[i]=a[i];
}
Arrays.sort(b);
//log(b);
int pos=b[(n-1)/2];
int lo=pos;
int hi=n;
while (lo+1<hi) {
int mid=(lo+hi)/2;
boolean s=canDo(mid,k,a);
if (s)
lo=mid;
else
hi=mid;
}
output(lo+1);
try {
out.close();
}
catch (Exception EX){}
}
public static void main(String[] args) throws Exception {
process();
}
static final class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
private int read() throws IOException {
if (curChar >= numChars) {
curChar = 0;
numChars = stream.read(buf);
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public final String readString() throws IOException {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res=new StringBuilder();
do {
res.append((char)c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public final int readInt() throws IOException {
int c = read();
boolean neg=false;
while (isSpaceChar(c)) {
c = read();
}
char d=(char)c;
//log("d:"+d);
if (d=='-') {
neg=true;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
//log("res:"+res);
if (neg)
return -res;
return res;
}
public final long readLong() throws IOException {
int c = read();
boolean neg=false;
while (isSpaceChar(c)) {
c = read();
}
char d=(char)c;
//log("d:"+d);
if (d=='-') {
neg=true;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
//log("res:"+res);
if (neg)
return -res;
return res;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
b697a2ec13d28e7fd9f07a6cba0dbbef
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
/*
5 3
1 2 3 2 1
100 64
43 30 88 55 14 10 78 99 6 29 10 79 11 96 7 20 37 65 79 78 46 62 37 47 37 60 4 28 24 9 87 4 20 94 47 95 100 13 60 24 34 4 89 63 65 20 11 68 99 47 41 38 37 23 23 13 3 1 39 28 65 95 98 44 64 58 77 11 89 49 58 30 77 20 94 40 15 17 62 92 9 91 27 23 24 74 92 60 91 40 88 14 44 75 25 73 51 4 31 25
10 7
9 6 2 4 4 8 4 6 2 1
9 6 2 4 4 8 4 6
2 4 4 4 6 6 8 9
Bin search on the median, and then on the length of the subarray. Use prefix sums to determine if it is possible to create a subarray of len i with median j.
*/
import java.util.*;
import java.io.*;
public class Main {
public static int N;
public static int K;
public static int[] arr;
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer details = new StringTokenizer(br.readLine());
N = Integer.parseInt(details.nextToken());
K = Integer.parseInt(details.nextToken());
StringTokenizer a = new StringTokenizer(br.readLine());
arr = new int[N];
for(int x = 0; x < N; x++) arr[x] = Integer.parseInt(a.nextToken());
int min = 0;
int max = N;
while(min < max){
int mid = (min + max + 1)/2;
//System.out.println("\n" + min + " " + mid + " " + max);
if(valid(mid)) min = mid;
else max = mid - 1;
}
System.out.println(min);
br.close();
}
public static boolean valid(int median){
int[] min = new int[N + 1];
int[] a = new int[N + 1];
for(int x = 1; x <= N; x++){
if(arr[x - 1] >= median) a[x] = 1;
else a[x] = -1;
a[x] += a[x - 1];
min[x] = Math.min(a[x], min[x - 1]);
}
//System.out.println(Arrays.toString(arr));
//System.out.println(Arrays.toString(min));
// System.out.println(Arrays.toString(a));
for(int x = K; x <= N; x++){
//Want largest to be at least zero and the distance between start and x to be at least k
//System.out.println(a[x] + " " + min[x - K - 1] + " " + x + " " + (x - K - 1));
if(a[x] - min[x - K] >= 1) return true;
}
// System.out.println("----NOT POSSIBLE----");
return false;
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
39c45cbb134844197a23d176f5a5f105
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.util.*;
import java.lang.*;
import java.io.*;
import java.awt.*;
// U KNOW THAT IF THIS DAY WILL BE URS THEN NO ONE CAN DEFEAT U HERE................
//JUst keep faith in ur strengths ..................................................
// ASCII = 48 + i ;// 2^28 = 268,435,456 > 2* 10^8 // log 10 base 2 = 3.3219
// odd:: (x^2+1)/2 , (x^2-1)/2 ; x>=3// even:: (x^2/4)+1 ,(x^2/4)-1 x >=4
// FOR ANY ODD NO N : N,N-1,N-2
//ALL ARE PAIRWISE COPRIME
//THEIR COMBINED LCM IS PRODUCT OF ALL THESE NOS
// two consecutive odds are always coprime to each other
// two consecutive even have always gcd = 2 ;
// Rectangle r = new Rectangle(int x , int y,int widht,int height)
//Creates a rect. with bottom left cordinates as (x, y) and top right as ((x+width),(y+height))
//BY DEFAULT Priority Queue is MIN in nature in java
//to use as max , just push with negative sign and change sign after removal
// We can make a sieve of max size 1e7 .(no time or space issue)
// In 1e7 starting nos we have about 66*1e4 prime nos
// In 1e6 starting nos we have about 78,498 prime nos
public class Main
{
// static int[] arr = new int[100002] ;
// static int[] dp = new int[100002] ;
static PrintWriter out;
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br=new BufferedReader(new InputStreamReader(System.in));
out=new PrintWriter(System.out);
}
String next(){
while(st==null || !st.hasMoreElements()){
try{
st= new StringTokenizer(br.readLine());
}
catch (IOException e){
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt(){
return Integer.parseInt(next());
}
long nextLong(){
return Long.parseLong(next());
}
double nextDouble(){
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try{
str=br.readLine();
}
catch(IOException e){
e.printStackTrace();
}
return str;
}
}
////////////////////////////////////////////////////////////////////////////////////
public static int countDigit(long n)
{
return (int)Math.floor(Math.log10(n) + 1);
}
/////////////////////////////////////////////////////////////////////////////////////////
public static int sumOfDigits(long n)
{
if( n< 0)return -1 ;
int sum = 0;
while( n > 0)
{
sum = sum + (int)( n %10) ;
n /= 10 ;
}
return sum ;
}
//////////////////////////////////////////////////////////////////////////////////////////////////
public static long arraySum(int[] arr , int start , int end)
{
long ans = 0 ;
for(int i = start ; i <= end ; i++)ans += arr[i] ;
return ans ;
}
/////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
public static void swapArray(int[] arr , int start , int end)
{
while(start < end)
{
int temp = arr[start] ;
arr[start] = arr[end];
arr[end] = temp;
start++ ;end-- ;
}
}
//////////////////////////////////////////////////////////////////////////////////
static long factorial(long a)
{
if(a== 0L || a==1L)return 1L ;
return a*factorial(a-1L) ;
}
///////////////////////////////////////////////////////////////////////////////
public static int[][] rotate(int[][] input){
int n =input.length;
int m = input[0].length ;
int[][] output = new int [m][n];
for (int i=0; i<n; i++)
for (int j=0;j<m; j++)
output [j][n-1-i] = input[i][j];
return output;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////// ////////////////////////////////////////////////
public static boolean isPowerOfTwo(long n)
{
if(n==0)
return false;
if(((n ) & (n-1)) == 0 ) return true ;
else return false ;
}
/////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
public static String reverse(String input)
{
StringBuilder str = new StringBuilder("") ;
for(int i =input.length()-1 ; i >= 0 ; i-- )
{
str.append(input.charAt(i));
}
return str.toString() ;
}
///////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
public static boolean isPossibleTriangle(int a ,int b , int c)
{
if( a + b > c && c+b > a && a +c > b)return true ;
else return false ;
}
////////////////////////////////////////////////////////////////////////////////////////////
static long xnor(long num1, long num2) {
if (num1 < num2) {
long temp = num1;
num1 = num2;
num2 = temp;
}
num1 = togglebit(num1);
return num1 ^ num2;
}
static long togglebit(long n) {
if (n == 0)
return 1;
long i = n;
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
return i ^ n;
}
///////////////////////////////////////////////////////////////////////////////////////////////
public static int xorOfFirstN(int n)
{
if( n % 4 ==0)return n ;
else if( n % 4 == 1)return 1 ;
else if( n % 4 == 2)return n+1 ;
else return 0 ;
}
//////////////////////////////////////////////////////////////////////////////////////////////
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 int lcm(int a, int b ,int c , int d )
{
int temp = lcm(a,b , c) ;
int ans = lcm(temp ,d ) ;
return ans ;
}
///////////////////////////////////////////////////////////////////////////////////////////
public static int lcm(int a, int b ,int c )
{
int temp = lcm(a,b) ;
int ans = lcm(temp ,c) ;
return ans ;
}
////////////////////////////////////////////////////////////////////////////////////////
public static int lcm(int a , int b )
{
int gc = gcd(a,b);
return (a/gc)*b ;
}
public static long lcm(long a , long b )
{
long gc = gcd(a,b);
return (a/gc)*b;
}
///////////////////////////////////////////////////////////////////////////////////////////
static boolean isPrime(long n)
{
if(n==1)
{
return false ;
}
boolean ans = true ;
for(long i = 2L; i*i <= n ;i++)
{
if(n% i ==0)
{
ans = false ;break ;
}
}
return ans ;
}
static boolean isPrime(int n)
{
if(n==1)
{
return false ;
}
boolean ans = true ;
for(int i = 2; i*i <= n ;i++)
{
if(n% i ==0)
{
ans = false ;break ;
}
}
return ans ;
}
///////////////////////////////////////////////////////////////////////////
static int sieve = 1000000 ;
static boolean[] prime = new boolean[sieve + 1] ;
public static void sieveOfEratosthenes()
{
// FALSE == prime
// TRUE == COMPOSITE
// FALSE== 1
// time complexity = 0(NlogLogN)== o(N)
// gives prime nos bw 1 to N
for(int i = 4; i<= sieve ; i++)
{
prime[i] = true ;
i++ ;
}
for(int p = 3; p*p <= sieve; p++)
{
if(prime[p] == false)
{
for(int i = p*p; i <= sieve; i += p)
prime[i] = true;
}
p++ ;
}
}
///////////////////////////////////////////////////////////////////////////////////
public static void sortD(int[] arr , int s , int e)
{
sort(arr ,s , e) ;
int i =s ; int j = e ;
while( i < j)
{
int temp = arr[i] ;
arr[i] =arr[j] ;
arr[j] = temp ;
i++ ; j-- ;
}
return ;
}
/////////////////////////////////////////////////////////////////////////////////////////
public static long countSubarraysSumToK(long[] arr ,long sum )
{
HashMap<Long,Long> map = new HashMap<>() ;
int n = arr.length ;
long prefixsum = 0 ;
long count = 0L ;
for(int i = 0; i < n ; i++)
{
prefixsum = prefixsum + arr[i] ;
if(sum == prefixsum)count = count+1 ;
if(map.containsKey(prefixsum -sum))
{
count = count + map.get(prefixsum -sum) ;
}
if(map.containsKey(prefixsum ))
{
map.put(prefixsum , map.get(prefixsum) +1 );
}
else{
map.put(prefixsum , 1L );
}
}
return count ;
}
///////////////////////////////////////////////////////////////////////////////////////////////
// KMP ALGORITHM : TIME COMPL:O(N+M)
// FINDS THE OCCURENCES OF PATTERN AS A SUBSTRING IN STRING
//RETURN THE ARRAYLIST OF INDEXES
// IF SIZE OF LIST IS ZERO MEANS PATTERN IS NOT PRESENT IN STRING
public static ArrayList<Integer> kmpAlgorithm(String str , String pat)
{
ArrayList<Integer> list =new ArrayList<>();
int n = str.length() ;
int m = pat.length() ;
String q = pat + "#" + str ;
int[] lps =new int[n+m+1] ;
longestPefixSuffix(lps, q,(n+m+1)) ;
for(int i =m+1 ; i < (n+m+1) ; i++ )
{
if(lps[i] == m)
{
list.add(i-2*m) ;
}
}
return list ;
}
public static void longestPefixSuffix(int[] lps ,String str , int n)
{
lps[0] = 0 ;
for(int i = 1 ; i<= n-1; i++)
{
int l = lps[i-1] ;
while( l > 0 && str.charAt(i) != str.charAt(l))
{
l = lps[l-1] ;
}
if(str.charAt(i) == str.charAt(l))
{
l++ ;
}
lps[i] = l ;
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
// CALCULATE TOTIENT Fn FOR ALL VALUES FROM 1 TO n
// TOTIENT(N) = count of nos less than n and grater than 1 whose gcd with n is 1
// or n and the no will be coprime in nature
//time : O(n*(log(logn)))
public static void eulerTotientFunction(int[] arr ,int n )
{
for(int i = 1; i <= n ;i++)arr[i] =i ;
for(int i= 2 ; i<= n ;i++)
{
if(arr[i] == i)
{
arr[i] =i-1 ;
for(int j =2*i ; j<= n ; j+= i )
{
arr[j] = (arr[j]*(i-1))/i ;
}
}
}
return ;
}
/////////////////////////////////////////////////////////////////////////////////////////////
public static long nCr(int n,int k)
{
long ans=1L;
k=k>n-k?n-k:k;
int j=1;
for(;j<=k;j++,n--)
{
if(n%j==0)
{
ans*=n/j;
}else
if(ans%j==0)
{
ans=ans/j*n;
}else
{
ans=(ans*n)/j;
}
}
return ans;
}
///////////////////////////////////////////////////////////////////////////////////////////
public static ArrayList<Integer> allFactors(int n)
{
ArrayList<Integer> list = new ArrayList<>() ;
for(int i = 1; i*i <= n ;i++)
{
if( n % i == 0)
{
if(i*i == n)
{
list.add(i) ;
}
else{
list.add(i) ;
list.add(n/i) ;
}
}
}
return list ;
}
public static ArrayList<Long> allFactors(long n)
{
ArrayList<Long> list = new ArrayList<>() ;
for(long i = 1L; i*i <= n ;i++)
{
if( n % i == 0)
{
if(i*i == n)
{
list.add(i) ;
}
else{
list.add(i) ;
list.add(n/i) ;
}
}
}
return list ;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
static final int MAXN = 1000001;
static int spf[] = new int[MAXN];
static void sieve()
{
spf[1] = 1;
for (int i=2; i<MAXN; i++)
spf[i] = i;
for (int i=4; i<MAXN; i+=2)
spf[i] = 2;
for (int i=3; i*i<MAXN; i++)
{
if (spf[i] == i)
{
for (int j=i*i; j<MAXN; j+=i)
if (spf[j]==j)
spf[j] = i;
}
}
}
static ArrayList<Integer> getPrimeFactorization(int x)
{
ArrayList<Integer> ret = new ArrayList<Integer>();
while (x != 1)
{
ret.add(spf[x]);
x = x / spf[x];
}
return ret;
}
//////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////
public static void merge(int arr[], int l, int m, int r)
{
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
/* Create temp arrays */
int L[] = new int[n1];
int R[] = new int[n2];
//Copy data to temp arrays
for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];
/* Merge the temp arrays */
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarry array
int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
/* Copy remaining elements of L[] if any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
/* Copy remaining elements of R[] if any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
// Main function that sorts arr[l..r] using
// merge()
public static void sort(int arr[], int l, int r)
{
if (l < r)
{
// Find the middle point
int m = (l+r)/2;
// Sort first and second halves
sort(arr, l, m);
sort(arr , m+1, r);
// Merge the sorted halves
merge(arr, l, m, r);
}
}
public static void sort(long arr[], int l, int r)
{
if (l < r)
{
// Find the middle point
int m = (l+r)/2;
// Sort first and second halves
sort(arr, l, m);
sort(arr , m+1, r);
// Merge the sorted halves
merge(arr, l, m, r);
}
}
public static void merge(long arr[], int l, int m, int r)
{
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
/* Create temp arrays */
long L[] = new long[n1];
long R[] = new long[n2];
//Copy data to temp arrays
for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];
/* Merge the temp arrays */
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarry array
int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
/* Copy remaining elements of L[] if any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
/* Copy remaining elements of R[] if any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
/////////////////////////////////////////////////////////////////////////////////////////
public static long knapsack(int[] weight,long value[],int maxWeight){
int n= value.length ;
//dp[i] stores the profit with KnapSack capacity "i"
long []dp = new long[maxWeight+1];
//initially profit with 0 to W KnapSack capacity is 0
Arrays.fill(dp, 0);
// iterate through all items
for(int i=0; i < n; i++)
//traverse dp array from right to left
for(int j = maxWeight; j >= weight[i]; j--)
dp[j] = Math.max(dp[j] , value[i] + dp[j - weight[i]]);
/*above line finds out maximum of dp[j](excluding ith element value)
and val[i] + dp[j-wt[i]] (including ith element value and the
profit with "KnapSack capacity - ith element weight") */
return dp[maxWeight];
}
///////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
// to return max sum of any subarray in given array
public static long kadanesAlgorithm(long[] arr)
{
if(arr.length == 0)return 0 ;
long[] dp = new long[arr.length] ;
dp[0] = arr[0] ;
long max = dp[0] ;
for(int i = 1; i < arr.length ; i++)
{
if(dp[i-1] > 0)
{
dp[i] = dp[i-1] + arr[i] ;
}
else{
dp[i] = arr[i] ;
}
if(dp[i] > max)max = dp[i] ;
}
return max ;
}
/////////////////////////////////////////////////////////////////////////////////////////////
public static long kadanesAlgorithm(int[] arr)
{
if(arr.length == 0)return 0 ;
long[] dp = new long[arr.length] ;
dp[0] = arr[0] ;
long max = dp[0] ;
for(int i = 1; i < arr.length ; i++)
{
if(dp[i-1] > 0)
{
dp[i] = dp[i-1] + arr[i] ;
}
else{
dp[i] = arr[i] ;
}
if(dp[i] > max)max = dp[i] ;
}
return max ;
}
///////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
//TO GENERATE ALL(DUPLICATE ALSO EXIST) PERMUTATIONS OF A STRING
// JUST CALL generatePermutation( str, start, end) start :inclusive ,end : exclusive
//Function for swapping the characters at position I with character at position j
public static String swapString(String a, int i, int j) {
char[] b =a.toCharArray();
char ch;
ch = b[i];
b[i] = b[j];
b[j] = ch;
return String.valueOf(b);
}
//Function for generating different permutations of the string
public static void generatePermutation(String str, int start, int end)
{
//Prints the permutations
if (start == end-1)
System.out.println(str);
else
{
for (int i = start; i < end; i++)
{
//Swapping the string by fixing a character
str = swapString(str,start,i);
//Recursively calling function generatePermutation() for rest of the characters
generatePermutation(str,start+1,end);
//Backtracking and swapping the characters again.
str = swapString(str,start,i);
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
public static long factMod(long n, long mod) {
if (n <= 1) return 1;
long ans = 1;
for (int i = 1; i <= n; i++) {
ans = (ans * i) % mod;
}
return ans;
}
/////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////
public static long power(int a ,int b)
{
//time comp : o(logn)
long x = (long)(a) ;
long n = (long)(b) ;
if(n==0)return 1 ;
if(n==1)return x;
long ans =1L ;
while(n>0)
{
if(n % 2 ==1)
{
ans = ans *x ;
}
n = n/2L ;
x = x*x ;
}
return ans ;
}
public static long power(long a ,long b)
{
//time comp : o(logn)
long x = (a) ;
long n = (b) ;
if(n==0)return 1L ;
if(n==1)return x;
long ans =1L ;
while(n>0)
{
if(n % 2 ==1)
{
ans = ans *x ;
}
n = n/2L ;
x = x*x ;
}
return ans ;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
public static long powerMod(long x, long n, long mod) {
//time comp : o(logn)
if(n==0)return 1L ;
if(n==1)return x;
long ans = 1;
while (n > 0) {
if (n % 2 == 1) ans = (ans * x) % mod;
x = (x * x) % mod;
n /= 2;
}
return ans;
}
//////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
/*
lowerBound - finds largest element equal or less than value paased
upperBound - finds smallest element equal or more than value passed
if not present return -1;
*/
public static long lowerBound(long[] arr,long k)
{
long ans=-1;
int start=0;
int end=arr.length-1;
while(start<=end)
{
int mid=(start+end)/2;
if(arr[mid]<=k)
{
ans=arr[mid];
start=mid+1;
}
else
{
end=mid-1;
}
}
return ans;
}
public static int lowerBound(int[] arr,int k)
{
int ans=-1;
int start=0;
int end=arr.length-1;
while(start<=end)
{
int mid=(start+end)/2;
if(arr[mid]<=k)
{
ans=arr[mid];
start=mid+1;
}
else
{
end=mid-1;
}
}
return ans;
}
public static long upperBound(long[] arr,long k)
{
long ans=-1;
int start=0;
int end=arr.length-1;
while(start<=end)
{
int mid=(start+end)/2;
if(arr[mid]>=k)
{
ans=arr[mid];
end=mid-1;
}
else
{
start=mid+1;
}
}
return ans;
}
public static int upperBound(int[] arr,int k)
{
int ans=-1;
int start=0;
int end=arr.length-1;
while(start<=end)
{
int mid=(start+end)/2;
if(arr[mid]>=k)
{
ans=arr[mid];
end=mid-1;
}
else
{
start=mid+1;
}
}
return ans;
}
//////////////////////////////////////////////////////////////////////////////////////////
public static void printArray(int[] arr , int si ,int ei)
{
for(int i = si ; i <= ei ; i++)
{
out.print(arr[i] +" ") ;
}
}
public static void printArrayln(int[] arr , int si ,int ei)
{
for(int i = si ; i <= ei ; i++)
{
out.print(arr[i] +" ") ;
}
out.println() ;
}
public static void printLArray(long[] arr , int si , int ei)
{
for(int i = si ; i <= ei ; i++)
{
out.print(arr[i] +" ") ;
}
}
public static void printLArrayln(long[] arr , int si , int ei)
{
for(int i = si ; i <= ei ; i++)
{
out.print(arr[i] +" ") ;
}
out.println() ;
}
public static void printtwodArray(int[][] ans)
{
for(int i = 0; i< ans.length ; i++)
{
for(int j = 0 ; j < ans[0].length ; j++)out.print(ans[i][j] +" ");
out.println() ;
}
out.println() ;
}
static long modPow(long a, long x, long p) {
//calculates a^x mod p in logarithmic time.
a = a % p ;
if(a == 0)return 0L ;
long res = 1L;
while(x > 0) {
if( x % 2 != 0) {
res = (res * a) % p;
}
a = (a * a) % p;
x =x/2;
}
return res;
}
static long modInverse(long a, long p) {
//calculates the modular multiplicative of a mod p.
//(assuming p is prime).
return modPow(a, p-2, p);
}
static long[] factorial = new long[1000001] ;
static void modfac(long mod)
{
factorial[0]=1L ; factorial[1]=1L ;
for(int i = 2; i<= 1000000 ;i++)
{
factorial[i] = factorial[i-1] *(long)(i) ;
factorial[i] = factorial[i] % mod ;
}
}
static long modBinomial(long n, long r, long p) {
// calculates C(n,r) mod p (assuming p is prime).
if(n < r) return 0L ;
long num = factorial[(int)(n)] ;
long den = (factorial[(int)(r)]*factorial[(int)(n-r)]) % p ;
long ans = num*(modInverse(den,p)) ;
ans = ans % p ;
return ans ;
}
static void update(int val , long[] bit ,int n)
{
for( ; val <= n ; val += (val &(-val)) )
{
bit[val]++ ;
}
}
static long query(int val , long[] bit , int n)
{
long ans = 0L;
for( ; val >=1 ; val-=(val&(-val)) )ans += bit[val];
return ans ;
}
static int countSetBits(long n)
{
int count = 0;
while (n > 0) {
n = (n) & (n - 1L);
count++;
}
return count;
}
static int abs(int x)
{
if(x < 0)x = -1*x ;
return x ;
}
static long abs(long x)
{
if(x < 0)x = -1L*x ;
return x ;
}
////////////////////////////////////////////////////////////////////////////////////////////////
static void p(int val)
{
out.print(val) ;
}
static void p()
{
out.print(" ") ;
}
static void pln(int val)
{
out.println(val) ;
}
static void pln()
{
out.println() ;
}
static void p(long val)
{
out.print(val) ;
}
static void pln(long val)
{
out.println(val) ;
}
static void yes()
{
out.println("YES") ;
}
static void no()
{
out.println("NO") ;
}
////////////////////////////////////////////////////////////////////////////////////////////
// calculate total no of nos greater than or equal to key in sorted array arr
static int bs(int[] arr, int s ,int e ,int key)
{
if( s> e)return 0 ;
int mid = (s+e)/2 ;
if(arr[mid] <key)
{
return bs(arr ,mid+1,e , key) ;
}
else{
return bs(arr ,s ,mid-1, key) + e-mid+1;
}
}
// static ArrayList<Integer>[] adj ;
// static int mod= 1000000007 ;
static int[] arr ;
static int n,k ;
static boolean check(int m)
{
int[] temp = new int[n+1];
for(int i = 1 ; i <= n ;i++)
{
if(arr[i]>= m )temp[i] =1;
else temp[i] =-1 ;
}
int[] pre = new int[n+1] ;
pre[1] = temp[1] ;
for(int i = 2; i <= n ;i++)pre[i] = pre[i-1] + temp[i] ;
int[] min = new int[n+1] ;
min[1] = pre[1] ;
if(min[1] > 0)min[1] = 0 ;
for(int i= 2 ;i <= n ;i++)
{
min[i] = Math.min(min[i-1] ,pre[i]) ;
}
for(int i = k; i<= n ;i++)
{
if(pre[i] > min[i-k])return true ;
}
return false ;
}
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
public static void solve()
{
FastReader scn = new FastReader() ;
//Scanner scn = new Scanner(System.in);
//int[] store = {2 ,3, 5 , 7 ,11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 } ;
// product of first 11 prime nos is greater than 10 ^ 12;
//sieve() ;
//ArrayList<Integer> arr[] = new ArrayList[n] ;
ArrayList<Integer> list = new ArrayList<>() ;
ArrayList<Long> lista = new ArrayList<>() ;
ArrayList<Long> listb = new ArrayList<>() ;
// ArrayList<Integer> lista = new ArrayList<>() ;
// ArrayList<Integer> listb = new ArrayList<>() ;
//ArrayList<String> lists = new ArrayList<>() ;
HashMap<Integer,Integer> map = new HashMap<>() ;
//HashMap<Long,Long> map = new HashMap<>() ;
HashMap<Integer,Integer> mapx = new HashMap<>() ;
HashMap<Integer,Integer> mapy = new HashMap<>() ;
//HashMap<String,Integer> maps = new HashMap<>() ;
//HashMap<Integer,Boolean> mapb = new HashMap<>() ;
//HashMap<Point,Integer> point = new HashMap<>() ;
Set<Integer> set = new HashSet<>() ;
Set<Integer> setx = new HashSet<>() ;
Set<Integer> sety = new HashSet<>() ;
StringBuilder sb =new StringBuilder("") ;
//Collections.sort(list);
//if(map.containsKey(arr[i]))map.put(arr[i] , map.get(arr[i]) +1 ) ;
//else map.put(arr[i],1) ;
// if(map.containsKey(temp))map.put(temp , map.get(temp) +1 ) ;
// else map.put(temp,1) ;
//int bit =Integer.bitCount(n);
// gives total no of set bits in n;
// Arrays.sort(arr, new Comparator<Pair>() {
// @Override
// public int compare(Pair a, Pair b) {
// if (a.first != b.first) {
// return a.first - b.first; // for increasing order of first
// }
// return a.second - b.second ; //if first is same then sort on second basis
// }
// });
int testcase = 1;
//testcase = scn.nextInt() ;
for(int testcases =1 ; testcases <= testcase ;testcases++)
{
//if(map.containsKey(arr[i]))map.put(arr[i],map.get(arr[i])+1) ;else map.put(arr[i],1) ;
//if(map.containsKey(temp))map.put(temp,map.get(temp)+1) ;else map.put(temp,1) ;
//adj = new ArrayList[n] ;
// for(int i = 0; i< n; i++)
// {
// adj[i] = new ArrayList<Integer>();
// }
// long n = scn.nextLong() ;
//String s = scn.next() ;
n= scn.nextInt() ; k = scn.nextInt() ;
arr= new int[n+1] ;
for(int i=1; i <= n;i++)
{
arr[i]= scn.nextInt();
}
int l = 1; int r= n ; int ans = 1 ;
while(l<= r)
{
int m = (l+r)/2 ;
// out.println(l+" " + r+" " + m ) ;
if(check(m))
{
ans = m;
l=m+1 ;
}
else{
r =m-1 ;
}
}
out.println(ans) ;
//out.println(ans+" "+in) ;
//out.println("Case #" + testcases + ": " + ans ) ;
//out.println("@") ;
set.clear() ;
sb.delete(0 , sb.length()) ;
list.clear() ;lista.clear() ;listb.clear() ;
map.clear() ;
mapx.clear() ;
mapy.clear() ;
setx.clear() ;sety.clear() ;
} // test case end loop
out.flush() ;
} // solve fn ends
public static void main (String[] args) throws java.lang.Exception
{
solve() ;
}
}
class Pair
{
int first ;
int second ;
public Pair(int x, int y)
{
this.first = x ;this.second = y ;
}
@Override
public boolean equals(Object obj)
{
if(obj == this)return true ;
if(obj == null)return false ;
if(this.getClass() != obj.getClass())
{
return false ;
}
Pair other = (Pair)(obj) ;
if(this.first != other.first)return false ;
if(this.second != other.second)return false ;
return true ;
}
@Override
public int hashCode()
{
return this.first^this.second ;
}
@Override
public String toString() {
String ans = "" ;
ans += this.first ;
ans += " ";
ans += this.second ;
return ans ;
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
48d9fa37d60afd8ea45fff7a978c762e
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
// d
import java.util.*;
// import java.lang.*;
import java.io.*;
// THIS TEMPLATE MADE BY AKSH BANSAL.
public class Solution {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args) throws IOException {
FastReader sc = new FastReader();
PrintWriter out = new PrintWriter(System.out);
// ________________________________
// int t = sc.nextInt();
// StringBuilder output = new StringBuilder();
// while (t-- > 0) {
// int
// output.append(solver()).append("\n");
// }
// out.println(output);
// _______________________________
int n = sc.nextInt();
int k = sc.nextInt();
Integer[] arr =new Integer[n];
int low = Integer.MAX_VALUE;
int high = -1;
for(int i=0;i<n;i++){
arr[i] = sc.nextInt();
low = Math.min(low, arr[i]);
high = Math.max(high, arr[i]);
}
out.println(solver(n,k, arr, low, high));
// ________________________________
out.flush();
}
public static int solver(int len, int k, Integer[] arr, int low, int high) {
int start = low, end = high+1;
// System.out.println(low+"__"+ high);
while(start<end-1){
int mid = start+(end-start)/2;
int[] dp = new int[len+1];
int cur = 0;
boolean flag = true;
for(int i=0;i<len;i++){
cur+=mid>arr[i]?-1:1;
dp[i+1] = Math.min(dp[i],cur);
if(i>=k-1 && cur-dp[i-k+1]>0){
start = mid;
flag =false;
i = len;
}
}
if(flag)end = mid;
}
return start;
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
c431aebf51962325431e386815fbae3f
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class D {
private static PrintWriter out;
private static class FS {
StringTokenizer st;
BufferedReader br;
public FS() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public String next() {
while (st == null || !st.hasMoreElements()) {
try {st = new StringTokenizer(br.readLine());}
catch (IOException e) {e.printStackTrace();}
}
return st.nextToken();
}
public String nextLine() {
String s = null;
try {s = br.readLine();}
catch (IOException e) {e.printStackTrace();}
return s;
}
public int nextInt() {return Integer.parseInt(next());}
public long nextLong() {return Long.parseLong(next());}
public double nextDouble() {return Double.parseDouble(next());}
}
private static boolean ok(int[] a, int k, int m) {
int mx = 0, mn = 0, s2 = 0, s1 = 0;
for (int i = 0; i < a.length && mx <= 0; ++i) {
if (a[i] < m) --s2; else ++s2;
if (i >= k) {
if (a[i-k] < m) --s1; else ++s1;
if (mn > s1) mn = s1;
if (mx < s2 - mn) mx = s2 - mn;
}
}
if (mx < s2 - mn) mx = s2 - mn;
return mx > 0;
}
public static void main(String[] args) {
FS sc = new FS();
out = new PrintWriter(new BufferedOutputStream(System.out));
int n = sc.nextInt(), k = sc.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; ++i) a[i] = sc.nextInt();
int lo = 1, hi = n, m;
while (lo <= hi) {
m = lo + ((hi-lo)>>1);
if(ok(a,k,m)) lo = m+1;
else hi = m-1;
}
out.println(lo-1);
out.close();
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
fe1872d1a04d0cac006b6792a2c9e76c
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Solution {
static Reader input = new Reader();
static int n, k, t, r, sum, temp;
static int[] a, arr, leftSum, rightSum, maxRight, maxLeft;
public static void main(String[] args) throws IOException {
n = input.nextInt();
k = input.nextInt();
a = new int[n];
arr = new int[n];
leftSum = new int[n];
rightSum = new int[n];
maxRight = new int[n];
maxLeft = new int[n];
t = n-k;
for(int i = 0; i < n; ++i) a[i] = input.nextInt();
int left = min(a), right = max(a)+1, middle, answer = left;
while(left < right) {
middle = left+right>>1;
if(ok(middle)) {
answer = middle;
left = middle+1;
} else {
right = middle;
}
}
System.out.print(answer);
}
static boolean ok(int x) {
for(int i = 0; i < n; ++i) {
arr[i] = (a[i] >= x ? 1 : -1);
}
leftSum[0] = arr[0];
for(int i = 1; i < n; ++i) {
leftSum[i] = leftSum[i-1]+arr[i];
}
rightSum[n-1] = arr[n-1];
for(int i = n-2; i > -1; --i) {
rightSum[i] = rightSum[i+1]+arr[i];
}
maxLeft[0] = rightSum[0];
for(int i = 1; i < n; ++i) {
maxLeft[i] = Math.max(maxLeft[i-1], rightSum[i]);
}
maxRight[n-1] = leftSum[n-1];
for(int i = n-2; i > -1; --i) {
maxRight[i] = Math.max(maxRight[i+1], leftSum[i]);
}
for(int l = 0; l <= t; ++l) {
r = l+k-1;
sum = sum(l, r);
if(l > 0) {
temp = maxLeft[l-1]-rightSum[l];
sum += Math.max(0, temp);
}
if(r < n-1) {
temp = maxRight[r+1]-leftSum[r];
sum += Math.max(0, temp);
}
if(sum > 0) {
return true;
}
}
return false;
}
static int sum(int l, int r) {
if(l == 0) return leftSum[r];
return leftSum[r]-leftSum[l-1];
}
static int min(int[] a) {
int min = a[0];
for(int i = 1; i < a.length; ++i) {
if(min > a[i]) min = a[i];
}
return min;
}
static int max(int[] a) {
int max = a[0];
for(int i = 1; i < a.length; ++i) {
if(max < a[i]) max = a[i];
}
return max;
}
static class Reader {
BufferedReader bufferedReader;
StringTokenizer string;
public Reader() {
InputStreamReader inr = new InputStreamReader(System.in);
bufferedReader = new BufferedReader(inr);
}
public String next() throws IOException {
while(string == null || ! string.hasMoreElements()) {
string = new StringTokenizer(bufferedReader.readLine());
}
return string.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public String nextLine() throws IOException {
return bufferedReader.readLine();
}
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
993f043aad39efa4f677b2b7e82cc3b9
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Collections;
import java.util.StringTokenizer;
public class MaxMedianBinarySearch {
public static void main(String[] args) throws IOException {
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));//new FileReader("cowdance.in")
PrintWriter out = new PrintWriter(System.out);//new FileWriter("cowdance.out")
StringTokenizer st = new StringTokenizer(read.readLine());
int n = Integer.parseInt(st.nextToken());//Long.parseLong(st.nextToken());
int k = Integer.parseInt(st.nextToken());
int [] a = new int [n];
int [] b;
st = new StringTokenizer(read.readLine());
for (int i = 0; i < n; i++) {
a[i] = Integer.parseInt(st.nextToken());//Long.parseLong(st.nextToken());
}
int lo = 1;
int hi = n+1;
while (lo < hi-1) {
int mid = (lo+hi)/2;
b = new int [n];
for (int i = 0; i < n; i++) {
if (a[i] < mid) {
b[i] = -1;
}else {
b[i] = 1;
}
}
for (int i = 1; i < n; i++) {
b[i] += b[i-1];
}
boolean work = false;
int min = 0;
int max = b[k-1];
for (int i = k; i < n; i++) {
min = Math.min(min, b[i-k]);
max = Math.max(max, b[i]-min);
}
if (max >= 1) {
lo = mid;
} else {
hi = mid;
}
}
out.println(lo);
out.close();
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
8fb1265b98ff56437f64b6cf6a17f1e2
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class MaxMed2 {
public static void main(String[] args) throws IOException{
BufferedReader f=new BufferedReader(new InputStreamReader(System.in));
PrintWriter out=new PrintWriter(System.out);
StringTokenizer st=new StringTokenizer(f.readLine());
int n=Integer.parseInt(st.nextToken());
int k=Integer.parseInt(st.nextToken());
int[] arr=new int[n];
st=new StringTokenizer(f.readLine());
for(int i=0;i<n;i++) {
arr[i]=Integer.parseInt(st.nextToken());
}
int l=0;
int r=n;
while(l<r) {
int mid=(l+r+1)/2;
long[] pos=new long[n+1];
for(int i=1;i<=n;i++) {
pos[i]=arr[i-1]>=mid?1:-1;
pos[i]+=pos[i-1];
}
long max=pos[k];
long min=0;
for(int i=k+1;i<=n;i++) {
min=Math.min(min, pos[i-k]);
max=Math.max(max, pos[i]-min);
}
if(max>0) {
l=mid;
}
else {
r=mid-1;
}
}
out.println(l);
out.close();
f.close();
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
6f56dde4df78de423cc4c34417010e4f
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class _1486_D {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
StringTokenizer line = new StringTokenizer(in.readLine());
int n = Integer.parseInt(line.nextToken());
int k = Integer.parseInt(line.nextToken());
int[] a = new int[n];
line = new StringTokenizer(in.readLine());
for(int i = 0; i < n; i++) {
a[i] = Integer.parseInt(line.nextToken());
}
int l = 0;
int r = n;
int res = -1;
while(l <= r) {
int m = (l + r) / 2;
if(possible(a, k, m)) {
res = m;
l = m + 1;
}else {
r = m - 1;
}
}
out.println(res);
in.close();
out.close();
}
static boolean possible(int[] a, int k, int median) {
int[] min = new int[a.length];
int dif = 0;
for(int i = 0; i < a.length; i++) {
if(a[i] >= median) {
dif++;
}else {
dif--;
}
min[i] = Math.min(i > 0 ? min[i - 1] : 0, dif);
if(i - k + 1 >= 0) {
int prev = i - k >= 0 ? min[i - k] : 0;
if(dif - prev > 0) {
return true;
}
}
}
return false;
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
567ff306aa287ba3a6740072e462ca4b
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class CFMaxMedian1486
{
public static int n;
public static int k;
public static int[] array;
public static void main (String[] args) throws IOException
{
BufferedReader r= new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
StringTokenizer st = new StringTokenizer(r.readLine());
n = Integer.parseInt(st.nextToken());
k = Integer.parseInt(st.nextToken());
st = new StringTokenizer(r.readLine());
array = new int[n];
for(int i = 0; i < n; i++)
array[i] = Integer.parseInt(st.nextToken());
int lo = -1, hi = n+1, mid = (hi + lo)/2;
while(lo < mid && mid < hi)
{
if(valid(mid)) lo = mid;
else hi = mid;
mid = (hi + lo)/2;
}
r.close();
pw.println(lo);
pw.close();
}
public static boolean valid(int med)
{
int[] binArray = new int[n];
for(int i = 0; i < n; i++)
{
if(array[i] >= med)
binArray[i] = 1;
else
binArray[i] = -1;
}
int[] pArray = new int[n+1];
pArray[0] = 0;
for(int i = 1; i < n+1; i++)
pArray[i] = pArray[i-1] + binArray[i-1];
int[] minArray = new int[n+1];
minArray[0] = 0;
for(int i = 1; i < n+1; i++)
minArray[i] = Math.min(minArray[i-1], pArray[i]);
for(int i = k; i < n+1; i++)
{
if(pArray[i] - minArray[i-k] > 0)
return(true);
}
return(false);
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
aaa41bd0a8d4567ec7ebd6bbc74caa8d
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
//package Algorithm.BinarySearch.Important;
import java.util.Arrays;
import java.util.Scanner;
public class Max_Median {
static int n, k;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
n = scan.nextInt(); k = scan.nextInt();
int[] a = new int[n+1], b = new int[n+1];
for (int i = 1; i <= n; i++) {
a[i] = scan.nextInt();
b[i] = a[i];
}
Arrays.sort(b);
int ans = 0, L = 1, R = n;
while (L <= R) {
int mid = (L + R) / 2;
if (check(a, b[mid])) {
L = mid+1; ans = Math.max(ans, b[mid]);
} else R = mid - 1;
}
System.out.println(ans);
}
static boolean check(int[] a, int median) {
int[] temp = new int[n+1];
for (int i = 1; i <= n; i++) {
if (a[i] >= median) temp[i]++;
else temp[i]--;
temp[i] += temp[i - 1];
}
int curMin = Integer.MAX_VALUE;
for (int i = k; i <= n; i++) {
curMin = Math.min(curMin, temp[i-k]);
if (temp[i] - curMin > 0) return true;
}
return false;
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
1865ad47e0ddb331a70d0edab20d25f9
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class MaxMedian
{
static int n, k;
public static void main(String[] args) throws NumberFormatException, IOException
{
BufferedReader scan = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
String[] in = scan.readLine().split(" ");
n = parse(in[0]);
k = parse(in[1]);
long[] ray = new long[n];
in = scan.readLine().split(" ");
for(int i = 0; i < n; i++)
ray[i] = parse(in[i]);
long max = getMax(ray);
out.println(max);
out.flush();
}
private static long getMax(long[] ray)
{
long low = 1, high = (long) (2 * 1e5), mid;
long value = 0;
while(low <= high)
{
mid = (low + high) / 2;
if(valid(mid, ray))
{
value = Math.max(value, mid);
low = mid + 1;
}
else
high = mid - 1;
}
return value;
}
private static boolean valid(long target, long[] ray)
{
long[] rel = new long[n];
for(int i = 0; i < n; i++)
rel[i] = ray[i] >= target ? 1 : -1;
for(int i = 1; i < n; i++)
rel[i] = rel[i-1] + rel[i];
long min = 0;
if(rel[k-1] > 0) return true;
for(int i = k; i < n; i++)
{
min = Math.min(min, rel[i-k]);
if(rel[i] - min > 0) return true;
}
return false;
}
public static int parse(String num)
{
return Integer.parseInt(num);
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
c4d577da946d97e40a9926f32ca57005
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.InputMismatchException;
import java.util.*;
import java.io.*;
import java.lang.*;
public class Main{
public static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
}
catch (IOException e) {
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
public int nextInt() {
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static long gcd(long a, long b){
if (a == 0)
return b;
return gcd(b % a, a);
}
static long lcm(long a, long b) {
return (a*b)/gcd(a, b);
}
public static void sortbyColumn(int arr[][], int col)
{
Arrays.sort(arr, new Comparator<int[]>() {
@Override
public int compare(final int[] entry1,
final int[] entry2) {
if (entry1[col] > entry2[col])
return 1;
else
return -1;
}
});
}
static long func(long a[],int size,int s){
long max1=a[s];
long maxc=a[s];
for(int i=s+1;i<size;i++){
maxc=Math.max(a[i],maxc+a[i]);
max1=Math.max(maxc,max1);
}
return max1;
}
public static class Pair<U extends Comparable<U>, V extends Comparable<V>> implements Comparable<Pair<U, V>> {
public U x;
public V y;
public Pair(U x, V y) {
this.x = x;
this.y = y;
}
public int hashCode() {
return (x == null ? 0 : x.hashCode() * 31) + (y == null ? 0 : y.hashCode());
}
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Pair<U, V> p = (Pair<U, V>) o;
return (x == null ? p.x == null : x.equals(p.x)) && (y == null ? p.y == null : y.equals(p.y));
}
public int compareTo(Pair<U, V> b) {
int cmpU = x.compareTo(b.x);
return cmpU != 0 ? cmpU : y.compareTo(b.y);
}
public String toString() {
return String.format("(%s, %s)", x.toString(), y.toString());
}
}
static class MultiSet<U extends Comparable<U>> {
public int sz = 0;
public TreeMap<U, Integer> t;
public MultiSet() {
t = new TreeMap<>();
}
public void add(U x) {
t.put(x, t.getOrDefault(x, 0) + 1);
sz++;
}
public void remove(U x) {
if (t.get(x) == 1) t.remove(x);
else t.put(x, t.get(x) - 1);
sz--;
}
}
static void shuffle(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;
}
}
static long myceil(long a, long b){
return (a+b-1)/b;
}
static long C(long n,long r){
long count=0,temp=n;
long ans=1;
long num=n-r+1,div=1;
while(num<=n){
ans*=num;
//ans+=MOD;
ans%=MOD;
ans*=mypow(div,MOD-2);
//ans+=MOD;
ans%=MOD;
num++;
div++;
}
ans+=MOD;
return ans%MOD;
}
static long fact(long a){
long i,ans=1;
for(i=1;i<=a;i++){
ans*=i;
ans%=MOD;
}
return ans%=MOD;
}
static void sieve(int n){
is_sieve[0]=1;
is_sieve[1]=1;
int i,j,k;
for(i=2;i<n;i++){
if(is_sieve[i]==0){
sieve[i]=i;
tr.add(i);
for(j=i*i;j<n;j+=i){
if(j>n||j<0){
break;
}
is_sieve[j]=1;
sieve[j]=i;
}
}
}
}
static void calc(int n){
int i,j;
dp[n-1]=0;
if(n>1)
dp[n-2]=1;
for(i=n-3;i>=0;i--){
long ind=n-i-1;
dp[i]=((ind*(long)mypow(10,ind-1))%MOD+dp[i+1])%MOD;
}
}
static long mypow(long x,long y){
long temp;
if( y == 0)
return 1;
temp = mypow(x, y/2);
if (y%2 == 0)
return (temp*temp)%MOD;
else
return ((x*temp)%MOD*(temp)%MOD)%MOD;
}
static long dist[],dp[];
static int visited[];
static ArrayList<Pair<Integer,String>> adj[];
//static int dp[][][];
static int R,G,B,MOD=1000000007;
static int[] par,size,memo;
static int[] sieve,is_sieve;
static TreeSet<Integer> tr;
static char ch[][], ch1[][];
// static void lengen(int arr[],int ind){
// memo[ind]=Math.max(lengen(arr,ind+1),lis(arr,))
// }
static int lis(int arr[],int n,int ind,int cur){
if(ind>=n){
return memo[ind]=0;
}
else if(ind>=0&&memo[ind]>-1){
return memo[ind];
}
else if(cur<arr[ind+1]){
return memo[ind]=Math.max(lis(arr,n,ind+1,arr[ind+1])+1,lis(arr,n,ind+1,cur));
}else{
return memo[ind]=lis(arr,n,ind+1,cur);
}
}
public static void main(String args[]){
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter w = new PrintWriter(outputStream);
int t,i,j,tno=0,tte;
//t=in.nextInt();
t=1;
//tte=t;
while(t-->0){
int n=in.nextInt();
int k=in.nextInt();
int arr[]=new int[n];
for(i=0;i<n;i++){
arr[i]=in.nextInt();
}
int l=1,r=n;
int mid=(l+r)/2,ans=0;
while(l<=r){
int curmin = 0;
mid=(l+r)/2;
//w.println(l+" "+mid+" "+r);
int flag=0;
int temp[]=new int[n];
int pre[]=new int[n];
for(i=0;i<n;i++){
if(arr[i]<mid){
temp[i]=-1;
}else{
temp[i]=1;
}
if(i==0){
pre[i]=temp[i];
}else{
pre[i]=pre[i-1]+temp[i];
}
if(i>=(k-1)){
if(i == k-1) {
if(pre[i]-curmin>0){
l=mid+1;
ans=mid;
flag=1;
break;
}
}
else{
curmin = Math.min(curmin , pre[i-k]);
if(pre[i]-curmin>0){
l=mid+1;
ans=mid;
flag=1;
break;
}
}
}
}
if(flag==0){
r=mid-1;
}
// w.println(l+" "+mid+" "+r);
}
w.println(ans);
}
w.close();
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
a2815047eaf5627c81b33a37fbbc03fb
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.io.*;
import java.util.*;
@SuppressWarnings("unchecked")
public class MaxMedian implements Runnable {
void solve() throws IOException {
int len = read.intNext(), k = read.intNext();
int[] arr = iArr(len);
for(int i = 0; i < len; i++ ){
arr[i] = read.intNext();
}
int l = 1, h = len + 1;
while( h - l > 1){
int mid = (h + l)/2;
int[] b = iArr(len);
for(int i = 0; i < len; i++ ){
int curr = (arr[i] >= mid)? 1: -1;
b[i] += curr;
if( i != 0 ){
b[i] += b[i - 1];
}
}
int max = b[k - 1], min = 0;
for(int i = k; i < len; i++ ){
min = min(min, b[i - k]);
max = max( max, b[i] - min );
}
if( max > 0 ){
l = mid;
}else{
h = mid;
}
}
println(l);
}
/************************************************************************************************************************************************/
public static void main(String[] args) throws IOException {
new Thread(null, new MaxMedian(), "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 final class Comparators {
public static final Comparator<int[]> pairIntArr =
(x, y) -> x[0] == y[0] ? compare(x[1], y[1]) : compare(x[0], y[0]);
private static final int compare(final int x, final int y) {
return Integer.compare(x, y);
}
}
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);
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
d5b75ff9380ee69aa4f8b23c2e80b145
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Codeforces
{
public static void main(String args[])throws Exception
{
BufferedReader bu=new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb=new StringBuilder();
String s[]=bu.readLine().split(" ");
int n=Integer.parseInt(s[0]),k=Integer.parseInt(s[1]);
int a[]=new int[n],i; b=new int[n];
s=bu.readLine().split(" ");
for(i=0;i<n;i++)
a[i]=Integer.parseInt(s[i]);
int l=1,r=n,ans=-1,mid;
while(l<=r)
{
mid=(l+r)>>1;
if(possible(a,mid,k))
{
ans=mid;
l=mid+1;
}
else r=mid-1;
}
System.out.print(ans);
}
static int b[];
static boolean possible(int a[],int m,int k)
{
int i,n=a.length;
for(i=0;i<n;i++)
{
if(a[i]>=m) b[i]=1;
else b[i]=-1;
if(i>0) b[i]+=b[i-1];
}
int mx=b[k-1];
int mn=0;
for(i=k;i<n;i++)
{
mn=Math.min(mn,b[i-k]);
mx=Math.max(mx,b[i]-mn);
}
return mx>0;
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
177e14ed04e50bbb33be6f5636d81638
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.util.*;
import java.io.*;
//My life seems to be a joke. But, one day I will conquer.
public class B{
public static void main(String[] args)
{
FastScanner fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int n = fs.nextInt(); int k = fs.nextInt();
int[] arr = fs.readArray(n);
int left = 1;//good
int right = n+1;//bad
int[] temp = new int[n];
while(left+1<right)
{
int mid = (left+right)/2;
for(int i=0;i<n;i++)
{
if(arr[i]>=mid)
{
temp[i] = 1;
}
else
{
temp[i] = -1;
}
}
for(int i=1;i<n;i++)
{
temp[i] += temp[i-1];
}
int max = temp[k - 1];
int min = 0;
for (int i = k; i < n; ++i) {
min = Math.min(min,temp[i - k]);
max = Math.max(max, temp[i] - min);
}
if(max>0)
{
left = mid;
}
else
{
right = mid;
}
}
out.println(left);//bcoz left is the best!!
out.close();
}
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());
}
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
8ffcd55357f8fabfa08cb37ac76dde3b
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
public class problemD {
static class Solution {
void solve() {
int n = fs.nextInt();
int k = fs.nextInt();
int[] a = fs.readArray(n);
b = new int[n+1];
pre = new int[n+1];
min = new int[n+1];
int ans = 0;
for (int low = 1, high = n; low <= high; ) {
int mid = (low+high)/2;
if (possible(mid, a, k)) {
ans = Math.max(ans, mid);
low = mid+1;
} else {
high = mid-1;
}
}
out.println(ans);
}
int[] b;
int[] pre;
int[] min;
boolean possible(int x, int[] a, int k) {
int n = a.length;
pre[0] = 0;
min[0] = 0;
for (int i = 1; i <= n; i ++) {
b[i] = a[i-1] >= x ? 1 : -1;
pre[i] = pre[i-1]+b[i];
min[i] = Math.min(i == 0 ? Integer.MAX_VALUE : min[i-1], pre[i]);
if (i >= k && pre[i] - min[i-k] > 0) return true;
}
return false;
}
}
public static void main(String[] args) throws Exception {
int T = 1;
Solution solution = new Solution();
for (int t = 0; t < T; t++) solution.solve();
out.close();
}
static void debug(Object... O) {
System.err.println("DEBUG: " + Arrays.deepToString(O));
}
private static FastScanner fs = new FastScanner();
private static PrintWriter out = new PrintWriter(System.out);
static class FastScanner { // Thanks SecondThread.
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[] readLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
ArrayList<Integer> readArrayList(int n) {
ArrayList<Integer> a = new ArrayList<>(n);
for (int i = 0 ; i < n; i ++ ) a.add(fs.nextInt());
return a;
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextString() {
return next();
}
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
280995a8547d873b01cf66715e5fc548
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
/*
"Everything in the universe is balanced. Every disappointment
you face in life will be balanced by something good for you!
Keep going, never give up."
Just have Patience + 1...
*/
import java.util.*;
import java.lang.*;
import java.io.*;
public class Solution {
public static void main(String[] args) throws java.lang.Exception {
out = new PrintWriter(new BufferedOutputStream(System.out));
sc = new FastReader();
int test = 1;
for (int t = 1; t <= test; t++) {
solve();
}
out.close();
}
private static void solve() {
int n = sc.nextInt();
int k = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
int maxMedian = binarySearch(arr, n, k);
out.println(maxMedian);
}
private static int binarySearch(int[] arr, int n, int k) {
int low = 1, high = n;
int maxMedian = -1;
while (low <= high) {
int mid = (low + high) >> 1;
if (medianAtLeastRequired(arr, n, k, mid)) {
maxMedian = mid;
low = mid + 1;
}else {
high = mid - 1;
}
}
return maxMedian;
}
private static boolean medianAtLeastRequired(int[] arr, int n, int k, int requiredMedian) {
int[] assigned = new int[n];
for (int i = 0; i < n; i++) {
assigned[i] = arr[i] < requiredMedian ? -1 : 1;
}
for (int i = 1; i < n; i++) {
assigned[i] += assigned[i - 1];
}
int maxSubarraySum = assigned[k - 1], minPrefixSum = 0;
for (int i = k; i < n; i++) {
minPrefixSum = Math.min(minPrefixSum, assigned[i - k]);
maxSubarraySum = Math.max(maxSubarraySum, assigned[i] - minPrefixSum);
}
return maxSubarraySum > 0;
}
public static FastReader sc;
public static PrintWriter out;
static class FastReader
{
BufferedReader br;
StringTokenizer str;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (str == null || !str.hasMoreElements())
{
try
{
str = new StringTokenizer(br.readLine());
}
catch (IOException lastMonthOfVacation)
{
lastMonthOfVacation.printStackTrace();
}
}
return str.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 lastMonthOfVacation)
{
lastMonthOfVacation.printStackTrace();
}
return str;
}
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
ceca32490727141bc16b7d5fb8340bbe
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Codeforces {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//int cases = Integer.parseInt(br.readLine());
//o:while(cases-- > 0) {
String[] str = br.readLine().split(" ");
int n = Integer.parseInt(str[0]);
int k = Integer.parseInt(str[1]);
str = br.readLine().split(" ");
int a[] = new int[n];
for(int i=0; i<n; i++) {
a[i] = Integer.parseInt(str[i]);
}
int l = 1, r = n, ans = -1;
while(l <= r) {
int mid = l + (r - l)/2;
if(possible(a, mid, k)) {
ans = mid;
l = mid + 1;
}else {
r = mid - 1;
}
}
System.out.println(ans);
//}
}
public static boolean possible(int[] a, int m, int k) {
int n = a.length;
int b[] = new int[n];
for(int i=0; i<n; i++) {
if(a[i] >= m) {
b[i] = 1;
}else {
b[i] = -1;
}
if(i > 0) {
b[i] += b[i-1];
}
}
int max = b[k-1];
int min = 0;
for(int i=k; i<n; i++) {
min = Math.min(min, b[i-k]);
max = Math.max(max, b[i] - min);
}
return max > 0;
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
54fc785251a0b3326e08413dec5e5e8d
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
//package maxmedian;
import java.util.*;
import java.io.*;
public class maxmedian {
public static boolean isValid(int[] nums, int val, int k) {
TreeSet<Integer> before = new TreeSet<Integer>();
int sum = 0;
int beforeSum = 0;
for(int i = 0; i < k; i++) {
if(nums[i] >= val) {
sum ++;
}
else {
sum --;
}
}
before.add(0);
if(sum > 0) {
return true;
}
for(int i = k; i < nums.length; i++) {
beforeSum += nums[i - k] >= val? 1 : -1;
before.add(beforeSum);
sum += nums[i] >= val? 1 : -1;
if(before.floor(sum - 1) != null) {
return true;
}
}
return false;
}
public static void main(String[] args) throws IOException {
BufferedReader fin = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(fin.readLine());
int n = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken());
int[] nums = new int[n];
st = new StringTokenizer(fin.readLine());
for(int i = 0; i < n; i++) {
nums[i] = Integer.parseInt(st.nextToken());
}
int low = 0;
int high = n;
int ans = 0;
int mid = low + (high - low) / 2;
while(low <= high) {
//System.out.println(mid);
if(isValid(nums, mid, k)) {
ans = Math.max(ans, mid);
low = mid + 1;
}
else {
high = mid - 1;
}
mid = low + (high - low) / 2;
}
System.out.println(ans);
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
90ca87f0cf72f46c1f90b0b070605f73
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
public class Main {
private static void run() throws IOException {
int n = in.nextInt();
int k = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
int left = 1;
int right = n;
while (left < right) {
int mid = (left + right + 1) >> 1;
if (is_ok(mid, a, k)) {
left = mid;
} else {
right = mid - 1;
}
}
out.println(left);
}
private static boolean is_ok(int x, int[] a, int k) {
int[] b = new int[a.length];
for (int i = 0; i < a.length; i++) {
b[i] = a[i] >= x ? 1 : -1;
}
int[] sum = new int[a.length];
sum[0] = b[0];
for (int i = 1; i < a.length; i++) {
sum[i] = sum[i - 1] + b[i];
}
int min = 1000000;
for (int i = k - 1; i < a.length; i++) {
int max_count = Math.max(sum[i] - min, sum[i]);
if (max_count > 0) return true;
min = Math.min(min, sum[i - k + 1]);
}
return false;
}
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
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
3f28d5ee11a084ab1f4269a4d52ca453
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Main {
static BufferedReader rd = new BufferedReader(new InputStreamReader(System.in));
static BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(System.out));
static StringTokenizer tok;
public static void main(String[] args) throws Exception {
solution();
}
public static void solution() throws Exception {
tok = new StringTokenizer(rd.readLine());
int n = Integer.parseInt(tok.nextToken());
int k = Integer.parseInt(tok.nextToken());
tok = new StringTokenizer(rd.readLine());
int[] arr = new int[n];
int[] sorted_arr = new int[n];
for(int i=0;i<n;i++) {
arr[i] = Integer.parseInt(tok.nextToken());
sorted_arr[i] = arr[i];
}
Arrays.sort(sorted_arr);
int l = 1, r = n+1;
while(r - l > 1) {
int m = (l+r)/2 ;
int[] brr = new int[n];
for(int i=0;i<n;i++) {
if(arr[i] < m) brr[i] = -1;
else brr[i] = 1;
}
for(int i=1;i<n;i++) brr[i] = brr[i] + brr[i-1];
int min = 0, max = brr[k-1];
for(int i=k;i<n;i++) {
min = Math.min(min, brr[i-k]);
max = Math.max(max, brr[i] - min);
}
if(max > 0) l = m;
else r = m;
}
System.out.println(l);
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
d1ae4509311e654204f1e96f2305ca3a
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
/*
Codeforces
Problem 1486D
*/
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class MaxMedian {
public static void main(String[] args) throws IOException {
FastIO in = new FastIO(System.in);
int n = in.nextInt();
int k = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = in.nextInt();
int l = 1;
int r = n+1;
while (r - l > 1) {
int m = (l + r) / 2;
int[] b = new int[n];
for (int i = 0; i < n; i++) {
if (a[i] >= m) b[i] = 1;
else b[i] = -1;
if (i > 0) b[i] += b[i-1];
}
int max = b[k-1];
int min = 0;
for (int i = k; i < n; i++) {
min = Math.min(min, b[i-k]);
max = Math.max(max, b[i] - min);
}
if (max > 0) l = m;
else r = m;
}
System.out.println(l);
in.close();
}
public static class FastIO {
private InputStream dis;
private byte[] buffer = new byte[1 << 17];
private int pointer = 0;
public FastIO(String fileName) throws IOException {
dis = new FileInputStream(fileName);
}
public FastIO(InputStream is) throws IOException {
dis = is;
}
public int nextInt() throws IOException {
int ret = 0;
byte b;
do {
b = nextByte();
} while (b <= ' ');
boolean negative = false;
if (b == '-') {
negative = true;
b = nextByte();
}
while (b >= '0' && b <= '9') {
ret = 10 * ret + b - '0';
b = nextByte();
}
return (negative) ? -ret : ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte b;
do {
b = nextByte();
} while (b <= ' ');
boolean negative = false;
if (b == '-') {
negative = true;
b = nextByte();
}
while (b >= '0' && b <= '9') {
ret = 10 * ret + b - '0';
b = nextByte();
}
return (negative) ? -ret : ret;
}
public byte nextByte() throws IOException {
if (pointer == buffer.length) {
dis.read(buffer, 0, buffer.length);
pointer = 0;
}
return buffer[pointer++];
}
public String next() throws IOException {
StringBuffer ret = new StringBuffer();
byte b;
do {
b = nextByte();
} while (b <= ' ');
while (b > ' ') {
ret.appendCodePoint(b);
b = nextByte();
}
return ret.toString();
}
public void close() throws IOException {
dis.close();
}
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
8a97d45c534c7d386737c2fb46189532
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.Scanner;
public class d1486 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int length = in.nextInt();
int minSubarrayLength = in.nextInt();
int[] array = new int[length];
int min = Integer.MAX_VALUE, max = 0;
for (int i = 0; i < array.length; i++) {
array[i] = in.nextInt();
min = Math.min(min, array[i]);
max = Math.max(max, array[i]);
}
while (min < max) {
int attempt = ((max + min) / 2) + ((min + max) % 2);
if (canGetMedian(array, minSubarrayLength, attempt)) {
min = attempt;
} else {
max = attempt - 1;
}
}
System.out.println(min);
}
private static boolean canGetMedian(int[] array, int minSubarrayLength, int attempt) {
int tooLow = 0;
int highEnough = 0;
int couldRemoveTooLow = 0;
int couldRemoveHighEnough = 0;
int startIdx = 0;
int endIdx = 0;
while (endIdx < array.length) {
if (array[endIdx] < attempt) {
tooLow++;
} else {
highEnough++;
}
if (endIdx - startIdx + 1 > minSubarrayLength) {
if (array[endIdx - minSubarrayLength] < attempt) {
couldRemoveTooLow++;
} else {
couldRemoveHighEnough++;
}
}
while (couldRemoveHighEnough < couldRemoveTooLow) {
if (array[startIdx++] < attempt) {
couldRemoveTooLow--;
tooLow--;
} else {
couldRemoveHighEnough--;
highEnough--;
}
}
if ((endIdx - startIdx + 1 >= minSubarrayLength) && (highEnough > tooLow)) {
return true;
}
endIdx++;
}
return false;
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
4e03ba99b39e3d910fd93c158816ae0d
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.util.*;
import java.lang.*;
import java.io.*;
public class Codechef {
public static void main(String[] args) throws java.lang.Exception {
out = new PrintWriter(new BufferedOutputStream(System.out));
sc = new FastReader();
int test = 1;
for (int t = 0; t < test; t++) {
int n = sc.nextInt();
int k = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
int l = 1, r = n;
int res = -1;
while (l <= r) {
int mid = (l + r) / 2;
int[] temp = new int[n];
for (int i = 0; i < n; i++) {
if (arr[i] >= mid) {
temp[i] = 1;
}else {
temp[i] = -1;
}
}
for (int i = 1; i < n; i++) {
temp[i] += temp[i - 1];
}
int max = temp[k - 1];
int min = 0;
for (int i = k; i < n; i++) {
min = Math.min(min, temp[i - k]);
max = Math.max(max, temp[i] - min);
}
if (max > 0) {
res = mid;
l = mid + 1;
}else {
r = mid - 1;
}
}
out.println(res);
}
out.close();
}
public static FastReader sc;
public static PrintWriter out;
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 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
b4c724ad75d27753fe0558d4c0ed5bd8
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.util.*;
import java.lang.*;
import java.io.*;
public class Codechef {
public static void main(String[] args) throws java.lang.Exception {
out = new PrintWriter(new BufferedOutputStream(System.out));
sc = new FastReader();
int test = 1;
for (int t = 0; t < test; t++) {
int n = sc.nextInt();
int k = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
int l = 1, r = n + 1;
while (r - l > 1) {
int mid = (l + r) / 2;
int[] temp = new int[n];
for (int i = 0; i < n; i++) {
if (arr[i] >= mid) {
temp[i] = 1;
}else {
temp[i] = -1;
}
}
for (int i = 1; i < n; i++) {
temp[i] += temp[i - 1];
}
int max = temp[k - 1];
int min = 0;
for (int i = k; i < n; i++) {
min = Math.min(min, temp[i - k]);
max = Math.max(max, temp[i] - min);
}
if (max > 0) {
l = mid;
}else {
r = mid;
}
}
out.println(l);
}
out.close();
}
public static FastReader sc;
public static PrintWriter out;
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 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
836b5f03f87bc364f9a081eed4174d84
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
// coached by rainboy
import java.io.*;
import java.util.*;
public class CF1486D extends PrintWriter {
Scanner sc = new Scanner(System.in);
CF1486D() { super(System.out, true); }
public static void main(String[] $) {
CF1486D o = new CF1486D(); o.main(); o.flush();
}
void main() {
int n = sc.nextInt();
int k = sc.nextInt();
int[] aa = new int[n];
int[] pp = new int[n + 1];
for (int i = 0; i < n; i++)
aa[i] = sc.nextInt();
int lower = 1, upper = n + 1;
while (upper - lower > 1) {
int a = (lower + upper) / 2;
boolean yes = false;
int p = 0;
for (int i = 1; i <= n; i++) {
p += aa[i - 1] >= a ? 1 : -1;
pp[i] = Math.min(p, pp[i - 1]);
if (i >= k && p > pp[i - k]) {
yes = true;
break;
}
}
if (yes)
lower = a;
else
upper = a;
}
println(lower);
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
41f2c9882ab35b70bcce2d1a092addb3
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Main{
private static final String name = "triangles";
private static PrintWriter out;
private static FastIO sc;
private static final int mod = 1_000_000_007;
public static void main(String[] args) throws Exception {
try{
sc = new FastIO(name+".in");
out = new PrintWriter(name+".out");
}catch(FileNotFoundException e) {
sc = new FastIO(System.in);
out = new PrintWriter(new BufferedOutputStream(System.out));
}
int N = sc.nextInt(), K = sc.nextInt();
int[] nums = new int[N];
for(int i = 0; i<N; i++) nums[i] = sc.nextInt();
int lo = 0, hi = N;
int[] sum = new int[N];
for (int dif = hi - lo; dif > 0; dif /= 2)
while (lo + dif <= hi && check(lo + dif, nums, K, sum, N)) lo += dif;
out.println(lo);
out.close();
}
private static boolean check(int t, int[] nums, int k, int[] sum, int N) {
for(int i = 0; i<N; i++) sum[i] = nums[i] < t ? -1:1;
for(int i = 1; i<N; i++) sum[i]+=sum[i-1];
int min = 0;
for(int i = k-1; i<N; i++) {
if(sum[i]-min > 0) return true;
min = Math.min(min, sum[i-k+1]);
}
return false;
}
private static class Two<A, B>{
public final A a;
public final B b;
public Two(A a, B b) {
this.a = a;
this.b = b;
}
@Override
public boolean equals(Object obj) {
if(!(obj instanceof Two)) return false;
Two curr = (Two)obj;
return curr.a.equals(a) && curr.b.equals(b);
}
@Override
public int hashCode() {
long seed = a.hashCode();
seed = seed<<32;
seed|=b.hashCode();
Random r = new Random();
r.setSeed(seed);
return r.nextInt();
}
@Override
public String toString() {
return "("+a.toString()+", "+b.toString()+")";
}
}
public static class BIT {
private final long[] bit;
private final long[] arr;
private final int len;
public BIT(int len) {
bit = new long[len + 1];
arr = new long[len];
this.len = len;
}
public void set(int ind, long val) {
add(ind, val - arr[ind]);
}
public void add(int ind, long val) {
arr[ind] += val;
ind++;
for (; ind <= len; ind += ind & -ind) bit[ind] += val;
}
public long prev(int ind) {
ind++;
long sum = 0;
for (; ind > 0; ind -= ind & -ind) sum += bit[ind];
return sum;
}
public long sum(int a, int b) {
return prev(b)-(a == 0 ? 0:prev(a-1));
}
}
private static class SegTree {
public static interface Oper{
long solve(long a, long b);
}
private long[] tree;
private final int n;
private final Oper oper;
public SegTree(int n, Oper oper) {
this.n = n;
tree = new long[n<<1];
this.oper = oper;
}
public long get(int a, int b) {
a += n;
b += n;
long curr = 0;
boolean checked = false;
while (a <= b) {
if ((a&1) == 1) {
if(checked) curr = oper.solve(curr, tree[a++]);
else curr = tree[a++];
checked = true;
}
if ((b&1) == 0) {
if(checked) curr = oper.solve(curr, tree[b--]);
else curr = tree[b--];
checked = true;
}
a = a>>1;
b = b>>1;
}
return curr;
}
public void set(int index, long val) {
index += n;
tree[index] = val;
for (index = index>>1; index >= 1; index = index>>1)
tree[index] = oper.solve(tree[index<<1], tree[(index<<1)+1]);
}
public long get(int index) {
return tree[index+n];
}
}
private static class FastIO {
InputStream dis;
byte[] buffer = new byte[1 << 17];
int pointer = 0, end = 0;
public FastIO(String fileName) throws Exception {
dis = new FileInputStream(fileName);
}
public FastIO(InputStream is) throws Exception {
dis = is;
}
public int nextInt() throws Exception {
int ret = 0;
byte b;
do {
b = nextByte();
} while (b <= ' ');
boolean negative = false;
if (b == '-') {
negative = true;
b = nextByte();
}
while (b >= '0' && b <= '9') {
ret = 10 * ret + b - '0';
b = nextByte();
}
return (negative) ? -ret : ret;
}
public long nextLong() throws Exception {
long ret = 0;
byte b;
do {
b = nextByte();
} while (b <= ' ');
boolean negative = false;
if (b == '-') {
negative = true;
b = nextByte();
}
while (b >= '0' && b <= '9') {
ret = 10 * ret + b - '0';
b = nextByte();
}
return (negative) ? -ret : ret;
}
private byte nextByte() throws Exception {
while(pointer >= end) {
end = dis.read(buffer, 0, buffer.length);
pointer = 0;
}
return buffer[pointer++];
}
public double nextDouble() throws Exception {
return Double.parseDouble(next());
}
public String next() throws Exception {
StringBuffer ret = new StringBuffer();
byte b;
do {
b = nextByte();
} while (b <= ' ');
while (b > ' ') {
ret.appendCodePoint(b);
b = nextByte();
}
return ret.toString();
}
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
437b9f3cd0d5c9221b262e2f03d39ae2
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
int N , M;
Scanner scan = new Scanner(System.in);
N=scan.nextInt();
M=scan.nextInt();
int[] a = new int[N+1];
int[] b = new int[N+1];
int[] s = new int[N+1];
for(int i = 1; i <= N; i++){
a[i]=scan.nextInt();
}
int l = 1, r = N;
while(l < r){
int mid = (l + r+1)/2;
for(int i = 1; i <= N; i++){
if(a[i] >= mid) b[i] = 1;
else b[i] = -1;
s[i] = s[i-1] + b[i];
}
int k = N+1;
int ok = 0;
for(int i = M; i <= N; i++){
k = Math.min(k, s[i-M]);
if(s[i] > k) ok = 1;
}
if(ok==1) l = mid;
else r = mid-1;
}
System.out.println(l);
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
3bd9195c5b95721970b595e05723abea
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class MaxMedian {
static FastScanner fs;
static FastWriter fw;
static boolean checkOnlineJudge = System.getProperty("ONLINE_JUDGE") == null;
private static final int iMax = (int) (2e9), iMin = (int) (-2e9);
private static final long lMax = (int) (1e16), lMin = (int) (-1e16);
private static final int mod1 = (int) (1e9 + 7);
private static final int mod2 = 998244353;
private static int n, k;
private static Integer[] arr;
public static void main(String[] args) throws IOException {
fs = new FastScanner();
fw = new FastWriter();
int t = 1;
//t = fs.nextInt();
while (t-- > 0) {
solve();
}
fw.out.close();
}
private static void solve() {
n = fs.nextInt();
k = fs.nextInt();
arr = readIntArray(n);
int l = 1, r = n;
while (r - l > 1) {
int mid = l + ((r - l) / 2);
if (check(mid))
l = mid;
else
r = mid;
}
int result = check(r) ? r : l;
fw.out.println(result);
}
private static boolean check(int x) {
int[] prefix_sum = new int[n + 1];
for (int i = 1; i <= n; i++) {
prefix_sum[i] = ((arr[i - 1] >= x) ? 1 : -1) + prefix_sum[i - 1];
}
int j = 0, min = 0;
for (int i = k; i <= n; i++) {
min = (int) getMin(min, prefix_sum[j]);
if (prefix_sum[i] - min > 0)
return true;
j++;
}
return false;
}
private static class UnionFind {
private final int[] parent;
private final int[] rank;
UnionFind(int n) {
parent = new int[n + 5];
rank = new int[n + 5];
for (int i = 0; i <= n; i++) {
parent[i] = i;
rank[i] = 0;
}
}
private int find(int i) {
if (parent[i] == i)
return i;
return parent[i] = find(parent[i]);
}
private void union(int a, int b) {
a = find(a);
b = find(b);
if (a != b) {
if (rank[a] < rank[b]) {
int temp = a;
a = b;
b = temp;
}
parent[b] = a;
if (rank[a] == rank[b])
rank[a]++;
}
}
}
private static int gcd(int a, int b) {
return (b == 0 ? a : gcd(b, a % b));
}
private static long pow(long a, long b) {
long result = 1;
while (b > 0) {
if ((b & 1L) == 1) {
result = (result * a) % mod1;
}
a = (a * a) % mod1;
b >>= 1;
}
return result;
}
private static long ceilDiv(long a, long b) {
return ((a + b - 1) / b);
}
private static long getMin(long... args) {
long min = lMax;
for (long arg : args)
min = Math.min(min, arg);
return min;
}
private static long getMax(long... args) {
long max = lMin;
for (long arg : args)
max = Math.max(max, arg);
return max;
}
private static List<Integer> primes(int n) {
boolean[] primeArr = new boolean[n + 5];
Arrays.fill(primeArr, true);
for (int i = 2; (i * i) <= n; i++) {
if (primeArr[i]) {
for (int j = i * i; j <= n; j += i) {
primeArr[j] = false;
}
}
}
List<Integer> primeList = new ArrayList<>();
for (int i = 2; i <= n; i++) {
if (primeArr[i])
primeList.add(i);
}
return primeList;
}
private static class Pair<U, V> {
private final U first;
private final V second;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair<?, ?> pair = (Pair<?, ?>) o;
return first.equals(pair.first) && second.equals(pair.second);
}
@Override
public int hashCode() {
return Objects.hash(first, second);
}
@Override
public String toString() {
return "(" + first + ", " + second + ")";
}
private Pair(U ff, V ss) {
this.first = ff;
this.second = ss;
}
}
private static <T> void randomizeArr(T[] arr, int n) {
Random r = new Random();
for (int i = (n - 1); i > 0; i--) {
int j = r.nextInt(i + 1);
swap(arr, i, j);
}
}
private static Integer[] readIntArray(int n) {
Integer[] arr = new Integer[n];
for (int i = 0; i < n; i++)
arr[i] = fs.nextInt();
return arr;
}
private static List<Integer> readIntList(int n) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++)
list.add(fs.nextInt());
return list;
}
private static <T> void swap(T[] arr, int i, int j) {
T temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
private static <T> void displayArr(T[] arr) {
for (T x : arr)
fw.out.print(x + " ");
fw.out.println();
}
private static <T> void displayList(List<T> list) {
for (T x : list)
fw.out.print(x + " ");
fw.out.println();
}
private static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner() throws IOException {
if (checkOnlineJudge)
this.br = new BufferedReader(new FileReader("src/input.txt"));
else
this.br = new BufferedReader(new InputStreamReader(System.in));
this.st = new StringTokenizer("");
}
public String next() {
while (!st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException err) {
err.printStackTrace();
}
}
return st.nextToken();
}
public String nextLine() {
if (st.hasMoreTokens()) {
return st.nextToken("").trim();
}
try {
return br.readLine().trim();
} catch (IOException err) {
err.printStackTrace();
}
return "";
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
private static class FastWriter {
PrintWriter out;
FastWriter() throws IOException {
if (checkOnlineJudge)
out = new PrintWriter(new FileWriter("src/output.txt"));
else
out = new PrintWriter(System.out);
}
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
7f11996c4dc0e8c386fe9fe454a1922e
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class Main {
private static final String NO = "NO";
private static final String YES = "YES";
InputStream is;
PrintWriter out;
String INPUT = "";
private static final long MOD = 998244353L;
static int MAXN = 100000;
void solve() {
int T = 1;//ni();
for (int i = 0; i < T; i++)
solve(i);
}
int n;
void solve(int t) {
n = ni();
int K = ni();
int[] a = na(n);
int low = 0, high = n + 1;
while (high - low > 1) {
int h = high + low >> 1;
if (ok(h, a, K)) {
low = h;
} else {
high = h;
}
}
out.println(low);
}
boolean ok(int h, int[] a, int K) {
int pre = 0;
int min = Integer.MAX_VALUE / 2;
int[] cs = new int[n + 1];
for (int i = 0; i < n; i++) {
pre += a[i] >= h ? 1 : -1;
cs[i + 1] = pre;
if (i >= K - 1) {
min = Math.min(min, cs[i - (K - 1)]);
}
if (pre - min >= 1)
return true;
}
return false;
}
// a^b
long power(long a, long b) {
long x = 1, y = a;
while (b > 0) {
if (b % 2 != 0) {
x = (x * y) % MOD;
}
y = (y * y) % MOD;
b /= 2;
}
return x % MOD;
}
private long gcd(long a, long b) {
while (a != 0) {
long tmp = b % a;
b = a;
a = tmp;
}
return b;
}
void run() throws Exception {
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
if (!INPUT.isEmpty())
tr(System.currentTimeMillis() - s + "ms");
}
public static void main(String[] args) throws Exception {
new Main().run();
}
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte() {
if (lenbuf == -1)
throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b))
;
return b;
}
private double nd() {
return Double.parseDouble(ns());
}
private char nc() {
return (char) skip();
}
private char[] nc(int n) {
char[] ret = new char[n];
for (int i = 0; i < n; i++)
ret[i] = nc();
return ret;
}
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != '
// ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n) {
if (!(isSpaceChar(b)))
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++)
map[i] = ns(m);
return map;
}
private int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = ni();
return a;
}
private Integer[] na2(int n) {
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++)
a[i] = ni();
return a;
}
private int[][] na(int n, int m) {
int[][] a = new int[n][];
for (int i = 0; i < n; i++)
a[i] = na(m);
return a;
}
private int ni() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private long[] nl(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nl();
return a;
}
private long[][] nl(int n, int m) {
long[][] a = new long[n][];
for (int i = 0; i < n; i++)
a[i] = nl(m);
return a;
}
private long nl() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private static void tr(Object... o) {
System.out.println(Arrays.deepToString(o));
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
1673e4971f5b5847e036df612e9bbd4d
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.util.*;
public class Sol{
public static void main(String [] args){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int k=sc.nextInt();
int a[]=new int[n];
int b[]=new int[n];
for(int i=0;i<n;i++){a[i]=sc.nextInt();}
int l=1;int r=n+1;
while(r-l>1){
int m=(l+r)/2;
for(int i=0;i<n;i++){if(a[i]>=m)b[i]=1;else{b[i]=-1;}}
for(int i=1;i<n;i++){b[i]+=b[i-1];}
int min=0;
int max=b[k-1];
for(int i=k;i<n;i++){
min=Math.min(min,b[i-k]);max=Math.max(b[i]-min,max);
}
if(max>0){l=m;}
else{r=m;}
}
System.out.println(l);
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
984dc2232971d491442162038b57c2c0
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class CF {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args) {
try {
System.setIn(new FileInputStream("input.txt"));
System.setOut(new PrintStream(new FileOutputStream("output.txt")));
} catch (Exception e) {
System.err.println("Error");
}
FastReader fs = new FastReader();
int t = 1;
int ans = 0;
while(t-- > 0) {
int n = fs.nextInt();
int k = fs.nextInt();
int[] a = new int[n+2];
for(int i=1; i<=n; i++) {
a[i] = fs.nextInt();
}
int l = 1, h = n;
while(l <= h) {
int m = (l+h)/2;
int f = 0;
int[] temp = new int[n+2];
int[] prefix = new int[n+2];
for(int i=1; i<n+1; i++) {
if(a[i] >= m) temp[i] = 1;
else temp[i] = -1;
}
for(int i=1; i<=n; i++) {
prefix[i] += prefix[i-1] + temp[i];
}
int min = Integer.MAX_VALUE;
for(int i=k; i<=n; i++) {
min = Math.min(min, prefix[i-k]);
if(prefix[i] - min > 0) {
f = 1;
}
}
if(f == 1) {
ans = m;
l = m+1;
} else h = m-1;
}
System.out.println(ans);
}
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
0c839a26af3777a6887eb382d1451d57
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.util.*;
public class cf703 {
public static Scanner sc = new Scanner(System.in);
public static int problemA(int n, int arr[]){
long tillNow=0;
for(int i=0; i<n; i++){
tillNow+=arr[i];
if(tillNow<i) return 0;
tillNow-=i;
}
return 1;
}
public static int binSrch(int arr[], int T){
//get index k of arr which is last element arr[k]<T and arr[k+1]>=T
int n = arr.length;
int start = 0, end=n-1;
while(start<end){
int mid = (start+end)/2;
if(arr[mid]<T && arr[mid+1]>=T) return mid;
else if(arr[mid]>=T) end=mid-1;
else start=mid;
}
return (end==0)?end:-1;
}
public static long calcD(int n, int id, long[] pr, int v){
long sum=0;
if(id>=0){
sum = Math.abs((id+1)*v-pr[id])+Math.abs((pr[n-1]-pr[id]) - v* (n-1-id));
}
else {
sum= Math.abs((pr[n-1]) - v* (n));
}
return sum;
}
public static int ask(int l, int r){
System.out.println("? "+l+" "+r);
int index = sc.nextInt();
return index;
}
public static int[] setTemp(int arr[], int v){
int n = arr.length;
int t[] = new int[n];
for(int i=0; i<n; i++){
if(arr[i]>=v) t[i]=1;
else t[i]=-1;
}
return t;
}
public static boolean isMedianAtLeastX(int temp[], int k){
boolean ans = false;
int n = temp.length;
for(int i=1; i<n; i++) temp[i]+=temp[i-1];
if(temp[k-1]>0) return true;
int minval=0;
for(int i=k; i<n; i++){
minval=Math.min(minval,temp[i-k]);
if (temp[i]-minval>0) ans=true;
}
return ans;
}
public static int problemD(int n, int k, int arr[]){
int start=1;
int end = n+1;
while((end-start)>1){
int mid = (end+start)/2;
int[] temp = setTemp(arr,mid);
boolean ans = isMedianAtLeastX(temp,k);
if(ans) start=mid;
else end=mid;
}
return start;
}
public static long problemB(int n, int x[], int y[]){
// int maxX = 1000000000;
// int maxY = 1000000000;
Arrays.sort(x);
Arrays.sort(y);
long res1 = x[(n/2)]-x[(n-1)/2] +1;
long res2 = y[(n/2)]-y[(n-1)/2] +1;
return res1*res2;
}
public static void problemCD(int n){
int smaxIndex = ask(1,n);
int start=1; int end=n;
if(smaxIndex==1 || ask(1,smaxIndex)!=smaxIndex){
//between smaxindex-n
int l=smaxIndex; int r=n;
while((r-l)>1){
int mid = (l+r)/2;
if(ask(smaxIndex,mid)==smaxIndex) r=mid;
else l=mid;
}
System.out.println("! "+r);
System.out.flush();
}
else{
//between 1-smaxindex
int l=1; int r=smaxIndex;
while((r-l)>1){
int mid = (l+r)/2;
if(ask(mid,smaxIndex)==smaxIndex) l=mid;
else r=mid;
}
System.out.println("! "+l);
System.out.flush();
}
}
public static void main(String[] args) {
int n,k;
n = sc.nextInt();
k = sc.nextInt();
int arr[] = new int[n];
for(int i=0; i<n; i++) arr[i] = sc.nextInt();
System.out.println(problemD(n,k,arr));
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
6b3af662a23a7a566b71963760b7dd2f
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Template {
static long[] c = new long[(int)1e6+8432];
static long[] b = new long[(int)1e6+8432];
public static void main(String[] args) {
FastScanner sc = new FastScanner();
// int yo = sc.nextInt();
// while (yo-- > 0) {
int n = sc.nextInt();
int k = sc.nextInt();
int[] a = sc.readArray(n);
long start = 0, end = (int) 1e7;
while(start < end) {
long mid = (start + end)/2;
long sum = 0;
long min = (long) 1e18;
long best = (long) -1e18;
c[0] = 0;
for(int i = 0; i < n; i++) {
b[i] = a[i] >= mid ? 1 : -1;
sum += b[i];
c[i+1] = sum;
if(i >= k-1) {
min = Math.min(min, c[i-k+1]);
best = Math.max(best, sum-min);
}
}
if(best > 0) {
start = mid+1;
}
else {
end = mid;
}
}
System.out.println(start-1);
// }
}
static class Pair {
int x;
int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
static void ruffleSort(int[] a) {
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;
}
Arrays.sort(a);
}
static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static boolean[] sieve(int n) {
boolean isPrime[] = new boolean[n + 1];
for (int i = 2; i <= n; i++) {
if (isPrime[i])
continue;
for (int j = 2 * i; j <= n; j += i) {
isPrime[j] = true;
}
}
return isPrime;
}
static int mod = 1000000007;
static long pow(int a, long b) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
if (b % 2 == 0) {
long ans = pow(a, b / 2);
return ans * ans;
} else {
long ans = pow(a, (b - 1) / 2);
return a * ans * ans;
}
}
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());
}
}
// For Input.txt and Output.txt
// FileInputStream in = new FileInputStream("input.txt");
// FileOutputStream out = new FileOutputStream("output.txt");
// PrintWriter pw = new PrintWriter(out);
// Scanner sc = new Scanner(in);
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
f520cc8532a9ddb41d8d8e4ad85e4bba
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class CF703D {
public static final int N = (int)(2e5);
public static int n, k;
public static int[] a, b, c;
public static SegmentTree T;
static class SegmentTree {
int mx[];
SegmentTree () {
mx = new int[N << 2];
build(1, 0, n - 1);
}
public void build (int v, int tl, int tr) {
if (tl == tr) {
mx[v] = c[tl];
return;
}
int tm = (tl + tr) >> 1;
build(v << 1, tl, tm);
build(v << 1 | 1, tm + 1, tr);
mx[v] = Math.max(mx[v << 1], mx[v << 1 | 1]);
}
public int get (int x, int v, int tl, int tr) {
if (mx[v] < x)
return -1;
if (tl == tr)
return tl;
int tm = (tl + tr) >> 1;
if (mx[v << 1 | 1] >= x)
return get(x, v << 1 | 1, tm + 1, tr);
return get(x, v << 1, tl, tm);
}
}
public static boolean check (int x) {
for (int i = 0; i < n; ++i) {
b[i] = (i == 0 ? 0 : b[i - 1]);
if (a[i] >= x)
b[i]++;
c[i] = b[i]*2 - i;
// System.out.println(b[i] + " " + c[i]);
}
// System.out.println();
T = new SegmentTree();
for (int l = 0, r = k - 1; r < n; ++l, ++r) {
int rr = T.get((l == 0 ? 1 : c[l - 1]) + 1, 1, 0, n - 1);
// System.out.println(r + " " + rr);
if (rr >= r)
return true;
}
return false;
}
public static void main (String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
k = Integer.parseInt(st.nextToken());
st = new StringTokenizer(br.readLine());
a = new int[n];
b = new int[n];
c = new int[n];
for (int i = 0; i < n; ++i)
a[i] = Integer.parseInt(st.nextToken());
int l = 0, r = n, res = 0;
while (l <= r) {
int mid = (l + r) >> 1;
if (check(mid)) {
res = mid;
l = mid + 1;
} else
r = mid - 1;
}
System.out.println(res);
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
e0b82b381da7bc99f76ca2bec96a80f0
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.util.Scanner;
public class Index {
static final int MAXN = 200005;
static int n, k;
static int[] a = new int[MAXN];
static int[] b = new int[MAXN];
static int[] sum = new int[MAXN];
static Scanner scan = new Scanner(System.in);
static boolean check(int x) {
for (int i = 1; i <= n; i++)
b[i] = a[i] >= x ? 1 : -1;
for (int i = 1; i <= n; i++)
sum[i] = sum[i - 1] + b[i];
int mx = -1000000000;
for (int i = k; i <= n; i++) {
mx = Math.max(mx + b[i], sum[i] - sum[i - k]);
if (mx > 0)
return true;
}
return false;
}
public static void main(String[] args) {
n = scan.nextInt();
k = scan.nextInt();
for (int i = 1; i <= n; i++)
a[i] = scan.nextInt();
int l = 1, r = n, mid;
while (l <= r) {
mid = (l + r) >> 1;
if (check(mid))
l = mid + 1;
else
r = mid - 1;
}
System.out.println(l - 1);
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
638aa73a8f8e60eb7cf74aec76a27ab1
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class abc
{
static BufferedReader br;
public static void main(String ard[])throws IOException
{
br=new BufferedReader(new InputStreamReader(System.in));
String s[]=br.readLine().split(" ");
int n=Integer.parseInt(s[0]);
int k=Integer.parseInt(s[1]);
s=br.readLine().split(" ");
int a[]=new int[n];
for(int i=0;i<n;i++)
a[i]=Integer.parseInt(s[i]);
int l=1,r=n+1;
while(r-l>1)
{
int b[]=new int[n];
int m=(l+r)/2;
for(int i=0;i<n;i++)
if(a[i]>=m)
b[i]=1;
else
b[i]=-1;
for(int i=1;i<n;i++)
b[i]+=b[i-1];
int mx=b[k-1];
int mn=0;
for(int i=k;i<n;i++)
{
mn=Math.min(mn,b[i-k]);
mx=Math.max(mx,b[i]-mn);
}
if(mx>0)
l=m;
else
r=m;
}
System.out.println(l);
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
dc7d4431502d37cf3fb4a56a9fc220fd
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class D
{
public static class FastIO
{
BufferedReader br;
BufferedWriter bw, be;
StringTokenizer st;
public FastIO()
{
br = new BufferedReader(new InputStreamReader(System.in));
bw = new BufferedWriter(new OutputStreamWriter(System.out));
be = new BufferedWriter(new OutputStreamWriter(System.err));
st = new StringTokenizer("");
}
private void read() throws IOException
{
st = new StringTokenizer(br.readLine());
}
public String ns() throws IOException
{
while(!st.hasMoreTokens())
read();
return st.nextToken();
}
public int ni() throws IOException
{
return Integer.parseInt(ns());
}
public long nl() throws IOException
{
return Long.parseLong(ns());
}
public float nf() throws IOException
{
return Float.parseFloat(ns());
}
public double nd() throws IOException
{
return Double.parseDouble(ns());
}
public char nc() throws IOException
{
return ns().charAt(0);
}
public int[] nia(int n) throws IOException
{
int[] a = new int[n+1];
for(int i = 1; i <= n; i++)
a[i] = ni();
return a;
}
public long[] nla(int n) throws IOException
{
long[] a = new long[n];
for(int i = 0; i < n; i++)
a[i] = nl();
return a;
}
public char[] nca() throws IOException
{
return f.ns().toCharArray();
}
public void out(String s) throws IOException
{
bw.write(s);
}
public void flush() throws IOException
{
bw.flush();
be.flush();
}
public void err(String s) throws IOException
{
be.write(s);
}
}
static FastIO f;
static int n, k, a[], da[];
public static void main(String args[]) throws IOException
{
f = new FastIO();
n = f.ni();
k = f.ni();
a = f.nia(n);
da = a.clone();
Arrays.sort(da);
int ans = search(1, n);
f.out(ans + "\n");
f.flush();
}
public static int search(int l, int r) throws IOException
{
if(l == r)
return da[l];
int mid = l + (r-l)/2 + 1;
int b[] = new int[n+1];
int i;
for(i = 1; i <= n; i++)
b[i] = (a[i] >= da[mid]) ? 1 : -1;
return prefix(b) ? search(mid, r) : search(l, mid-1);
}
public static boolean prefix(int[] b)
{
int p[] = new int[n+1], i, min;
for(i = 1; i <= n; i++)
p[i] = p[i-1] + b[i];
for(i = k, min = p[0]; i <= n; i++)
{
min = Math.min(min, p[i-k]);
if(p[i] - min > 0)
return true;
}
return false;
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
1afc784abccd39937c6ee382bdd9df24
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.Arrays;
import java.util.Random;
import java.io.FileWriter;
import java.io.PrintWriter;
/*
Solution Created: 12:43:51 20/02/2021
Custom Competitive programming helper.
*/
public class Main {
public static void solve() {
int n = in.nextInt(), k = in.nextInt();
int[] a = in.na(n);
int l = 1, r = n, ans = 1;
while(l<=r){
int median = (l+r)/2;
int[] b = new int[n];
for(int i = 0; i<n; i++) b[i] = a[i]>=median?1:-1;
for(int i = 1; i<n; i++) b[i] += b[i-1];
int mn = 0;
boolean can = b[k-1]>0;
for(int i = k; i<n; i++){
mn = Math.min(mn, b[i-k]);
can |= b[i]-mn>0;
}
if(can){
ans = median;
l = median+1;
}else r = median-1;
}
out.println(ans);
}
public static void main(String[] args) {
in = new Reader();
out = new Writer();
int t = 1;
while (t-- > 0)
solve();
out.exit();
}
static Reader in;
static Writer out;
static class Reader {
static BufferedReader br;
static StringTokenizer st;
public Reader() {
this.br = new BufferedReader(new InputStreamReader(System.in));
}
public Reader(String f){
try {
this.br = new BufferedReader(new FileReader(f));
} catch (IOException e) {
e.printStackTrace();
}
}
public int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
public double[] nd(int n) {
double[] a = new double[n];
for (int i = 0; i < n; i++) a[i] = nextDouble();
return a;
}
public long[] nl(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
public char[] nca() {
return next().toCharArray();
}
public String[] ns(int n) {
String[] a = new String[n];
for (int i = 0; i < n; i++) a[i] = next();
return a;
}
public int nextInt() {
ensureNext();
return Integer.parseInt(st.nextToken());
}
public double nextDouble() {
ensureNext();
return Double.parseDouble(st.nextToken());
}
public Long nextLong() {
ensureNext();
return Long.parseLong(st.nextToken());
}
public String next() {
ensureNext();
return st.nextToken();
}
public String nextLine() {
try {
return br.readLine();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private void ensureNext() {
if (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
static class Util{
private static Random random = new Random();
static long[] fact;
public static void initFactorial(int n, long mod) {
fact = new long[n+1];
fact[0] = 1;
for (int i = 1; i < n+1; i++) fact[i] = (fact[i - 1] * i) % mod;
}
public static long modInverse(long a, long MOD) {
long[] gcdE = gcdExtended(a, MOD);
if (gcdE[0] != 1) return -1; // Inverted doesn't exist
long x = gcdE[1];
return (x % MOD + MOD) % MOD;
}
public static long[] gcdExtended(long p, long q) {
if (q == 0) return new long[] { p, 1, 0 };
long[] vals = gcdExtended(q, p % q);
long tmp = vals[2];
vals[2] = vals[1] - (p / q) * vals[2];
vals[1] = tmp;
return vals;
}
public static long nCr(int n, int r, long MOD) {
if (r == 0) return 1;
return (fact[n] * modInverse(fact[r], MOD) % MOD * modInverse(fact[n - r], MOD) % MOD) % MOD;
}
public static long nCr(int n, int r) {
return (fact[n]/fact[r])/fact[n-r];
}
public static long nPr(int n, int r, long MOD) {
if (r == 0) return 1;
return (fact[n] * modInverse(fact[n - r], MOD) % MOD) % MOD;
}
public static long nPr(int n, int r) {
return fact[n]/fact[n-r];
}
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;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
public static boolean[] getSieve(int n) {
boolean[] isPrime = new boolean[n+1];
for (int i = 2; i <= n; i++) isPrime[i] = true;
for (int i = 2; i*i <= n; i++) if (isPrime[i])
for (int j = i; i*j <= n; j++) isPrime[i*j] = false;
return isPrime;
}
public static int gcd(int a, int b) {
int tmp = 0;
while(b != 0) {
tmp = b;
b = a%b;
a = tmp;
}
return a;
}
public static long gcd(long a, long b) {
long tmp = 0;
while(b != 0) {
tmp = b;
b = a%b;
a = tmp;
}
return a;
}
public static int random(int min, int max) {
return random.nextInt(max-min+1)+min;
}
public static void dbg(Object... o) {
System.out.println(Arrays.deepToString(o));
}
public static void reverse(int[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
int tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(int[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(long[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
long tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(long[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(float[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
float tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(float[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(double[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
double tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(double[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(char[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
char tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(char[] s) {
reverse(s, 0, s.length-1);
}
public static <T> void reverse(T[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
T tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static <T> void reverse(T[] s) {
reverse(s, 0, s.length-1);
}
public static void shuffle(int[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
int t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(long[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
long t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(float[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
float t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(double[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
double t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(char[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
char t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static <T> void shuffle(T[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
T t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void sortArray(int[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(long[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(float[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(double[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(char[] a) {
shuffle(a);
Arrays.sort(a);
}
public static <T extends Comparable<T>> void sortArray(T[] a) {
Arrays.sort(a);
}
}
static class Writer {
private PrintWriter pw;
public Writer(){
pw = new PrintWriter(System.out);
}
public Writer(String f){
try {
pw = new PrintWriter(new FileWriter(f));
} catch (IOException e) {
e.printStackTrace();
}
}
public void printArray(int[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
}
public void printlnArray(int[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
pw.println();
}
public void printArray(long[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
}
public void printlnArray(long[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
pw.println();
}
public void print(Object o) {
pw.print(o.toString());
}
public void println(Object o) {
pw.println(o.toString());
}
public void println() {
pw.println();
}
public void flush() {
pw.flush();
}
public void exit() {
pw.close();
}
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
310993266febbcbda7fee5d9241c41ff
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import java.io.*;
import java.util.*;
public class A
{
static int n, k;
static int[] arr;
static char[] s;
public static void main(String[] args) throws IOException
{
f = new Flash();
out = new PrintWriter(System.out);
int T = 1; //ni();
for(int tc = 1; tc <= T; tc++){
n = ni(); k = ni(); arr = arr(n); sop(fn());
}
out.flush(); out.close();
}
static int fn()
{
int l = 1, r = n;
while(l < r) {
int mid = l + (r - l + 1) / 2;
if(ok(mid)) l = mid;
else r = mid - 1;
}
return l;
}
static boolean ok(int x) {
int[] b = new int[n];
for(int i = 0; i < n; i++) {
if(arr[i] >= x) b[i] = 1;
else b[i] = -1;
}
int[] pref = new int[n]; pref[0] = b[0];
for(int i = 1; i < n; i++) pref[i] += pref[i-1] + b[i];
int max = pref[k-1], min = 0;
for(int i = k; i < n; i++) {
min = min(min, pref[i-k]);
max = max(max, pref[i] - min);
}
if(max > 0) return true;
return false;
}
static Flash f;
static PrintWriter out;
static final long mod = (long)1e9+7;
static final long inf = Long.MAX_VALUE;
static final int _inf = Integer.MAX_VALUE;
static final int maxN = (int)5e5+5;
static long[] fact, inv;
static void sort(int[] a){
List<Integer> A = new ArrayList<>();
for(int i : a) A.add(i);
Collections.sort(A);
for(int i = 0; i < A.size(); i++) a[i] = A.get(i);
}
static void sort(long[] a){
List<Long> A = new ArrayList<>();
for(long i : a) A.add(i);
Collections.sort(A);
for(int i = 0; i < A.size(); i++) a[i] = A.get(i);
}
static void print(int[] a){
StringBuilder sb = new StringBuilder();
for(int i = 0; i < a.length; i++) sb.append(a[i] + " ");
sop(sb);
}
static void print(long[] a){
StringBuilder sb = new StringBuilder();
for(int i = 0; i < a.length; i++) sb.append(a[i] + " ");
sop(sb);
}
static int swap(int itself, int dummy){return itself;}
static long swap(long itself, long dummy){return itself;}
static void sop(Object o){out.println(o);}
static int ni(){return f.ni();}
static long nl(){return f.nl();}
static double nd(){return f.nd();}
static String next(){return f.next();}
static String ns(){return f.ns();}
static char[] nc(){return f.nc();}
static int[] arr(int len){return f.arr(len);}
static int gcd(int a, int b){if(b == 0) return a; return gcd(b, a%b);}
static long gcd(long a, long b){if(b == 0) return a; return gcd(b, a%b);}
static int lcm(int a, int b){return (a*b)/gcd(a, b);}
static long lcm(long a, long b){return (a*b)/gcd(a, b);}
static class Flash
{
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();
}
String ns(){
String s = new String();
try{
s = br.readLine().trim();
}catch(IOException e){
e.printStackTrace();
}
return s;
}
int[] arr(int n){
int[] a = new int[n];
for(int i = 0; i < n; i++) a[i] = ni();
return a;
}
char[] nc(){return ns().toCharArray();}
int ni(){return Integer.parseInt(next());}
long nl(){return Long.parseLong(next());}
double nd(){return Double.parseDouble(next());}
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
4f43b768df1c772b892841b810d69d09
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
//package com.company;
import java.io.*;
import java.util.*;
public class Main {
static FastReader sc = new FastReader();
static PrintWriter out = new PrintWriter(System.out);
private static int N = 200005;
private static int[] a = new int[N];
private static int[] b = new int[N];
private static int n = 0, k = 0;
private static boolean check(int mid){
for(int i = 1 ; i <= n ; ++i) b[i] = b[i - 1] + (a[i] >= mid ? 1 : -1);
int lr = N , rs = 0;
for(int i = k ; i <= n ; ++i){
lr = Math.min(lr , b[i - k]);
rs = Math.max(rs , b[i] - lr);
}
return rs <= 0;
}
public static void main(String[] args) throws IOException{
// write your code here
n = sc.nextInt(); k = sc.nextInt();
for(int i = 1 ; i <= n ; ++i) a[i] = sc.nextInt();
int l = 1 , r = N;
while(l < r){
int mid = l + r + 1 >> 1;
if(check(mid)) r = mid - 1;
else l = mid;
}
out.print(l);
out.flush();
}
}
/** 读取int和double的类 */
class FastReader {
BufferedReader br;
StringTokenizer st; public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
} } return st.nextToken(); } int nextInt() {
return Integer.parseInt(next());
} long nextLong() {
return Long.parseLong(next());
} double nextDouble() {
return Double.parseDouble(next());
}String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
b775db0434e50b5f6a26f062218278bf
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Maxmed {
public static void main(String[] args) {
int n, k;
Scanner in = new Scanner(System.in);
n = in.nextInt();
k = in.nextInt();
int[] nums = new int[n];
for (int i = 0; i < n; i++) {
nums[i] = in.nextInt();
}
int l = 1;
int r = n + 1;
while (l + 1 < r) {
int m = (l + r) / 2;
int[] compare = new int[n];
for (int i = 0; i < n; i++) {
if (m <= nums[i])
compare[i] = 1;
else
compare[i] = -1;
if (i > 0)
compare[i] += compare[i - 1];
}
boolean possible;
possible = false;
if (compare[k - 1] > 0)
possible = true;
int minSum = 0;
for (int i = k; i < n; i++) {
minSum = Math.min(minSum, compare[i - k]);
if (compare[i] > minSum)
possible = true;
}
if (possible)
l = m;
else
r = m;
}
System.out.println(l);
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
1ecbbc4a757175957c59bbb1613c110f
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.io.*;
import java.util.*;
import java.lang.*;
public class Main {
public static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
static long MOD = (long) (1e9 + 7);
//static int MOD = 998244353;
static long MOD2 = MOD * MOD;
static FastReader sc = new FastReader();
static int pInf = Integer.MAX_VALUE;
static int nInf = Integer.MIN_VALUE;
static long ded = (long)(1e17)+9;
public static void main(String[] args) throws Exception {
int test = 1;
//test = sc.nextInt();
for (int i = 1; i <= test; i++){
//out.print("Case #"+i+": ");
solve();
}
out.flush();
out.close();
}
static int n,k;
static int[] a;
static void solve() throws Exception {
n = sc.nextInt();
k = sc.nextInt();
a = new int[n];
for(int i = 0 ; i < n; i++){
a[i] = sc.nextInt();
}
int l = 0;
int r = 2_000_01;
while(r-l>1){
int m = l+(r-l)/2;
if(good(m)){
l = m;
}else{
r = m;
}
}
out.println(l);
}
static boolean good(int m){
int[] p = new int[n+1];
int sum = 0;
int min = pInf;
int best = nInf;
for(int i = 0; i < n; i++){
if(a[i]<m){
sum += -1;
}else{
sum += 1;
}
p[i+1] = sum;
if(i-k+1>=0){
min = Math.min(min,p[i-k+1]);
best = Math.max(best,sum-min);
}
}
return best>0;
}
static int query(int l,int r){
out.println("? "+l+" "+r);
out.flush();
return sc.nextInt();
}
static class Pair implements Comparable<Pair> {
int x;
long y;
int idx;
public Pair(int x, long y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Pair o) {
if ((this.x == o.x)) {
//return (this.y - o.y);
}
return (this.x - o.x);
}
}
public static long mul(long a, long b) {
return ((a % MOD) * (b % MOD)) % MOD;
}
public static long add(long a, long b) {
return ((a % MOD) + (b % MOD)) % MOD;
}
public static long c2(long n) {
if ((n & 1) == 0) {
return mul(n / 2, n - 1);
} else {
return mul(n, (n - 1) / 2);
}
}
//Shuffle Sort
static final Random random = new Random();
static void ruffleSort(int[] a) {
int n = a.length;//shuffle, then sort
for (int i = 0; i < n; i++) {
int oi = random.nextInt(n); int temp= a[oi];
a[oi] = a[i];
a[i] = temp;
}
Arrays.sort(a);
}
//Brian Kernighans Algorithm
static long countSetBits(long n) {
if (n == 0) return 0;
return 1 + countSetBits(n & (n - 1));
}
//Euclidean Algorithm
static long gcd(long A, long B) {
if (B == 0) return A;
return gcd(B, A % B);
}
//Modular Exponentiation
static long fastExpo(long x, long n) {
if (n == 0) return 1;
if ((n & 1) == 0) return fastExpo((x * x) % MOD, n / 2) % MOD;
return ((x % MOD) * fastExpo((x * x) % MOD, (n - 1) / 2)) % MOD;
}
//AKS Algorithm
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 <= Math.sqrt(n); i += 6)
if (n % i == 0 || n % (i + 2) == 0) return false;
return true;
}
public static long modinv(long x) {
return modpow(x, MOD - 2);
}
public static long modpow(long a, long b) {
if (b == 0) {
return 1;
}
long x = modpow(a, b / 2);
x = (x * x) % MOD;
if (b % 2 == 1) {
return (x * a) % MOD;
}
return x;
}
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 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
50fb9f254fe31a72699e9f829b291e83
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class _703 {
static MyScanner sc;
public static void main(String[] args) {
sc = new MyScanner();
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
int t = 1;
while (t-- > 0) {
int n = sc.nextInt();
int k = sc.nextInt();
int [] a = new int[n];
for (int i = 0; i < n; i++) a[i] = sc.nextInt();
int l = 0; int r = n + 1;
while (l < r) {
int mid = (l + r) / 2;
int [] b = new int[n];
for (int i = 0; i < n; i++) {
if (a[i] >= mid) b[i] = 1;
else b[i] = -1;
}
int [] pref = new int[n + 1];
for (int i = 1; i <= n; i++) pref[i] = pref[i - 1] + b[i - 1];
PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.add(pref[0]);
int max = (int) -1e7;
for (int i = k; i <= n; i++) {
max = Math.max(pref[i] - pq.peek(), max);
pq.add(pref[i - k + 1]);
}
if (max > 0) {
l = mid + 1;
} else {
r = mid;
}
}
out.println(l - 1);
}
out.close();
}
static void sort(int[] a) {
ArrayList<Integer> q = new ArrayList<>();
for (int i : a) q.add(i);
Collections.sort(q);
for (int i = 0; i < a.length; i++) a[i] = q.get(i);
}
static void sort(long[] a) {
ArrayList<Long> q = new ArrayList<>();
for (long i : a) q.add(i);
Collections.sort(q);
for (int i = 0; i < a.length; i++) a[i] = q.get(i);
}
//-----------MyScanner class for faster input----------
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
5ccb8dcb40044e742ce9e0a030be121c
|
train_110.jsonl
|
1613658900
|
You are a given an array $$$a$$$ of length $$$n$$$. Find a subarray $$$a[l..r]$$$ with length at least $$$k$$$ with the largest median.A median in an array of length $$$n$$$ is an element which occupies position number $$$\lfloor \frac{n + 1}{2} \rfloor$$$ after we sort the elements in non-decreasing order. For example: $$$median([1, 2, 3, 4]) = 2$$$, $$$median([3, 2, 1]) = 2$$$, $$$median([2, 1, 2, 1]) = 1$$$.Subarray $$$a[l..r]$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_l,a_{l+1},\ldots,a_r$$$ for some $$$1 \leq l \leq r \leq n$$$, its length is $$$r - l + 1$$$.
|
256 megabytes
|
//package round703;
import java.io.*;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Queue;
public class D {
InputStream is;
FastWriter out;
String INPUT = "";
void solve()
{
int n = ni(), K = ni();
int[] a = na(n);
int low = 0, high = n+1;
while(high - low > 1){
int h = high+low>>1;
if(ok(h, a, K)){
low = h;
}else{
high = h;
}
}
out.println(low);
}
boolean ok(int h, int[] a, int K)
{
int n = a.length;
// higher >= lower + 1
int c = 0;
int min = Integer.MAX_VALUE / 2;
int[] cs = new int[n+1];
for(int i = 0;i < n;i++){
c += a[i] >= h ? 1 : -1;
cs[i+1] = c;
if(i >= K-1){
min = Math.min(min, cs[i-(K-1)]);
}
if(c-min >= 1)return true;
}
return false;
}
void run() throws Exception
{
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new FastWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new D().run(); }
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private long[] nal(int n)
{
long[] a = new long[n];
for(int i = 0;i < n;i++)a[i] = nl();
return a;
}
private char[][] nm(int n, int m) {
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[][] nmi(int n, int m) {
int[][] map = new int[n][];
for(int i = 0;i < n;i++)map[i] = na(m);
return map;
}
private int ni() { return (int)nl(); }
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
public static class FastWriter
{
private static final int BUF_SIZE = 1<<13;
private final byte[] buf = new byte[BUF_SIZE];
private final OutputStream out;
private int ptr = 0;
private FastWriter(){out = null;}
public FastWriter(OutputStream os)
{
this.out = os;
}
public FastWriter(String path)
{
try {
this.out = new FileOutputStream(path);
} catch (FileNotFoundException e) {
throw new RuntimeException("FastWriter");
}
}
public FastWriter write(byte b)
{
buf[ptr++] = b;
if(ptr == BUF_SIZE)innerflush();
return this;
}
public FastWriter write(char c)
{
return write((byte)c);
}
public FastWriter write(char[] s)
{
for(char c : s){
buf[ptr++] = (byte)c;
if(ptr == BUF_SIZE)innerflush();
}
return this;
}
public FastWriter write(String s)
{
s.chars().forEach(c -> {
buf[ptr++] = (byte)c;
if(ptr == BUF_SIZE)innerflush();
});
return this;
}
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;
}
public FastWriter write(int x)
{
if(x == Integer.MIN_VALUE){
return write((long)x);
}
if(ptr + 12 >= BUF_SIZE)innerflush();
if(x < 0){
write((byte)'-');
x = -x;
}
int d = countDigits(x);
for(int i = ptr + d - 1;i >= ptr;i--){
buf[i] = (byte)('0'+x%10);
x /= 10;
}
ptr += d;
return this;
}
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;
}
public FastWriter write(long x)
{
if(x == Long.MIN_VALUE){
return write("" + x);
}
if(ptr + 21 >= BUF_SIZE)innerflush();
if(x < 0){
write((byte)'-');
x = -x;
}
int d = countDigits(x);
for(int i = ptr + d - 1;i >= ptr;i--){
buf[i] = (byte)('0'+x%10);
x /= 10;
}
ptr += d;
return this;
}
public FastWriter write(double x, int precision)
{
if(x < 0){
write('-');
x = -x;
}
x += Math.pow(10, -precision)/2;
// if(x < 0){ x = 0; }
write((long)x).write(".");
x -= (long)x;
for(int i = 0;i < precision;i++){
x *= 10;
write((char)('0'+(int)x));
x -= (int)x;
}
return this;
}
public FastWriter writeln(char c){
return write(c).writeln();
}
public FastWriter writeln(int x){
return write(x).writeln();
}
public FastWriter writeln(long x){
return write(x).writeln();
}
public FastWriter writeln(double x, int precision){
return write(x, precision).writeln();
}
public FastWriter write(int... xs)
{
boolean first = true;
for(int x : xs) {
if (!first) write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter write(long... xs)
{
boolean first = true;
for(long x : xs) {
if (!first) write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter writeln()
{
return write((byte)'\n');
}
public FastWriter writeln(int... xs)
{
return write(xs).writeln();
}
public FastWriter writeln(long... xs)
{
return write(xs).writeln();
}
public FastWriter writeln(char[] line)
{
return write(line).writeln();
}
public FastWriter writeln(char[]... map)
{
for(char[] line : map)write(line).writeln();
return this;
}
public FastWriter writeln(String s)
{
return write(s).writeln();
}
private void innerflush()
{
try {
out.write(buf, 0, ptr);
ptr = 0;
} catch (IOException e) {
throw new RuntimeException("innerflush");
}
}
public void flush()
{
innerflush();
try {
out.flush();
} catch (IOException e) {
throw new RuntimeException("flush");
}
}
public FastWriter print(byte b) { return write(b); }
public FastWriter print(char c) { return write(c); }
public FastWriter print(char[] s) { return write(s); }
public FastWriter print(String s) { return write(s); }
public FastWriter print(int x) { return write(x); }
public FastWriter print(long x) { return write(x); }
public FastWriter print(double x, int precision) { return write(x, precision); }
public FastWriter println(char c){ return writeln(c); }
public FastWriter println(int x){ return writeln(x); }
public FastWriter println(long x){ return writeln(x); }
public FastWriter println(double x, int precision){ return writeln(x, precision); }
public FastWriter print(int... xs) { return write(xs); }
public FastWriter print(long... xs) { return write(xs); }
public FastWriter println(int... xs) { return writeln(xs); }
public FastWriter println(long... xs) { return writeln(xs); }
public FastWriter println(char[] line) { return writeln(line); }
public FastWriter println(char[]... map) { return writeln(map); }
public FastWriter println(String s) { return writeln(s); }
public FastWriter println() { return writeln(); }
}
public void trnz(int... o)
{
for(int i = 0;i < o.length;i++)if(o[i] != 0)System.out.print(i+":"+o[i]+" ");
System.out.println();
}
// print ids which are 1
public void trt(long... o)
{
Queue<Integer> stands = new ArrayDeque<>();
for(int i = 0;i < o.length;i++){
for(long x = o[i];x != 0;x &= x-1)stands.add(i<<6|Long.numberOfTrailingZeros(x));
}
System.out.println(stands);
}
public void tf(boolean... r)
{
for(boolean x : r)System.out.print(x?'#':'.');
System.out.println();
}
public void tf(boolean[]... b)
{
for(boolean[] r : b) {
for(boolean x : r)System.out.print(x?'#':'.');
System.out.println();
}
System.out.println();
}
public void tf(long[]... b)
{
if(INPUT.length() != 0) {
for (long[] r : b) {
for (long x : r) {
for (int i = 0; i < 64; i++) {
System.out.print(x << ~i < 0 ? '#' : '.');
}
}
System.out.println();
}
System.out.println();
}
}
public void tf(long... b)
{
if(INPUT.length() != 0) {
for (long x : b) {
for (int i = 0; i < 64; i++) {
System.out.print(x << ~i < 0 ? '#' : '.');
}
}
System.out.println();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
|
Java
|
["5 3\n1 2 3 2 1", "4 2\n1 2 3 4"]
|
2 seconds
|
["2", "3"]
|
NoteIn the first example all the possible subarrays are $$$[1..3]$$$, $$$[1..4]$$$, $$$[1..5]$$$, $$$[2..4]$$$, $$$[2..5]$$$ and $$$[3..5]$$$ and the median for all of them is $$$2$$$, so the maximum possible median is $$$2$$$ too.In the second example $$$median([3..4]) = 3$$$.
|
Java 11
|
standard input
|
[
"binary search",
"data structures",
"dp"
] |
dddeb7663c948515def967374f2b8812
|
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$).
| 2,100
|
Output one integer $$$m$$$ — the maximum median you can get.
|
standard output
| |
PASSED
|
9bb234ac445aadc3292e541abb547ba0
|
train_110.jsonl
|
1613658900
|
You are given a tree consisting of $$$n$$$ vertices, and $$$m$$$ simple vertex paths. Your task is to find how many pairs of those paths intersect at exactly one vertex. More formally you have to find the number of pairs $$$(i, j)$$$ $$$(1 \leq i < j \leq m)$$$ such that $$$path_i$$$ and $$$path_j$$$ have exactly one vertex in common.
|
512 megabytes
|
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class OnePointPathsLog {
static final int jumps = 19;
static int[][] parents;
static int[] parent; // parents[0]
static int[] deep;
static int[] subTreeSize;
static int[] subTree;
static int[] extCount;
static int vertices;
static List<Set<Integer>> neibours;
static int[] treeLine;
static int tlc;
static int jump(int a, int t) {
for (int i = 0; i < jumps; ++i) {
if (((1 << i) & t) != 0)
a = parents[i][a];
}
return a;
}
static int lca(int a, int b) {
if (deep[a] > deep[b]) a = jump(a, deep[a] - deep[b]);
if (deep[a] < deep[b]) b = jump(b, deep[b] - deep[a]);
if (a == b) return a;
for (int i = jumps - 1; i >= 0; --i) {
if (parents[i][a] != parents[i][b]) {
a = parents[i][a];
b = parents[i][b];
}
}
return parent[a];
}
static class Path {
int from;
int to;
int lca;
int[] neibours;
Path(int a, int b) {
from = a;
to = b;
lca = lca(a, b);
neibours = buildNeibours(a, b, lca);
}
private int[] buildNeibours(int a, int b, int c) {
if(a==b) return new int[]{};
if(a == c) return new int[]{jump(b, deep[b]-deep[c]-1)};
if(b == c) return new int[]{jump(a, deep[a]-deep[c]-1)};
int n1 = jump(b, deep[b]-deep[c]-1);
int n2 = jump(a, deep[a]-deep[c]-1);
return new int[]{Math.min(n1,n2),Math.max(n1, n2)};
}
public void update(int p, int v) {
for(int i = 0; i<neibours.length;++i)
if(neibours[i]==p)
neibours[i] = v;
}
}
static int marker;
static int smallPaths;
private static long findOnes(int root, List<Path> paths) {
if (paths.isEmpty()) return 0;
int n = subTreeSize[root];
// boolean type = false;
//if (n>10000) {
// type = true;
// System.out.println(n);
//}
if (n == 1) {
long p = paths.size();
return p * (p - 1) / 2;
}
if (n == 2) {
long t1 = 0;
long t2 = 0;
long t3 = 0;
for (Path p : paths) {
if (p.from != p.to) ++t3;
else if (p.from == root) ++t1;
else ++t2;
}
return t3 * (t1 + t2) + t1 * (t1 - 1) / 2 + t2 * (t2 - 1) / 2;
}
if(n<10) return findOnesDropRoot(root, paths);
if(paths.size()<300) {
++smallPaths;
}
int child = maxChild(root);
if(subTreeSize[child]*2 <= n) {
//if(type) System.out.println("center");
return findOnesDropRoot(root, paths);
}
// if(type) System.out.println("edge");
while (subTreeSize[child]*3>n) child = maxChild(child);
child = parent[child];
int par = parent[child];
List<Path> inner = new ArrayList<>();
List<Path> outer = new ArrayList<>();
int v = vertices++;
if(v>=subTree.length) while (true);
neibours.get(par).remove(child);
neibours.get(par).add(v);
subTreeSize[v] = 1;
parent[v] = par;
int d = subTreeSize[child] - 1;
while (true) {
subTreeSize[par]-=d;
if(par == root) break;
par = parent[par];
}
++marker;
expandTree(child);
// markSubtree(child, marker);
for(int i = 0; i<tlc; ++i) {
extCount[treeLine[i]] = 0;
subTree[treeLine[i]] = marker;
}
for(Path p: paths) {
if(subTree[p.lca] == marker) {
inner.add(p);
continue;
}
if(subTree[p.from] == marker) {
++extCount[p.from];
p.from = v;
p.update(child, v);
}
if(subTree[p.to] == marker) {
++extCount[p.to];
p.to = v;
p.update(child, v);
}
outer.add(p);
}
// updateExtCount(child);
for(int i = tlc-1; i>0; --i) {
int j = treeLine[i];
extCount[parent[j]]+=extCount[j];
}
long ans = 0;
for(Path p: inner) {
ans+=extCount[p.lca];
for(int i: p.neibours) ans-=extCount[i];
}
return ans + findOnes(root, outer) + findOnes(child, inner);
}
private static int maxChild(int center) {
return neibours.get(center).stream().mapToInt(i -> i)
.reduce((a, b) -> subTreeSize[a] > subTreeSize[b] ? a : b)
.getAsInt();
}
private static long findOnesDropRoot(int root, List<Path> paths) {
List<Path> center = new ArrayList<>();
Map<Integer, List<Path>> inner = new HashMap<>();
Map<Integer, Integer> markers = new HashMap<>();
expandTree(root);
for(Integer i: neibours.get(root)) {
int m = ++marker;
markers.put(m, i);
subTree[i] = m;
extCount[i] = 0;
inner.put(i, new ArrayList<>());
// markSubtree(i, m);
}
for(int i = 1+markers.size(); i<tlc; ++i) {
int v = treeLine[i];
subTree[v] = subTree[parent[v]];
extCount[v] = 0;
}
for(Path p: paths) {
if(p.lca == root) {
++extCount[p.from];
++extCount[p.to];
center.add(p);
} else {
inner.get(markers.get(subTree[p.from])).add(p);
}
}
//updateExtCount(root);
for(int i = tlc-1; i>0; --i) {
int j = treeLine[i];
extCount[parent[j]]+=extCount[j];
}
long ans = findOnes(center);
for(Map.Entry<Integer, List<Path>> p: inner.entrySet()) {
for(Path path: p.getValue()) {
ans+=extCount[path.lca];
for(int i: path.neibours) ans-=extCount[i];
}
ans+=findOnes(p.getKey(), p.getValue());
}
return ans;
}
static class PairCounter {
Map<Integer, Integer> ones = new HashMap<>();
Map<Long, Integer> pairs = new HashMap<>();
int getAndAppend(int[] neibours) {
if (neibours.length == 0) return 0;
if (neibours.length == 1) {
if (ones.containsKey(neibours[0])) {
int t = ones.get(neibours[0]);
ones.put(neibours[0], t + 1);
return t;
} else {
ones.put(neibours[0], 1);
return 0;
}
}
int t = getAndAppend(new int[]{neibours[0]}) + getAndAppend(new int[]{neibours[1]});
long l = neibours[0] * 1000000L + neibours[1];
if (pairs.containsKey(l)) {
int k = pairs.get(l);
t -= k;
pairs.put(l, k + 1);
} else {
pairs.put(l, 1);
}
return t;
}
}
private static long findOnes(List<Path> center) {
int cnt = 0;
long ans = 0;
PairCounter pcn = new PairCounter();
for (Path p : center) {
ans += cnt - pcn.getAndAppend(p.neibours);
++cnt;
}
return ans;
}
static void expandTree(int vert) {
tlc = 1;
treeLine[0] = vert;
for(int i = 0; i<tlc; ++i) {
int v = treeLine[i];
if (subTreeSize[v]>1)
for(int j: neibours.get(v)) treeLine[tlc++] = j;
}
}
private static void updateExtCount(int vert) {
if(vert>=neibours.size()) return;
for (int i : neibours.get(vert)) {
updateExtCount(i);
extCount[vert] += extCount[i];
}
}
private static void markSubtree(int vert, int m) {
subTree[vert] = m;
extCount[vert] = 0;
if(vert>=neibours.size()) return;
for (int i : neibours.get(vert))
markSubtree(i, m);
}
static BufferedReader input;
static StringTokenizer stoken = new StringTokenizer("");
static String nextString() throws IOException {
while (!stoken.hasMoreTokens()){
String st = input.readLine();
stoken = new StringTokenizer(st);
}
return stoken.nextToken();
}
static int nextInt() throws Exception {
return Integer.parseInt(nextString());
}
public static void main(String[] args) throws Exception{
long l1 = System.currentTimeMillis();
input = new BufferedReader(
new InputStreamReader(System.in)
);
//Scanner scanner = // new Scanner(new File("bigtest3.txt"));
//new Scanner(System.in);
int n = /*scanner.*/nextInt();
vertices = n;
int nv = (int)(1.3*n);
parents = new int[jumps][];
parent = new int[nv];
parents[0] = parent;
for(int i = 1; i<jumps; ++i) parents[i] = new int[n];
deep = new int[n];
subTreeSize = new int[nv];
subTree = new int[nv];
extCount = new int[nv];
treeLine = new int[nv];
neibours = IntStream.range(0, n).mapToObj(i -> new HashSet<Integer>()).collect(Collectors.toList());
for (int i = 1; i < n; ++i) {
int a = /*scanner.*/nextInt() - 1;
int b = /*scanner.*/nextInt() - 1;
neibours.get(a).add(b);
neibours.get(b).add(a);
}
initDSP(0, 0, 0);
for (int i = 1; i < jumps; ++i)
for (int j = 0; j < n; ++j)
parents[i][j] = parents[i - 1][parents[i - 1][j]];
for(int i = 0; i<n; ++i) neibours.get(i).remove(parent[i]);
List<Path> paths = new ArrayList<>();
int m = /*scanner.*/nextInt();
for(int i = 0; i<m; ++i) paths.add(new Path(/*scanner.*/nextInt()-1, /*scanner.*/nextInt() - 1));
System.out.println(findOnes(0, paths));
//System.out.println(System.currentTimeMillis() - l1);
//System.out.println(vertices);
//System.out.println(smallPaths);
}
private static void initDSP(int vert, int prev, int d) {
parent[vert] = prev;
deep[vert] = d++;
subTreeSize[vert] = 1;
for (int i : neibours.get(vert))
if (i != prev) {
initDSP(i, vert, d);
subTreeSize[vert] += subTreeSize[i];
}
}
}
|
Java
|
["5\n1 2\n1 3\n1 4\n3 5\n4\n2 3\n2 4\n3 4\n3 5", "1\n3\n1 1\n1 1\n1 1", "5\n1 2\n1 3\n1 4\n3 5\n6\n2 3\n2 4\n3 4\n3 5\n1 1\n1 2"]
|
6 seconds
|
["2", "3", "7"]
|
NoteThe tree in the first example and paths look like this. Pairs $$$(1,4)$$$ and $$$(3,4)$$$ intersect at one vertex.In the second example all three paths contain the same single vertex, so all pairs $$$(1, 2)$$$, $$$(1, 3)$$$ and $$$(2, 3)$$$ intersect at one vertex.The third example is the same as the first example with two additional paths. Pairs $$$(1,4)$$$, $$$(1,5)$$$, $$$(2,5)$$$, $$$(3,4)$$$, $$$(3,5)$$$, $$$(3,6)$$$ and $$$(5,6)$$$ intersect at one vertex.
|
Java 8
|
standard input
|
[
"combinatorics",
"data structures",
"dfs and similar",
"dp",
"trees"
] |
632afd3c714e4ab34fbc474f9f99d345
|
First line contains a single integer $$$n$$$ $$$(1 \leq n \leq 3 \cdot 10^5)$$$. Next $$$n - 1$$$ lines describe the tree. Each line contains two integers $$$u$$$ and $$$v$$$ $$$(1 \leq u, v \leq n)$$$ describing an edge between vertices $$$u$$$ and $$$v$$$. Next line contains a single integer $$$m$$$ $$$(1 \leq m \leq 3 \cdot 10^5)$$$. Next $$$m$$$ lines describe paths. Each line describes a path by it's two endpoints $$$u$$$ and $$$v$$$ $$$(1 \leq u, v \leq n)$$$. The given path is all the vertices on the shortest path from $$$u$$$ to $$$v$$$ (including $$$u$$$ and $$$v$$$).
| 2,600
|
Output a single integer — the number of pairs of paths that intersect at exactly one vertex.
|
standard output
| |
PASSED
|
add1cfa5983b29aa99b33de5d976f269
|
train_110.jsonl
|
1613658900
|
You are given a tree consisting of $$$n$$$ vertices, and $$$m$$$ simple vertex paths. Your task is to find how many pairs of those paths intersect at exactly one vertex. More formally you have to find the number of pairs $$$(i, j)$$$ $$$(1 \leq i < j \leq m)$$$ such that $$$path_i$$$ and $$$path_j$$$ have exactly one vertex in common.
|
512 megabytes
|
/**
* author: derrick20
* created: 2/20/21 10:47 PM
*/
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class PairOfPaths {
static FastScanner sc = new FastScanner();
static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) {
N = sc.nextInt();
adjList = new ArrayList[N];
for (int i = 0; i < N; i++) {
adjList[i] = new ArrayList<>();
}
for (int i = 0; i < N - 1; i++) {
int u = sc.nextInt() - 1;
int v = sc.nextInt() - 1;
adjList[u].add(v);
adjList[v].add(u);
}
setupLCA(N);
subtree = new long[N];
nonLCA = new long[N];
outside = new HashMap[N];
Arrays.setAll(outside, i -> new HashMap<>());
duplicates = new HashMap[N];
Arrays.setAll(duplicates, i -> new HashMap<>());
up = new long[N];
int M = sc.nextInt();
for (int p = 0; p < M; p++) {
int u = sc.nextInt() - 1;
int v = sc.nextInt() - 1;
int lca = leastCommonAncestor(u, v);
for (int node : new int[]{u, v}) {
if (node != lca) {
int anc = lastBelow(node, lca);
nonLCA[node]++;
outside[lca].merge(anc, 1L, Long::sum);
up[node]++;
up[anc]--;
}
}
subtree[lca]++;
if (u != lca && v != lca) {
// must be from different subtrees, identify with child node
int ancU = lastBelow(u, lca);
int ancV = lastBelow(v, lca);
if (ancU != ancV) {
duplicates[lca].merge(new Pair(ancU, ancV), 1L, Long::sum);
}
}
}
propagate(0, -1);
long ans = 0;
for (int lca = 0; lca < N; lca++) {
long allPairs = subtree[lca] * (subtree[lca] - 1) / 2;
long upward = subtree[lca] * nonLCA[lca];
// two ways for us to include an upward path:
// either use a non-lca path starting at this lca
// or, use something that starts in a child branch and goes up
long overCounted = 0;
for (int adj : adjList[lca]) {
if (adj != parent[0][lca]) {
long outPaths = outside[lca].getOrDefault(adj, 0L);
upward += up[adj] * (subtree[lca] - outPaths);
overCounted += outPaths * (outPaths - 1) / 2;
}
}
long underCounted = 0;
for (long dup : duplicates[lca].values()) {
underCounted += dup * (dup - 1) / 2;
}
long downward = allPairs - overCounted + underCounted;
ans += downward + upward;
}
out.println(ans);
out.close();
}
static int N;
static int[] depth;
static int[][] parent;
static ArrayList<Integer>[] adjList;
static long[] subtree, nonLCA, up;
static HashMap<Integer, Long>[] outside;
static HashMap<Pair, Long>[] duplicates;
static void propagate(int node, int par) {
for (int adj : adjList[node]) {
if (adj != par) {
propagate(adj, node);
up[node] += up[adj];
}
}
}
static class Pair {
int u, v;
public Pair(int uu, int vv) {
u = min(uu, vv); v = max(uu, vv);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair pair = (Pair) o;
return u == pair.u && v == pair.v;
}
@Override
public int hashCode() {
return Objects.hash(u, v);
}
}
static int lastBelow(int curr, int goal) {
for (int k = parent.length - 1; k >= 0; k--) {
if (depth[parent[k][curr]] > depth[goal]) {
curr = parent[k][curr];
}
}
ASSERT(parent[0][curr] == goal);
return curr;
}
static void dfsSetup(int node, int par, int dep) {
depth[node] = dep;
for (int adj : adjList[node]) {
if (adj != par) {
parent[0][adj] = node;
dfsSetup(adj, node, dep + 1);
}
}
}
static int leastCommonAncestor(int u, int v) {
if (depth[u] < depth[v]) {
u = u ^ v ^ (v = u);
}
for (int k = parent.length - 1; k >= 0; k--) {
int par = parent[k][u];
if (depth[par] >= depth[v]) {
u = par;
}
}
if (u == v) {
return u;
} else {
for (int k = parent.length - 1; k >= 0; k--) {
if (parent[k][u] != parent[k][v]) {
u = parent[k][u];
v = parent[k][v];
}
}
return parent[0][u];
}
}
static void setupLCA(int N) {
depth = new int[N];
int LOG = -1;
while ((1 << (LOG + 1)) < N) {
LOG++;
}
parent = new int[LOG + 1][N];
dfsSetup(0, -1, 0); // if too many parent levels, just set to root
for (int k = 1; k <= parent.length - 1; k++) {
for (int node = 0; node < N; node++) {
parent[k][node] = parent[k - 1][parent[k - 1][node]];
}
}
}
static 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);
}
}
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++];
}
int nextInt() {
return (int) nextLong();
}
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;
}
double nextDouble() {
boolean neg = false;
if (c == NC) c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-') neg = true;
}
double cur = nextLong();
if (c != '.') {
return neg ? -cur : cur;
} else {
double frac = nextLong() / cnt;
return neg ? -cur - frac : cur + frac;
}
}
String next() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
boolean hasNext() {
if (c > 32) return true;
while (true) {
c = getChar();
if (c == NC) return false;
else if (c > 32) return true;
}
}
}
static void ASSERT(boolean assertion, String message) {
if (!assertion) throw new AssertionError(message);
}
static void ASSERT(boolean assertion) {
if (!assertion) throw new AssertionError();
}
}
|
Java
|
["5\n1 2\n1 3\n1 4\n3 5\n4\n2 3\n2 4\n3 4\n3 5", "1\n3\n1 1\n1 1\n1 1", "5\n1 2\n1 3\n1 4\n3 5\n6\n2 3\n2 4\n3 4\n3 5\n1 1\n1 2"]
|
6 seconds
|
["2", "3", "7"]
|
NoteThe tree in the first example and paths look like this. Pairs $$$(1,4)$$$ and $$$(3,4)$$$ intersect at one vertex.In the second example all three paths contain the same single vertex, so all pairs $$$(1, 2)$$$, $$$(1, 3)$$$ and $$$(2, 3)$$$ intersect at one vertex.The third example is the same as the first example with two additional paths. Pairs $$$(1,4)$$$, $$$(1,5)$$$, $$$(2,5)$$$, $$$(3,4)$$$, $$$(3,5)$$$, $$$(3,6)$$$ and $$$(5,6)$$$ intersect at one vertex.
|
Java 8
|
standard input
|
[
"combinatorics",
"data structures",
"dfs and similar",
"dp",
"trees"
] |
632afd3c714e4ab34fbc474f9f99d345
|
First line contains a single integer $$$n$$$ $$$(1 \leq n \leq 3 \cdot 10^5)$$$. Next $$$n - 1$$$ lines describe the tree. Each line contains two integers $$$u$$$ and $$$v$$$ $$$(1 \leq u, v \leq n)$$$ describing an edge between vertices $$$u$$$ and $$$v$$$. Next line contains a single integer $$$m$$$ $$$(1 \leq m \leq 3 \cdot 10^5)$$$. Next $$$m$$$ lines describe paths. Each line describes a path by it's two endpoints $$$u$$$ and $$$v$$$ $$$(1 \leq u, v \leq n)$$$. The given path is all the vertices on the shortest path from $$$u$$$ to $$$v$$$ (including $$$u$$$ and $$$v$$$).
| 2,600
|
Output a single integer — the number of pairs of paths that intersect at exactly one vertex.
|
standard output
| |
PASSED
|
e64fece2755dc3fff13c68e2ed6f862c
|
train_110.jsonl
|
1613658900
|
You are given a tree consisting of $$$n$$$ vertices, and $$$m$$$ simple vertex paths. Your task is to find how many pairs of those paths intersect at exactly one vertex. More formally you have to find the number of pairs $$$(i, j)$$$ $$$(1 \leq i < j \leq m)$$$ such that $$$path_i$$$ and $$$path_j$$$ have exactly one vertex in common.
|
512 megabytes
|
/**
* author: derrick20
* created: 2/20/21 10:47 PM
*/
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class PairOfPaths {
static FastScanner sc = new FastScanner();
static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) {
N = sc.nextInt();
adjList = new ArrayList[N];
for (int i = 0; i < N; i++) {
adjList[i] = new ArrayList<>();
}
for (int i = 0; i < N - 1; i++) {
int u = sc.nextInt() - 1;
int v = sc.nextInt() - 1;
adjList[u].add(v);
adjList[v].add(u);
}
setupLCA();
subtree = new long[N];
nonLCA = new long[N];
outside = new HashMap[N];
Arrays.setAll(outside, i -> new HashMap<>());
duplicates = new HashMap[N];
Arrays.setAll(duplicates, i -> new HashMap<>());
up = new long[N];
int M = sc.nextInt();
for (int p = 0; p < M; p++) {
int u = sc.nextInt() - 1;
int v = sc.nextInt() - 1;
int lca = leastCommonAncestor(u, v);
for (int node : new int[]{u, v}) {
if (node != lca) {
int anc = lastBelow(node, lca);
nonLCA[node]++;
outside[lca].merge(anc, 1L, Long::sum);
up[node]++;
up[anc]--;
}
}
subtree[lca]++;
if (u != lca && v != lca) {
// must be from different subtrees, identify with child node
int ancU = lastBelow(u, lca);
int ancV = lastBelow(v, lca);
if (ancU != ancV) {
duplicates[lca].merge(new Pair(ancU, ancV), 1L, Long::sum);
}
}
}
propagate(0, -1);
long ans = 0;
for (int lca = 0; lca < N; lca++) {
long allPairs = subtree[lca] * (subtree[lca] - 1) / 2;
long upward = subtree[lca] * nonLCA[lca];
// two ways for us to include an upward path:
// either use a non-lca path starting at this lca
// or, use something that starts in a child branch and goes up
long overCounted = 0;
for (int adj : adjList[lca]) {
if (adj != firstParents[lca]) {
long outPaths = outside[lca].getOrDefault(adj, 0L);
upward += up[adj] * (subtree[lca] - outPaths);
// System.out.println("For adj = " + adj + " outpaths = " + outPaths);
overCounted += outPaths * (outPaths - 1) / 2;
}
}
long underCounted = 0;
for (long dup : duplicates[lca].values()) {
underCounted += dup * (dup - 1) / 2;
}
long downward = allPairs - overCounted + underCounted;
// System.out.println(downward + " " + upward);
ans += downward + upward;
}
out.println(ans);
out.close();
}
/*
8
1 2
2 3
3 4
4 5
4 6
5 7
6 8
5
7 8
7 8
1 4
1 4
1 4
*/
static int N;
static int maxDepth;
static int[] depth;
static int[][] parent;
static int[] firstParents;
static ArrayList<Integer>[] adjList;
static long[] subtree, nonLCA, up;
static HashMap<Integer, Long>[] outside;
static HashMap<Pair, Long>[] duplicates;
static void propagate(int node, int par) {
for (int adj : adjList[node]) {
if (adj != par) {
propagate(adj, node);
up[node] += up[adj];
}
}
}
static class Pair {
int u, v;
public Pair(int uu, int vv) {
u = min(uu, vv); v = max(uu, vv);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair pair = (Pair) o;
return u == pair.u && v == pair.v;
}
@Override
public int hashCode() {
return Objects.hash(u, v);
}
}
static int lastBelow(int curr, int goal) {
for (int k = parent.length - 1; k >= 0; k--) {
if (depth[parent[k][curr]] > depth[goal]) {
curr = parent[k][curr];
}
}
ASSERT(firstParents[curr] == goal);
return curr;
}
static void setupLCA() {
maxDepth = 0;
depth = new int[N];
firstParents = new int[N];
firstParents[0] = 0;
depth[0] = 0;
dfs(0);
int power = 1;
while (1 << power <= maxDepth) {
power++;
}
parent = new int[power][N];
for (int node = 0; node < N; node++) {
parent[0][node] = firstParents[node];
}
for (int p = 1; p < parent.length; p++) {
for (int i = 0; i < N; i++) {
parent[p][i] = -1;
}
}
for (int p = 1; p < parent.length; p++) {
for (int node = 0; node < N; node++) {
if (parent[p - 1][node] != -1) {
int myParent = parent[p - 1][node];
parent[p][node] = parent[p-1][myParent];
}
}
}
}
static void dfs(int node) {
for (int adj : adjList[node]) {
if (adj != firstParents[node]) {
firstParents[adj] = node;
depth[adj] = depth[node] + 1;
maxDepth = Math.max(maxDepth, depth[adj]);
dfs(adj);
}
}
}
static int leastCommonAncestor(int a, int b) {
if (depth[b] > depth[a]) {
int c = a;
a = b;
b = c;
}
int dist = depth[a] - depth[b];
while (dist > 0) {
int power = (int) (Math.log(dist) / Math.log(2));
a = parent[power][a];
dist -= 1 << power;
}
if (a == b) {
return a;
}
for (int j = parent.length - 1; j >= 0; j--) {
if (parent[j][a] != parent[j][b]) {
a = parent[j][a];
b = parent[j][b];
}
}
return parent[0][a];
}
static 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);
}
}
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++];
}
int nextInt() {
return (int) nextLong();
}
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;
}
double nextDouble() {
boolean neg = false;
if (c == NC) c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-') neg = true;
}
double cur = nextLong();
if (c != '.') {
return neg ? -cur : cur;
} else {
double frac = nextLong() / cnt;
return neg ? -cur - frac : cur + frac;
}
}
String next() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
boolean hasNext() {
if (c > 32) return true;
while (true) {
c = getChar();
if (c == NC) return false;
else if (c > 32) return true;
}
}
}
static void ASSERT(boolean assertion, String message) {
if (!assertion) throw new AssertionError(message);
}
static void ASSERT(boolean assertion) {
if (!assertion) throw new AssertionError();
}
}
|
Java
|
["5\n1 2\n1 3\n1 4\n3 5\n4\n2 3\n2 4\n3 4\n3 5", "1\n3\n1 1\n1 1\n1 1", "5\n1 2\n1 3\n1 4\n3 5\n6\n2 3\n2 4\n3 4\n3 5\n1 1\n1 2"]
|
6 seconds
|
["2", "3", "7"]
|
NoteThe tree in the first example and paths look like this. Pairs $$$(1,4)$$$ and $$$(3,4)$$$ intersect at one vertex.In the second example all three paths contain the same single vertex, so all pairs $$$(1, 2)$$$, $$$(1, 3)$$$ and $$$(2, 3)$$$ intersect at one vertex.The third example is the same as the first example with two additional paths. Pairs $$$(1,4)$$$, $$$(1,5)$$$, $$$(2,5)$$$, $$$(3,4)$$$, $$$(3,5)$$$, $$$(3,6)$$$ and $$$(5,6)$$$ intersect at one vertex.
|
Java 8
|
standard input
|
[
"combinatorics",
"data structures",
"dfs and similar",
"dp",
"trees"
] |
632afd3c714e4ab34fbc474f9f99d345
|
First line contains a single integer $$$n$$$ $$$(1 \leq n \leq 3 \cdot 10^5)$$$. Next $$$n - 1$$$ lines describe the tree. Each line contains two integers $$$u$$$ and $$$v$$$ $$$(1 \leq u, v \leq n)$$$ describing an edge between vertices $$$u$$$ and $$$v$$$. Next line contains a single integer $$$m$$$ $$$(1 \leq m \leq 3 \cdot 10^5)$$$. Next $$$m$$$ lines describe paths. Each line describes a path by it's two endpoints $$$u$$$ and $$$v$$$ $$$(1 \leq u, v \leq n)$$$. The given path is all the vertices on the shortest path from $$$u$$$ to $$$v$$$ (including $$$u$$$ and $$$v$$$).
| 2,600
|
Output a single integer — the number of pairs of paths that intersect at exactly one vertex.
|
standard output
| |
PASSED
|
f2a07cce5fd669064dd68cde56b194bb
|
train_110.jsonl
|
1613658900
|
You are given a tree consisting of $$$n$$$ vertices, and $$$m$$$ simple vertex paths. Your task is to find how many pairs of those paths intersect at exactly one vertex. More formally you have to find the number of pairs $$$(i, j)$$$ $$$(1 \leq i < j \leq m)$$$ such that $$$path_i$$$ and $$$path_j$$$ have exactly one vertex in common.
|
512 megabytes
|
import java.io.*;
import java.util.*;
/*
polyakoff
*/
public class Main {
static FastReader in;
static PrintWriter out;
static Random rand = new Random();
static final int oo = (int) 1e9 + 10;
static final long OO = (long) 2e18 + 10;
static final int MOD = (int) 1e9 + 7;
static final int LOGN = 22;
static int n, m;
static ArrayList<Integer>[] g;
static int[][] paths, par, childs, cntDown1, cntUp2;
static int[] tin, tout, cntUp1;
static ArrayList<Pair>[] forks;
static HashMap<Long, Integer>[] cntDown2;
static class Pair {
int i1, i2;
Pair(int i1, int i2) {
this.i1 = i1;
this.i2 = i2;
}
}
static int timer = 0;
static void dfs0(int v, int from) {
tin[v] = timer++;
par[v][0] = from;
for (int i = 1; i < LOGN; i++) {
par[v][i] = par[par[v][i - 1]][i - 1];
}
for (int to : g[v]) {
if (to == from)
continue;
dfs0(to, v);
}
tout[v] = timer++;
}
static boolean isAncestor(int v, int u) {
return tin[v] < tin[u] && tout[u] < tout[v];
}
static int lca(int v, int u) {
if (v == u) return v;
if (isAncestor(v, u)) return v;
if (isAncestor(u, v)) return u;
for (int i = LOGN - 1; i >= 0; i--) {
if (!isAncestor(par[v][i], u))
v = par[v][i];
}
return par[v][0];
}
// get index of child in which tree u is
static int getChild(int v, int u) {
int low = 0, high = childs[v].length - 1;
while (low < high) {
int mid = (low + high) / 2;
if (childs[v][mid] == u || isAncestor(childs[v][mid], u))
return mid;
if (tout[childs[v][mid]] < tin[u])
low = mid + 1;
else
high = mid - 1;
}
return low;
}
static void dfs1(int v, int from) {
int i = 0;
for (int to : g[v]) {
if (to == from)
continue;
dfs1(to, v);
cntUp1[v] += cntUp1[to];
cntUp2[v][i++] = cntUp1[to];
}
for (Pair p : forks[v]) {
if (p.i1 != -1) {
cntUp1[v]--;
cntUp2[v][p.i1]--;
}
if (p.i2 != -1) {
cntUp1[v]--;
cntUp2[v][p.i2]--;
}
}
}
static void solve() {
n = in.nextInt();
g = new ArrayList[n]; Arrays.setAll(g, i -> new ArrayList<>());
for (int i = 0; i < n - 1; i++) {
int v = in.nextInt() - 1;
int u = in.nextInt() - 1;
g[v].add(u);
g[u].add(v);
}
m = in.nextInt();
paths = new int[m][3];
for (int i = 0; i < m; i++) {
int v = in.nextInt() - 1;
int u = in.nextInt() - 1;
paths[i][0] = v;
paths[i][1] = u;
}
par = new int[n][LOGN];
tin = new int[n];
tout = new int[n];
dfs0(0, 0);
childs = new int[n][];
childs[0] = new int[g[0].size()];
for (int i = 1; i < n; i++) {
childs[i] = new int[g[i].size() - 1];
}
forks = new ArrayList[n]; Arrays.setAll(forks, i -> new ArrayList<>());
cntDown1 = new int[n][]; Arrays.setAll(cntDown1, i -> new int[childs[i].length]);
cntDown2 = new HashMap[n]; Arrays.setAll(cntDown2, i -> new HashMap<>());
for (int v = 0; v < n; v++) {
int i = 0;
for (int to : g[v]) {
if (to == par[v][0])
continue;
childs[v][i++] = to;
}
}
// prepare for same lca
for (int i = 0; i < m; i++) {
int v = paths[i][0];
int u = paths[i][1];
int lca = lca(v, u);
paths[i][2] = lca;
if (v == u) {
forks[v].add(new Pair(-1, -1));
continue;
}
// indices of childs where v and u are
int i1 = lca != v ? getChild(lca, v) : -1;
int i2 = lca != u ? getChild(lca, u) : -1;
if (i2 < i1) {
int temp = i1;
i1 = i2;
i2 = temp;
}
forks[lca].add(new Pair(i1, i2));
if (i1 != -1)
cntDown1[lca][i1]++;
if (i2 != -1)
cntDown1[lca][i2]++;
if (i1 != -1 && i2 != -1) {
long hash = 1L * i1 * childs[lca].length + i2;
cntDown2[lca].putIfAbsent(hash, 0);
cntDown2[lca].put(hash, cntDown2[lca].get(hash) + 1);
}
}
// prepare for different lca
cntUp1 = new int[n];
cntUp2 = new int[n][]; Arrays.setAll(cntUp2, i -> new int[childs[i].length]);
for (int i = 0; i < m; i++) {
int v = paths[i][0];
int u = paths[i][1];
int lca = paths[i][2];
if (v != lca)
cntUp1[v]++;
if (u != lca)
cntUp1[u]++;
}
dfs1(0, 0);
long ans = 0;
for (int v = 0; v < n; v++) {
int total = forks[v].size();
long cnt = 1L * total * (total - 1);
for (Pair p : forks[v]) {
if (p.i1 != -1)
cnt -= cntDown1[v][p.i1] - 1;
if (p.i2 != -1)
cnt -= cntDown1[v][p.i2] - 1;
if (p.i1 != -1 && p.i2 != -1) {
long hash = 1L * p.i1 * childs[v].length + p.i2;
cnt += cntDown2[v].get(hash) - 1;
}
}
cnt /= 2;
ans += cnt;
}
for (int v = 0; v < n; v++) {
for (Pair p : forks[v]) {
long cnt = cntUp1[v];
if (p.i1 != -1)
cnt -= cntUp2[v][p.i1];
if (p.i2 != -1)
cnt -= cntUp2[v][p.i2];
ans += cnt;
}
}
out.println(ans);
}
public static void main(String[] args) {
in = new FastReader();
out = new PrintWriter(System.out);
int T = 1;
// T = in.nextInt();
while (T-- > 0)
solve();
out.flush();
out.close();
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
FastReader() {
this(System.in);
}
FastReader(String file) throws FileNotFoundException {
this(new FileInputStream(file));
}
FastReader(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String next() {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(nextLine());
}
return st.nextToken();
}
String nextLine() {
String line;
try {
line = br.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return line;
}
}
}
|
Java
|
["5\n1 2\n1 3\n1 4\n3 5\n4\n2 3\n2 4\n3 4\n3 5", "1\n3\n1 1\n1 1\n1 1", "5\n1 2\n1 3\n1 4\n3 5\n6\n2 3\n2 4\n3 4\n3 5\n1 1\n1 2"]
|
6 seconds
|
["2", "3", "7"]
|
NoteThe tree in the first example and paths look like this. Pairs $$$(1,4)$$$ and $$$(3,4)$$$ intersect at one vertex.In the second example all three paths contain the same single vertex, so all pairs $$$(1, 2)$$$, $$$(1, 3)$$$ and $$$(2, 3)$$$ intersect at one vertex.The third example is the same as the first example with two additional paths. Pairs $$$(1,4)$$$, $$$(1,5)$$$, $$$(2,5)$$$, $$$(3,4)$$$, $$$(3,5)$$$, $$$(3,6)$$$ and $$$(5,6)$$$ intersect at one vertex.
|
Java 8
|
standard input
|
[
"combinatorics",
"data structures",
"dfs and similar",
"dp",
"trees"
] |
632afd3c714e4ab34fbc474f9f99d345
|
First line contains a single integer $$$n$$$ $$$(1 \leq n \leq 3 \cdot 10^5)$$$. Next $$$n - 1$$$ lines describe the tree. Each line contains two integers $$$u$$$ and $$$v$$$ $$$(1 \leq u, v \leq n)$$$ describing an edge between vertices $$$u$$$ and $$$v$$$. Next line contains a single integer $$$m$$$ $$$(1 \leq m \leq 3 \cdot 10^5)$$$. Next $$$m$$$ lines describe paths. Each line describes a path by it's two endpoints $$$u$$$ and $$$v$$$ $$$(1 \leq u, v \leq n)$$$. The given path is all the vertices on the shortest path from $$$u$$$ to $$$v$$$ (including $$$u$$$ and $$$v$$$).
| 2,600
|
Output a single integer — the number of pairs of paths that intersect at exactly one vertex.
|
standard output
| |
PASSED
|
d5199e772cdccfd451487a2cdf1faf05
|
train_110.jsonl
|
1613658900
|
You are given a tree consisting of $$$n$$$ vertices, and $$$m$$$ simple vertex paths. Your task is to find how many pairs of those paths intersect at exactly one vertex. More formally you have to find the number of pairs $$$(i, j)$$$ $$$(1 \leq i < j \leq m)$$$ such that $$$path_i$$$ and $$$path_j$$$ have exactly one vertex in common.
|
512 megabytes
|
import java.io.*;
import java.util.*;
import java.lang.*;
public class Main {
public static int inf = (int)1e9+7;
public static int mod = (int)1e9+7;
public static Map<Integer, List<Integer>> map;
public static int[] deep;
public static int[][] dp;
public static int[] ldf;
public static int[] rdf;
public static int[] T;
public static int n;
public static int cnt;
public static int dfn;
public static void main(String[] args) throws IOException, InterruptedException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
Scanner sc = new Scanner(System.in);
//code part
n = Integer.parseInt(reader.readLine());
map = new HashMap<>();
deep = new int[n + 1];
dp = new int[n + 1][21];
ldf = new int[n + 1];
rdf = new int[n + 1];
T = new int[n + 1];
cnt = n;
dfn = 0;
for (int i = 0; i <= n; i++){
map.put(i, new ArrayList<>());
}
for (int i = 0; i < n - 1; i++) {
String[] s = reader.readLine().split("\\s+");
int x = Integer.parseInt(s[0]);
int y = Integer.parseInt(s[1]);
map.get(x).add(y);
map.get(y).add(x);
}
dfs(1, 0);
int m = Integer.parseInt(reader.readLine());
//x, y, a, b, LCA
int[][] paths = new int[m][5];
for (int i = 0; i < m; i++) {
String[] s = reader.readLine().split("\\s+");
int x = Integer.parseInt(s[0]);
int y = Integer.parseInt(s[1]);
paths[i][0] = x;
paths[i][1] = y;
paths[i][4] = LCA(x, y);
paths[i][2] = kthParent(x, deep[x] - deep[paths[i][4]] - 1);
paths[i][3] = kthParent(y, deep[y] - deep[paths[i][4]] - 1);
if(paths[i][2] > paths[i][3]){
int temp = paths[i][0];
paths[i][0] = paths[i][1];
paths[i][1] = temp;
temp = paths[i][2];
paths[i][2] = paths[i][3];
paths[i][3] = temp;
}
}
Arrays.sort(paths, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
if(deep[o1[4]] != deep[o2[4]]){
return deep[o1[4]] - deep[o2[4]];
}else if(o1[4] != o2[4]){
return o1[4] - o2[4];
}else if(o1[2] != o2[2]){
return o2[2] - o1[2];
}else{
return o1[3] - o2[3];
}
}
});
long ans = 0L;
int[] bucket = new int[cnt + 1];
for (int i = 0; i < m; i++){
int j = i;
int count = 0;
while (j < m - 1 && paths[i][4] == paths[j + 1][4]){
j++;
}
//第一种情况,两个路径的LCA相同
for (int k = i; k <= j; k++){
int t = k;
//a相同
while (t < j && paths[t + 1][2] == paths[t][2]){
t++;
}
for (int p = k; p <= t; p++){
ans += count - bucket[paths[p][3]];
}
for (int p = k; p <= t; p++){
bucket[paths[p][2]]++;
bucket[paths[p][3]]++;
}
count += t - k + 1;
k = t;
}
for (int k = i; k <= j; k++){
bucket[paths[k][2]] = bucket[paths[k][3]] = 0;
}
//第二种情况,两个路径的LCA不同,但是一个路径的LCA在另外一条路径上
for (int k = i; k <= j; k++){
ans += query(rdf[paths[k][4]]) - query(ldf[paths[k][4]] - 1);
if(paths[k][2] <= n){
ans -= query(rdf[paths[k][2]]) - query(ldf[paths[k][2]] - 1);
}
if(paths[k][3] <= n){
ans -= query(rdf[paths[k][3]]) - query(ldf[paths[k][3]] - 1);
}
}
for(int k = i; k <= j; k++){
add(ldf[paths[k][0]]);
add(ldf[paths[k][1]]);
}
i = j;
}
System.out.println(ans);
//code part
sc.close();
writer.flush();
writer.close();
reader.close();
}
public static void dfs(int cur, int fa){
ldf[cur] = ++dfn;
deep[cur] = deep[fa] + 1;
dp[cur][0] = fa;
for(int j = 1; (1 << j) < deep[cur]; j++){
dp[cur][j] = dp[dp[cur][j - 1]][j - 1];
}
for(int x : map.get(cur)){
if(x != fa){
dfs(x, cur);
}
}
rdf[cur] = dfn;
}
//寻找x和y的最近公共祖先
public static int LCA(int x, int y){
if(deep[x] < deep[y]){
int temp = x;
x = y;
y = temp;
}
int d = deep[x] - deep[y];
for (int j = 0; d > 0 ; j++){
if(((d >> j) & 1) == 1){
x = dp[x][j];
d -= (1 << j);
}
}
if(x == y){
return y;
}
for (int j = 20; j >= 0; j--){
if(dp[x][j] != dp[y][j]){
x = dp[x][j];
y = dp[y][j];
}
}
return dp[x][0];
}
//寻找x的第k个祖先
public static int kthParent(int x, int k){
if(k < 0){
return ++cnt;
}
for(int j = 0; k > 0; j++){
if(((k >> j) & 1) == 1){
x = dp[x][j];
k -= 1 << j;
}
}
return x;
}
public static void add(int x){
while (x <= n){
T[x]++;
x += x & -x;
}
}
public static int query(int x){
int sum = 0;
while (x > 0){
sum += T[x];
x -= x & -x;
}
return sum;
}
}
|
Java
|
["5\n1 2\n1 3\n1 4\n3 5\n4\n2 3\n2 4\n3 4\n3 5", "1\n3\n1 1\n1 1\n1 1", "5\n1 2\n1 3\n1 4\n3 5\n6\n2 3\n2 4\n3 4\n3 5\n1 1\n1 2"]
|
6 seconds
|
["2", "3", "7"]
|
NoteThe tree in the first example and paths look like this. Pairs $$$(1,4)$$$ and $$$(3,4)$$$ intersect at one vertex.In the second example all three paths contain the same single vertex, so all pairs $$$(1, 2)$$$, $$$(1, 3)$$$ and $$$(2, 3)$$$ intersect at one vertex.The third example is the same as the first example with two additional paths. Pairs $$$(1,4)$$$, $$$(1,5)$$$, $$$(2,5)$$$, $$$(3,4)$$$, $$$(3,5)$$$, $$$(3,6)$$$ and $$$(5,6)$$$ intersect at one vertex.
|
Java 8
|
standard input
|
[
"combinatorics",
"data structures",
"dfs and similar",
"dp",
"trees"
] |
632afd3c714e4ab34fbc474f9f99d345
|
First line contains a single integer $$$n$$$ $$$(1 \leq n \leq 3 \cdot 10^5)$$$. Next $$$n - 1$$$ lines describe the tree. Each line contains two integers $$$u$$$ and $$$v$$$ $$$(1 \leq u, v \leq n)$$$ describing an edge between vertices $$$u$$$ and $$$v$$$. Next line contains a single integer $$$m$$$ $$$(1 \leq m \leq 3 \cdot 10^5)$$$. Next $$$m$$$ lines describe paths. Each line describes a path by it's two endpoints $$$u$$$ and $$$v$$$ $$$(1 \leq u, v \leq n)$$$. The given path is all the vertices on the shortest path from $$$u$$$ to $$$v$$$ (including $$$u$$$ and $$$v$$$).
| 2,600
|
Output a single integer — the number of pairs of paths that intersect at exactly one vertex.
|
standard output
| |
PASSED
|
15998d631e934fdca20f36cc5c927d6e
|
train_110.jsonl
|
1613658900
|
You are given a tree consisting of $$$n$$$ vertices, and $$$m$$$ simple vertex paths. Your task is to find how many pairs of those paths intersect at exactly one vertex. More formally you have to find the number of pairs $$$(i, j)$$$ $$$(1 \leq i < j \leq m)$$$ such that $$$path_i$$$ and $$$path_j$$$ have exactly one vertex in common.
|
512 megabytes
|
//package round703;
import java.io.*;
import java.util.*;
public class F {
InputStream is;
FastWriter out;
String INPUT = "";
void solve()
{
int n = ni();
int[] from = new int[n - 1];
int[] to = new int[n - 1];
for (int i = 0; i < n - 1; i++) {
from[i] = ni() - 1;
to[i] = ni() - 1;
}
int[][] g = packU(n, from, to);
int[][] pars = parents(g, 0);
int[] par = pars[0], ord = pars[1], dep = pars[2];
int Q = ni();
int[][] qs = new int[Q][];
LCAFast2 lf = LCAFast2.build(g, 0);
for(int z = 0;z < Q;z++){
qs[z] = new int[]{ni()-1, ni()-1, -1};
qs[z][2] = lf.lca(qs[z][0], qs[z][1]);
if(qs[z][0] == qs[z][2]){
int d = qs[z][0]; qs[z][0] = qs[z][1]; qs[z][1] = d;
}
}
Arrays.sort(qs, (x, y) -> x[2] - y[2]);
int[] up = new int[n];
int[] leaf = new int[n];
int[] pin = new int[n];
for(int i = 0;i < Q;i++){
up[qs[i][0]]++;
up[qs[i][1]]++;
up[qs[i][2]] -= 2;
if(qs[i][0] != qs[i][2])leaf[qs[i][0]]++;
if(qs[i][1] != qs[i][2])leaf[qs[i][1]]++;
if(qs[i][0] == qs[i][1])pin[qs[i][0]]++;
}
for(int i = n-1;i >= 1;i--){
int cur = ord[i];
up[par[cur]] += up[cur];
}
int p = 0;
int[] temp = new int[n];
long ans = 0;
int[] upm = new int[n];
for(int i = 0;i < n;i++){
int cur = i;
int op = p;
while(p < Q && qs[p][2] == i)p++;
ans += (long)(p-op-pin[cur]) * (up[cur]+pin[cur]);
ans += (long)pin[cur] * up[cur];
// tr("aaa", cur, ans, op, p, leaf[cur], pin[cur], up[cur], pin[cur]);
for(int e : g[cur]){
if(par[cur] == e)continue;
upm[e] = up[e];
}
for(int k = op;k < p;k++) {
int[] q = qs[k];
if(q[1] != q[2]) {
int ln = lf.anc(q[0], dep[q[0]] - dep[q[2]] - 1);
int rn = lf.anc(q[1], dep[q[1]] - dep[q[2]] - 1);
upm[ln]--;
upm[rn]--;
}else if(q[0] != q[2]) {
int ln = lf.anc(q[0], dep[q[0]] - dep[q[2]] - 1);
upm[ln]--;
}
}
long lans = 0;
lans += (long)(p-op-pin[cur]) * (p-op-pin[cur]);
Map<Long, Integer> map = new HashMap<>();
for(int k = op;k < p;k++){
int[] q = qs[k];
if(q[1] != q[2]) {
int ln = lf.anc(q[0], dep[q[0]] - dep[q[2]] - 1);
int rn = lf.anc(q[1], dep[q[1]] - dep[q[2]] - 1);
lans -= temp[ln] * 2 + 1;
lans -= temp[rn] * 2 + 1;
ans -= upm[ln];
ans -= upm[rn];
temp[ln]++;
temp[rn]++;
if (ln > rn) {
int d = ln;
ln = rn;
rn = d;
}
map.merge((long) ln << 32 | rn, 1, Integer::sum);
}else if(q[0] != q[2]){
int ln = lf.anc(q[0], dep[q[0]] - dep[q[2]] - 1);
lans -= temp[ln] * 2 + 1;
temp[ln]++;
ans -= upm[ln];
int rn = q[2];
}
}
for(int t : map.values()){
lans += (long)t*t;
}
ans += lans/2;
ans += (long)pin[cur] * (pin[cur]-1)/2;
// tr(cur, ans, lans);
for(int e : g[cur]){
if(par[cur] == e)continue;
temp[e] = 0;
}
}
out.println(ans);
}
public static class LCAFast2 {
public int n, h;
public int[][] bigst;
public int[][] bigind;
public long[][] smallb;
public int[] vs, first, deps;
public int lca(int a, int b)
{
return vs[rmqpos(Math.min(first[a], first[b]), Math.max(first[a], first[b]))];
}
public int pointOnPath(int a, int b, int dfroma)
{
int lca = lca(a, b);
if(dfroma <= dep(a) - dep(lca)){
return anc(a, dfroma);
}
int dfromb = dep(b) - dep(lca) - (dfroma - (dep(a) - dep(lca)));
if(dfromb < 0)return -1;
return anc(b, dfromb);
}
public int anc(int a, int d)
{
int da = dep(a);
if(da < d)return -1;
int danc = da - d;
int low = 0, high = first[a] + 1;
while(high - low > 1){
int h = high+low>>1;
if(rmqval(h, first[a]) <= danc){
low = h;
}else {
high = h;
}
}
return vs[low];
}
public int d(int a, int b)
{
return dep(a) + dep(b) - 2 * rmqval(Math.min(first[a], first[b]), Math.max(first[a], first[b]));
}
public int dep(int x)
{
return deps[first[x]];
}
public int rmqpos(int l, int r)
{
if(l > r)return -1;
int cl = l>>>6;
int cr = r>>>6;
if(cl == cr){
return argmax(smallb[l&63][cl], r-l+1) + l;
}else{
int min = deps[l] - max(smallb[l&63][cl], 63-(l&63)+1);
int pos = argmax(smallb[l&63][cl], 63-(l&63)+1) + l;
{
int can = deps[r>>>6<<6] - max(smallb[0][cr], (r&63)-0+1);
if(can < min){
min = can;
pos = argmax(smallb[0][cr], (r&63)-0+1) + (r>>>6<<6);
}
}
if(cl+1 <= cr-1){
int len = (cr-1)-(cl+1)+1;
int h = 31-Integer.numberOfLeadingZeros(len);
{
int can = bigst[h][cl+1];
if(can < min){
min = can;
pos = bigind[h][cl+1];
}
}
{
int can = bigst[h][cr-1-(1<<h)+1];
if(can < min){
min = can;
pos = bigind[h][cr-1-(1<<h)+1];
}
}
}
return pos;
}
}
public int rmqval(int l, int r)
{
if(l > r)return -1;
int cl = l>>>6;
int cr = r>>>6;
if(cl == cr){
return deps[l] - max(smallb[l&63][cl], r-l+1);
}else{
int min = deps[l] - max(smallb[l&63][cl], 63-(l&63)+1);
min = Math.min(min, deps[r>>>6<<6] - max(smallb[0][cr], (r&63)-0+1));
if(cl+1 <= cr-1){
int len = (cr-1)-(cl+1)+1;
int h = 31-Integer.numberOfLeadingZeros(len);
min = Math.min(min, bigst[h][cl+1]);
min = Math.min(min, bigst[h][cr-1-(1<<h)+1]);
}
return min;
}
}
public static LCAFast2 build(int[][] g, int root)
{
LCAFast2 ret = new LCAFast2();
int[][] et = eulerTour(g, root);
int[] vs = et[0], deps = et[1], first = et[2];
ret.vs = vs;
ret.first = first;
ret.deps = deps;
int n = deps.length;
int u = n+63>>>6;
int h = 31-Integer.numberOfLeadingZeros(u) + 1;
int[][] bigst = new int[h][];
int[][] bigind = new int[h][];
int[] cup = new int[u];
int[] cupind = new int[u];
Arrays.fill(cup, Integer.MAX_VALUE);
for(int i = 0;i < n;i++){
if(deps[i] < cup[i>>>6]){
cup[i>>>6] = deps[i];
cupind[i>>>6] = i;
}
}
bigst[0] = cup;
bigind[0] = cupind;
for(int i = 1;i < h;i++){
bigst[i] = new int[u-(1<<i)+1];
bigind[i] = new int[u-(1<<i)+1];
for(int j = 0;j + (1<<i) <= u;j++){
if(bigst[i-1][j] < bigst[i-1][j+(1<<i-1)]){
bigst[i][j] = bigst[i-1][j];
bigind[i][j] = bigind[i-1][j];
}else{
bigst[i][j] = bigst[i-1][j+(1<<i-1)];
bigind[i][j] = bigind[i-1][j+(1<<i-1)];
}
}
}
long[][] smallb = new long[64][u];
for(int i = 0;i < u;i++){
long x = 0;
for(int j = 0;j < 63 && (i<<6|j+1) < n;j++){
if(deps[i<<6|j] > deps[i<<6|j+1]){
x |= 1L<<j;
}
}
long val = 0;
for(int j = 63;j >= 0;j--){
val <<= 1;
if(x<<~j<0){
val |= 1L;
}else{
val &= val - 1;
}
smallb[j][i] = val;
}
//
// for(int j = 0;j < 64;j++){
// smallb[j][i] = make(x>>>j);
// }
}
ret.n = n; ret.h = h;
ret.bigst = bigst;
ret.bigind = bigind;
ret.smallb = smallb;
return ret;
}
public static int[][] eulerTour(int[][] g, int root)
{
int n = g.length;
int[] vs = new int[2*n-1];
int[] deps = new int[2*n-1];
int[] first = new int[n];
Arrays.fill(first, -1);
int p = 0;
int[] stack = new int[n];
int[] inds = new int[n];
int sp = 0;
stack[sp++] = root;
outer:
while(sp > 0){
int cur = stack[sp-1], ind = inds[sp-1];
vs[p] = cur;
deps[p] = sp-1;
if(first[cur] == -1)first[cur] = p;
p++;
while(ind < g[cur].length){
int nex = g[cur][ind++];
if(first[nex] == -1){
inds[sp-1] = ind;
stack[sp] = nex;
inds[sp] = 0;
sp++;
continue outer;
}
}
inds[sp-1] = ind;
if(ind == g[cur].length)sp--;
}
return new int[][]{vs, deps, first};
}
// TinyRMQ
public static long make(long x)
{
int h = 0;
int max = 0;
long ret = 0;
for(int i = 0;i < 64;i++){
if(x<<~i<0){
h++;
}else{
h--;
}
if(h > max){
max = h;
ret |= 1L<<i;
}
}
return ret;
}
public static int max(long x, int r)
{
assert r > 0;
return Long.bitCount(x&(1L<<r-1)-1);
}
public static int argmax(long x, int r)
{
assert r > 0;
return 64-Long.numberOfLeadingZeros(x&(1L<<r-1)-1);
}
}
public static int[][] parents(int[][] g, int root) {
int n = g.length;
int[] par = new int[n];
Arrays.fill(par, -1);
int[] depth = new int[n];
depth[0] = 0;
int[] q = new int[n];
q[0] = root;
for (int p = 0, r = 1; p < r; p++) {
int cur = q[p];
for (int nex : g[cur]) {
if (par[cur] != nex) {
q[r++] = nex;
par[nex] = cur;
depth[nex] = depth[cur] + 1;
}
}
}
return new int[][]{par, q, depth};
}
public static int[][] packU(int n, int[] from, int[] to) {
return packU(n, from, to, from.length);
}
public static int[][] packU(int n, int[] from, int[] to, int sup) {
int[][] g = new int[n][];
int[] p = new int[n];
for (int i = 0; i < sup; i++) p[from[i]]++;
for (int i = 0; i < sup; i++) p[to[i]]++;
for (int i = 0; i < n; i++) g[i] = new int[p[i]];
for (int i = 0; i < sup; i++) {
g[from[i]][--p[from[i]]] = to[i];
g[to[i]][--p[to[i]]] = from[i];
}
return g;
}
void run() throws Exception
{
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new FastWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new F().run(); }
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private long[] nal(int n)
{
long[] a = new long[n];
for(int i = 0;i < n;i++)a[i] = nl();
return a;
}
private char[][] nm(int n, int m) {
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[][] nmi(int n, int m) {
int[][] map = new int[n][];
for(int i = 0;i < n;i++)map[i] = na(m);
return map;
}
private int ni() { return (int)nl(); }
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
public static class FastWriter
{
private static final int BUF_SIZE = 1<<13;
private final byte[] buf = new byte[BUF_SIZE];
private final OutputStream out;
private int ptr = 0;
private FastWriter(){out = null;}
public FastWriter(OutputStream os)
{
this.out = os;
}
public FastWriter(String path)
{
try {
this.out = new FileOutputStream(path);
} catch (FileNotFoundException e) {
throw new RuntimeException("FastWriter");
}
}
public FastWriter write(byte b)
{
buf[ptr++] = b;
if(ptr == BUF_SIZE)innerflush();
return this;
}
public FastWriter write(char c)
{
return write((byte)c);
}
public FastWriter write(char[] s)
{
for(char c : s){
buf[ptr++] = (byte)c;
if(ptr == BUF_SIZE)innerflush();
}
return this;
}
public FastWriter write(String s)
{
s.chars().forEach(c -> {
buf[ptr++] = (byte)c;
if(ptr == BUF_SIZE)innerflush();
});
return this;
}
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;
}
public FastWriter write(int x)
{
if(x == Integer.MIN_VALUE){
return write((long)x);
}
if(ptr + 12 >= BUF_SIZE)innerflush();
if(x < 0){
write((byte)'-');
x = -x;
}
int d = countDigits(x);
for(int i = ptr + d - 1;i >= ptr;i--){
buf[i] = (byte)('0'+x%10);
x /= 10;
}
ptr += d;
return this;
}
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;
}
public FastWriter write(long x)
{
if(x == Long.MIN_VALUE){
return write("" + x);
}
if(ptr + 21 >= BUF_SIZE)innerflush();
if(x < 0){
write((byte)'-');
x = -x;
}
int d = countDigits(x);
for(int i = ptr + d - 1;i >= ptr;i--){
buf[i] = (byte)('0'+x%10);
x /= 10;
}
ptr += d;
return this;
}
public FastWriter write(double x, int precision)
{
if(x < 0){
write('-');
x = -x;
}
x += Math.pow(10, -precision)/2;
// if(x < 0){ x = 0; }
write((long)x).write(".");
x -= (long)x;
for(int i = 0;i < precision;i++){
x *= 10;
write((char)('0'+(int)x));
x -= (int)x;
}
return this;
}
public FastWriter writeln(char c){
return write(c).writeln();
}
public FastWriter writeln(int x){
return write(x).writeln();
}
public FastWriter writeln(long x){
return write(x).writeln();
}
public FastWriter writeln(double x, int precision){
return write(x, precision).writeln();
}
public FastWriter write(int... xs)
{
boolean first = true;
for(int x : xs) {
if (!first) write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter write(long... xs)
{
boolean first = true;
for(long x : xs) {
if (!first) write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter writeln()
{
return write((byte)'\n');
}
public FastWriter writeln(int... xs)
{
return write(xs).writeln();
}
public FastWriter writeln(long... xs)
{
return write(xs).writeln();
}
public FastWriter writeln(char[] line)
{
return write(line).writeln();
}
public FastWriter writeln(char[]... map)
{
for(char[] line : map)write(line).writeln();
return this;
}
public FastWriter writeln(String s)
{
return write(s).writeln();
}
private void innerflush()
{
try {
out.write(buf, 0, ptr);
ptr = 0;
} catch (IOException e) {
throw new RuntimeException("innerflush");
}
}
public void flush()
{
innerflush();
try {
out.flush();
} catch (IOException e) {
throw new RuntimeException("flush");
}
}
public FastWriter print(byte b) { return write(b); }
public FastWriter print(char c) { return write(c); }
public FastWriter print(char[] s) { return write(s); }
public FastWriter print(String s) { return write(s); }
public FastWriter print(int x) { return write(x); }
public FastWriter print(long x) { return write(x); }
public FastWriter print(double x, int precision) { return write(x, precision); }
public FastWriter println(char c){ return writeln(c); }
public FastWriter println(int x){ return writeln(x); }
public FastWriter println(long x){ return writeln(x); }
public FastWriter println(double x, int precision){ return writeln(x, precision); }
public FastWriter print(int... xs) { return write(xs); }
public FastWriter print(long... xs) { return write(xs); }
public FastWriter println(int... xs) { return writeln(xs); }
public FastWriter println(long... xs) { return writeln(xs); }
public FastWriter println(char[] line) { return writeln(line); }
public FastWriter println(char[]... map) { return writeln(map); }
public FastWriter println(String s) { return writeln(s); }
public FastWriter println() { return writeln(); }
}
public void trnz(int... o)
{
for(int i = 0;i < o.length;i++)if(o[i] != 0)System.out.print(i+":"+o[i]+" ");
System.out.println();
}
// print ids which are 1
public void trt(long... o)
{
Queue<Integer> stands = new ArrayDeque<>();
for(int i = 0;i < o.length;i++){
for(long x = o[i];x != 0;x &= x-1)stands.add(i<<6|Long.numberOfTrailingZeros(x));
}
System.out.println(stands);
}
public void tf(boolean... r)
{
for(boolean x : r)System.out.print(x?'#':'.');
System.out.println();
}
public void tf(boolean[]... b)
{
for(boolean[] r : b) {
for(boolean x : r)System.out.print(x?'#':'.');
System.out.println();
}
System.out.println();
}
public void tf(long[]... b)
{
if(INPUT.length() != 0) {
for (long[] r : b) {
for (long x : r) {
for (int i = 0; i < 64; i++) {
System.out.print(x << ~i < 0 ? '#' : '.');
}
}
System.out.println();
}
System.out.println();
}
}
public void tf(long... b)
{
if(INPUT.length() != 0) {
for (long x : b) {
for (int i = 0; i < 64; i++) {
System.out.print(x << ~i < 0 ? '#' : '.');
}
}
System.out.println();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
|
Java
|
["5\n1 2\n1 3\n1 4\n3 5\n4\n2 3\n2 4\n3 4\n3 5", "1\n3\n1 1\n1 1\n1 1", "5\n1 2\n1 3\n1 4\n3 5\n6\n2 3\n2 4\n3 4\n3 5\n1 1\n1 2"]
|
6 seconds
|
["2", "3", "7"]
|
NoteThe tree in the first example and paths look like this. Pairs $$$(1,4)$$$ and $$$(3,4)$$$ intersect at one vertex.In the second example all three paths contain the same single vertex, so all pairs $$$(1, 2)$$$, $$$(1, 3)$$$ and $$$(2, 3)$$$ intersect at one vertex.The third example is the same as the first example with two additional paths. Pairs $$$(1,4)$$$, $$$(1,5)$$$, $$$(2,5)$$$, $$$(3,4)$$$, $$$(3,5)$$$, $$$(3,6)$$$ and $$$(5,6)$$$ intersect at one vertex.
|
Java 11
|
standard input
|
[
"combinatorics",
"data structures",
"dfs and similar",
"dp",
"trees"
] |
632afd3c714e4ab34fbc474f9f99d345
|
First line contains a single integer $$$n$$$ $$$(1 \leq n \leq 3 \cdot 10^5)$$$. Next $$$n - 1$$$ lines describe the tree. Each line contains two integers $$$u$$$ and $$$v$$$ $$$(1 \leq u, v \leq n)$$$ describing an edge between vertices $$$u$$$ and $$$v$$$. Next line contains a single integer $$$m$$$ $$$(1 \leq m \leq 3 \cdot 10^5)$$$. Next $$$m$$$ lines describe paths. Each line describes a path by it's two endpoints $$$u$$$ and $$$v$$$ $$$(1 \leq u, v \leq n)$$$. The given path is all the vertices on the shortest path from $$$u$$$ to $$$v$$$ (including $$$u$$$ and $$$v$$$).
| 2,600
|
Output a single integer — the number of pairs of paths that intersect at exactly one vertex.
|
standard output
| |
PASSED
|
62ce54e406716c4f1ff9730606a7777f
|
train_110.jsonl
|
1613658900
|
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
|
512 megabytes
|
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.math.BigInteger;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map.Entry;
import java.util.PriorityQueue;
import java.util.Random;
import java.util.Scanner;
import java.util.TreeSet;
public final class CF_703_D2_E {
static boolean verb=true;
static void log(Object X){if (verb) System.err.println(X);}
static void log(Object[] X){if (verb) {for (Object U:X) System.err.print(U+" ");System.err.println("");}}
static void log(int[] X){if (verb) {for (int U:X) System.err.print(U+" ");System.err.println("");}}
static void log(int[] X,int L){if (verb) {for (int i=0;i<L;i++) System.err.print(X[i]+" ");System.err.println("");}}
static void log(long[] X){if (verb) {for (long U:X) System.err.print(U+" ");System.err.println("");}}
static void logWln(Object X){if (verb) System.err.print(X);}
static void info(Object o){ System.out.println(o);}
static void output(Object o){outputWln(""+o+"\n"); }
static void outputWln(Object o){try {out.write(""+ o);} catch (Exception e) {}}
// Global vars
static BufferedWriter out;
static InputReader reader;
static long powerMod(long b,long e,long m){
long x=1;
while (e>0) {
if (e%2==1)
x=(b*x)%m;
b=(b*b)%m;
e=e/2;
}
return x;
}
/*
static void test() {
log("testing");
Random r=new Random();
int NTESTS=1000000000;
int NMAX=40;
//int MMAX=10000;
int VMAX=50;
for( int t=0;t<NTESTS;t++) {
int n=r.nextInt(NMAX)+2;
int MMAX=(n*(n-1))/2;
int m=r.nextInt(MMAX)+1;
HashSet<String> hs=new HashSet<String>();
ArrayList<Integer>[] friends=new ArrayList[n];
ArrayList<Integer>[] cost=new ArrayList[n];
for (int u=0;u<n;u++) {
friends[u]=new ArrayList<Integer>();
cost[u]=new ArrayList<Integer>();
}
StringBuffer script=new StringBuffer();
for (int i=0;i<m;i++) {
boolean goon=true;
while (goon) {
int u=r.nextInt(n);
int v=r.nextInt(n);
if (u!=v) {
if (u>v) {
int w=u;
u=v;
v=w;
}
String s=u+" "+v;
if (!hs.contains(s)) {
hs.add(s);
goon=false;
int w=r.nextInt(VMAX)+1;
friends[u].add(v);
friends[v].add(u);
cost[u].add(w);
cost[v].add(w);
script.append((u+1)+" "+(v+1)+" "+w+"\n");
}
}
}
}
long[] ans1=solveSubtil(friends,cost);
long[] ans2=solveBourrin(friends,cost);
for (int i=0;i<n;i++) {
if (ans1[i]!=ans2[i]) {
log("Error");
log(n+" "+m);
log(script);
log(ans1);
log(ans2);
return;
}
}
}
log("done");
}
*/
static int sign(int x) {
if (x>0)
return 1;
if (x==0)
return 0;
return -1;
}
static class Segment implements Comparable<Segment>{
int a;
int b;
public int compareTo(Segment X) {
if (a!=X.a)
return a-X.a;
if (b!=X.b)
return b-X.b;
return 0;
}
public Segment(int a, int b) {
this.a = a;
this.b = b;
}
}
static int order;
static int BYA=0;
static int BYB=1;
static class Composite implements Comparable<Composite>{
int p;
long v;
int idx;
int temp;
public int compareTo(Composite X) {
if (v<X.v)
return -1;
if (v>X.v)
return 1;
if (p!=X.p)
return p-X.p;
if (temp!=X.temp)
return temp-X.temp;
return idx-X.idx;
}
public Composite(int p, long v, int idx, int temp) {
this.p = p;
this.v = v;
this.idx = idx;
this.temp = temp;
}
public String toString() {
return "p:"+p+" dist:"+v+" node:"+(idx+1)+" temp:"+temp;
}
}
static class BIT {
int[] tree;
int N;
BIT(int N){
tree=new int[N+1];
this.N=N;
}
void add(int idx,int val){
idx++;
while (idx<=N){
tree[idx]+=val;
idx+=idx & (-idx);
}
}
int read(int idx){
idx++;
int sum=0;
while (idx>0){
sum+=tree[idx];
idx-=idx & (-idx);
}
return sum;
}
}
static ArrayList<ArrayList<Integer>> generatePermutations(ArrayList<Integer> items){
ArrayList<ArrayList<Integer>> globalRes=new ArrayList<ArrayList<Integer>>();
if (items.size()>1) {
for (Integer item:items){
ArrayList<Integer> itemsTmp=new ArrayList<Integer>(items);
itemsTmp.remove(item);
ArrayList<ArrayList<Integer>> res=generatePermutations(itemsTmp);
for (ArrayList<Integer> list:res){
list.add(item);
}
globalRes.addAll(res);
}
}
else {
Integer item=items.get(0);
ArrayList<Integer> list=new ArrayList<Integer>();
list.add(item);
globalRes.add(list);
}
return globalRes;
}
static int VX=51;
static long[] solveSubtil(int[][] friends,int[][] cost) {
int n=friends.length;
long[] ct=new long[n];
Arrays.fill(ct,MX);
ct[0]=0;
long[][] cst=new long[VX][n];
for (int e=0;e<VX;e++)
Arrays.fill(cst[e],MX);
//int[] tmp=new int[n];
PriorityQueue<Composite> pq=new PriorityQueue<Composite>();
pq.add(new Composite(0,0,0,0));
while (pq.size()>0) {
Composite X=pq.poll();
// don't process obsolete values
//if (X.v==cst[X.p][X.idx])
{
//log("processing X:"+X);
int u=X.idx;
int L=friends[u].length;
int p=X.p;
for (int t=0;t<L;t++) {
int node=friends[u][t];
int price=cost[u][t];
//log("considering node:"+(node+1));
if (p==0) {
long dist=cst[price][node];
if (dist>X.v) {
cst[price][node]=X.v;
//tmp[node]=price;
Composite Y=new Composite(1-p,X.v,node,price);
pq.add(Y);
//log("--adding : "+Y);
} else {
//log("--not interesting");
}
} else {
long nextDest=X.v+(X.temp+price)*(X.temp+price);
if (ct[node]>nextDest) {
ct[node]=nextDest;
Composite Y=new Composite(1-p,nextDest,node,0);
pq.add(Y);
//log("--adding : "+Y);
} else {
//log("--not interesting");
}
}
}
}
}
////logWln("cst1:");
////log(cst[1]);
return ct;
}
static long[] solveSubtilSlow(ArrayList<Integer>[] friends,ArrayList<Integer>[] cost) {
int n=friends.length;
long[][] cst=new long[2][n];
for (int e=0;e<2;e++)
Arrays.fill(cst[e],MX);
cst[0][0]=0;
//int[] tmp=new int[n];
Composite[][] ref=new Composite[2][n];
for (int e=0;e<2;e++)
for (int i=0;i<n;i++)
ref[e][i]=new Composite(e,cst[e][i],i,0);
PriorityQueue<Composite> pq=new PriorityQueue<Composite>();
pq.add(ref[0][0]);
while (pq.size()>0) {
Composite X=pq.poll();
// don't process obsolete values
//if (X.v==cst[X.p][X.idx])
{
//log("processing X:"+X);
int u=X.idx;
int L=friends[u].size();
int p=X.p;
for (int t=0;t<L;t++) {
int node=friends[u].get(t);
int price=cost[u].get(t);
long dst=cst[1-p][node];
//log("considering node:"+(node+1));
if (p==0) {
long worstv=dst+(100*100);
long best=X.v+(price+1)*(price+1);
if (worstv>best) {
cst[1-p][node]=X.v;
//tmp[node]=price;
Composite Y=new Composite(1-p,X.v,node,price);
pq.add(Y);
//log("--adding");
} else {
//log("--not interesting // "+worstv+" "+best);
}
} else {
long nextDest=X.v+(X.temp+price)*(X.temp+price);
if (dst>nextDest) {
cst[1-p][node]=nextDest;
Composite Y=new Composite(1-p,nextDest,node,0);
pq.add(Y);
//log("--adding");
} else {
//log("--not interesting");
}
}
}
}
}
//logWln("cst1:");
//log(cst[1]);
return cst[0];
}
static long MX=Long.MAX_VALUE/2;
static long[] solveBourrin(int[][] friends,int[][] cost) {
int n=friends.length;
long[] cst=new long[n];
Arrays.fill(cst,MX);
cst[0]=0;
int[] tmp=new int[n];
Composite[] ref=new Composite[n];
for (int i=0;i<n;i++)
ref[i]=new Composite(0,cst[i],i,0);
PriorityQueue<Composite> pq=new PriorityQueue<Composite>();
pq.add(ref[0]);
while (pq.size()>0) {
Composite X=pq.poll();
int u=X.idx;
int LU=friends[u].length;
for (int tu=0;tu<LU;tu++) {
int v=friends[u][tu];
int cv=cost[u][tu];
int LV=friends[v].length;
for (int tv=0;tv<LV;tv++) {
int w=friends[v][tv];
int cw=cost[v][tv];
long diff=(cw+cv);
diff*=diff;
long nxt=X.v+diff;
if (cst[w]>nxt) {
cst[w]=nxt;
pq.add(new Composite(0,cst[w],w,0));
}
}
}
}
return cst;
}
static long mod=1000000007;
static void process() throws Exception {
out = new BufferedWriter(new OutputStreamWriter(System.out));
reader=new InputReader(System.in);
Locale.setDefault(Locale.US);
//test();
int n=reader.readInt();
int m=reader.readInt();
int[] ed=new int[m];
int[] to=new int[m];
int[] from=new int[m];
int[] cst=new int[m];
int[] ptr=new int[n];
for (int i=0;i<m;i++) {
int u=reader.readInt()-1;
int v=reader.readInt()-1;
int w=reader.readInt();
ptr[u]++;
ptr[v]++;
from[i]=u;
to[i]=v;
cst[i]=w;
}
int[][] friends=new int[n][];
int[][] cost=new int[n][];
for (int i=0;i<n;i++) {
friends[i]=new int[ptr[i]];
cost[i]=new int[ptr[i]];
}
for (int i=0;i<m;i++) {
int u=from[i];
int v=to[i];
int w=cst[i];
friends[u][ptr[u]-1]=v;
cost[u][ptr[u]-1]=w;
friends[v][ptr[v]-1]=u;
cost[v][ptr[v]-1]=w;
ptr[u]--;
ptr[v]--;
}
//long[] ans=solveBourrin(friends,cost);
long[] ans=solveSubtil(friends,cost);
//log(ans);
//log(alt);
for (long x:ans) {
if (x!=MX)
outputWln(x+" ");
else
outputWln("-1 ");
}
output("");
try {
out.close();
}
catch (Exception EX){}
}
public static void main(String[] args) throws Exception {
process();
}
static final class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
private int read() throws IOException {
if (curChar >= numChars) {
curChar = 0;
numChars = stream.read(buf);
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public final String readString() throws IOException {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res=new StringBuilder();
do {
res.append((char)c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public final int readInt() throws IOException {
int c = read();
boolean neg=false;
while (isSpaceChar(c)) {
c = read();
}
char d=(char)c;
//log("d:"+d);
if (d=='-') {
neg=true;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
//log("res:"+res);
if (neg)
return -res;
return res;
}
public final long readLong() throws IOException {
int c = read();
boolean neg=false;
while (isSpaceChar(c)) {
c = read();
}
char d=(char)c;
//log("d:"+d);
if (d=='-') {
neg=true;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
//log("res:"+res);
if (neg)
return -res;
return res;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
|
Java
|
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
|
4 seconds
|
["0 98 49 25 114", "0 -1 9"]
|
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
|
Java 11
|
standard input
|
[
"binary search",
"brute force",
"constructive algorithms",
"dp",
"flows",
"graphs",
"shortest paths"
] |
abee4d188bb59d82fcf4579c7416a343
|
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
| 2,200
|
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
|
standard output
| |
PASSED
|
a00858eb04e047034d951c48821d723e
|
train_110.jsonl
|
1613658900
|
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
|
512 megabytes
|
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.math.BigInteger;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map.Entry;
import java.util.PriorityQueue;
import java.util.Random;
import java.util.Scanner;
import java.util.TreeSet;
public final class CF_703_D2_E {
static boolean verb=true;
static void log(Object X){if (verb) System.err.println(X);}
static void log(Object[] X){if (verb) {for (Object U:X) System.err.print(U+" ");System.err.println("");}}
static void log(int[] X){if (verb) {for (int U:X) System.err.print(U+" ");System.err.println("");}}
static void log(int[] X,int L){if (verb) {for (int i=0;i<L;i++) System.err.print(X[i]+" ");System.err.println("");}}
static void log(long[] X){if (verb) {for (long U:X) System.err.print(U+" ");System.err.println("");}}
static void logWln(Object X){if (verb) System.err.print(X);}
static void info(Object o){ System.out.println(o);}
static void output(Object o){outputWln(""+o+"\n"); }
static void outputWln(Object o){try {out.write(""+ o);} catch (Exception e) {}}
// Global vars
static BufferedWriter out;
static InputReader reader;
static long powerMod(long b,long e,long m){
long x=1;
while (e>0) {
if (e%2==1)
x=(b*x)%m;
b=(b*b)%m;
e=e/2;
}
return x;
}
static void test() {
log("testing");
Random r=new Random();
int NTESTS=1000000000;
int NMAX=40;
//int MMAX=10000;
int VMAX=50;
for( int t=0;t<NTESTS;t++) {
int n=r.nextInt(NMAX)+2;
int MMAX=(n*(n-1))/2;
int m=r.nextInt(MMAX)+1;
HashSet<String> hs=new HashSet<String>();
ArrayList<Integer>[] friends=new ArrayList[n];
ArrayList<Integer>[] cost=new ArrayList[n];
for (int u=0;u<n;u++) {
friends[u]=new ArrayList<Integer>();
cost[u]=new ArrayList<Integer>();
}
StringBuffer script=new StringBuffer();
for (int i=0;i<m;i++) {
boolean goon=true;
while (goon) {
int u=r.nextInt(n);
int v=r.nextInt(n);
if (u!=v) {
if (u>v) {
int w=u;
u=v;
v=w;
}
String s=u+" "+v;
if (!hs.contains(s)) {
hs.add(s);
goon=false;
int w=r.nextInt(VMAX)+1;
friends[u].add(v);
friends[v].add(u);
cost[u].add(w);
cost[v].add(w);
script.append((u+1)+" "+(v+1)+" "+w+"\n");
}
}
}
}
long[] ans1=solveSubtil(friends,cost);
long[] ans2=solveBourrin(friends,cost);
for (int i=0;i<n;i++) {
if (ans1[i]!=ans2[i]) {
log("Error");
log(n+" "+m);
log(script);
log(ans1);
log(ans2);
return;
}
}
}
log("done");
}
static int sign(int x) {
if (x>0)
return 1;
if (x==0)
return 0;
return -1;
}
static class Segment implements Comparable<Segment>{
int a;
int b;
public int compareTo(Segment X) {
if (a!=X.a)
return a-X.a;
if (b!=X.b)
return b-X.b;
return 0;
}
public Segment(int a, int b) {
this.a = a;
this.b = b;
}
}
static int order;
static int BYA=0;
static int BYB=1;
static class Composite implements Comparable<Composite>{
int p;
long v;
int idx;
int temp;
public int compareTo(Composite X) {
if (v<X.v)
return -1;
if (v>X.v)
return 1;
if (p!=X.p)
return p-X.p;
if (temp!=X.temp)
return temp-X.temp;
return idx-X.idx;
}
public Composite(int p, long v, int idx, int temp) {
this.p = p;
this.v = v;
this.idx = idx;
this.temp = temp;
}
public String toString() {
return "p:"+p+" dist:"+v+" node:"+(idx+1)+" temp:"+temp;
}
}
static class BIT {
int[] tree;
int N;
BIT(int N){
tree=new int[N+1];
this.N=N;
}
void add(int idx,int val){
idx++;
while (idx<=N){
tree[idx]+=val;
idx+=idx & (-idx);
}
}
int read(int idx){
idx++;
int sum=0;
while (idx>0){
sum+=tree[idx];
idx-=idx & (-idx);
}
return sum;
}
}
static ArrayList<ArrayList<Integer>> generatePermutations(ArrayList<Integer> items){
ArrayList<ArrayList<Integer>> globalRes=new ArrayList<ArrayList<Integer>>();
if (items.size()>1) {
for (Integer item:items){
ArrayList<Integer> itemsTmp=new ArrayList<Integer>(items);
itemsTmp.remove(item);
ArrayList<ArrayList<Integer>> res=generatePermutations(itemsTmp);
for (ArrayList<Integer> list:res){
list.add(item);
}
globalRes.addAll(res);
}
}
else {
Integer item=items.get(0);
ArrayList<Integer> list=new ArrayList<Integer>();
list.add(item);
globalRes.add(list);
}
return globalRes;
}
static int VX=51;
static long[] solveSubtil(ArrayList<Integer>[] friends,ArrayList<Integer>[] cost) {
int n=friends.length;
long[] ct=new long[n];
Arrays.fill(ct,MX);
ct[0]=0;
long[][] cst=new long[VX][n];
for (int e=0;e<VX;e++)
Arrays.fill(cst[e],MX);
//int[] tmp=new int[n];
PriorityQueue<Composite> pq=new PriorityQueue<Composite>();
pq.add(new Composite(0,0,0,0));
while (pq.size()>0) {
Composite X=pq.poll();
// don't process obsolete values
//if (X.v==cst[X.p][X.idx])
{
//log("processing X:"+X);
int u=X.idx;
int L=friends[u].size();
int p=X.p;
for (int t=0;t<L;t++) {
int node=friends[u].get(t);
int price=cost[u].get(t);
//log("considering node:"+(node+1));
if (p==0) {
long dist=cst[price][node];
if (dist>X.v) {
cst[price][node]=X.v;
//tmp[node]=price;
Composite Y=new Composite(1-p,X.v,node,price);
pq.add(Y);
//log("--adding : "+Y);
} else {
//log("--not interesting");
}
} else {
long nextDest=X.v+(X.temp+price)*(X.temp+price);
if (ct[node]>nextDest) {
ct[node]=nextDest;
Composite Y=new Composite(1-p,nextDest,node,0);
pq.add(Y);
//log("--adding : "+Y);
} else {
//log("--not interesting");
}
}
}
}
}
////logWln("cst1:");
////log(cst[1]);
return ct;
}
static long[] solveSubtilSlow(ArrayList<Integer>[] friends,ArrayList<Integer>[] cost) {
int n=friends.length;
long[][] cst=new long[2][n];
for (int e=0;e<2;e++)
Arrays.fill(cst[e],MX);
cst[0][0]=0;
//int[] tmp=new int[n];
Composite[][] ref=new Composite[2][n];
for (int e=0;e<2;e++)
for (int i=0;i<n;i++)
ref[e][i]=new Composite(e,cst[e][i],i,0);
PriorityQueue<Composite> pq=new PriorityQueue<Composite>();
pq.add(ref[0][0]);
while (pq.size()>0) {
Composite X=pq.poll();
// don't process obsolete values
//if (X.v==cst[X.p][X.idx])
{
//log("processing X:"+X);
int u=X.idx;
int L=friends[u].size();
int p=X.p;
for (int t=0;t<L;t++) {
int node=friends[u].get(t);
int price=cost[u].get(t);
long dst=cst[1-p][node];
//log("considering node:"+(node+1));
if (p==0) {
long worstv=dst+(100*100);
long best=X.v+(price+1)*(price+1);
if (worstv>best) {
cst[1-p][node]=X.v;
//tmp[node]=price;
Composite Y=new Composite(1-p,X.v,node,price);
pq.add(Y);
//log("--adding");
} else {
//log("--not interesting // "+worstv+" "+best);
}
} else {
long nextDest=X.v+(X.temp+price)*(X.temp+price);
if (dst>nextDest) {
cst[1-p][node]=nextDest;
Composite Y=new Composite(1-p,nextDest,node,0);
pq.add(Y);
//log("--adding");
} else {
//log("--not interesting");
}
}
}
}
}
//logWln("cst1:");
//log(cst[1]);
return cst[0];
}
static long MX=Long.MAX_VALUE/2;
static long[] solveBourrin(ArrayList<Integer>[] friends,ArrayList<Integer>[] cost) {
int n=friends.length;
long[] cst=new long[n];
Arrays.fill(cst,MX);
cst[0]=0;
int[] tmp=new int[n];
Composite[] ref=new Composite[n];
for (int i=0;i<n;i++)
ref[i]=new Composite(0,cst[i],i,0);
PriorityQueue<Composite> pq=new PriorityQueue<Composite>();
pq.add(ref[0]);
while (pq.size()>0) {
Composite X=pq.poll();
int u=X.idx;
int LU=friends[u].size();
for (int tu=0;tu<LU;tu++) {
int v=friends[u].get(tu);
int cv=cost[u].get(tu);
int LV=friends[v].size();
for (int tv=0;tv<LV;tv++) {
int w=friends[v].get(tv);
int cw=cost[v].get(tv);
long diff=(cw+cv);
diff*=diff;
long nxt=X.v+diff;
if (cst[w]>nxt) {
cst[w]=nxt;
pq.add(new Composite(0,cst[w],w,0));
}
}
}
}
return cst;
}
static long mod=1000000007;
static void process() throws Exception {
out = new BufferedWriter(new OutputStreamWriter(System.out));
reader=new InputReader(System.in);
Locale.setDefault(Locale.US);
//test();
int n=reader.readInt();
int m=reader.readInt();
int[] ed=new int[m];
ArrayList<Integer>[] friends=new ArrayList[n];
ArrayList<Integer>[] cost=new ArrayList[n];
for (int u=0;u<n;u++) {
friends[u]=new ArrayList<Integer>();
cost[u]=new ArrayList<Integer>();
}
for (int i=0;i<m;i++) {
int u=reader.readInt()-1;
int v=reader.readInt()-1;
int w=reader.readInt();
friends[u].add(v);
friends[v].add(u);
cost[u].add(w);
cost[v].add(w);
}
//long[] ans=solveBourrin(friends,cost);
long[] ans=solveSubtil(friends,cost);
//log(ans);
//log(alt);
for (long x:ans) {
if (x!=MX)
outputWln(x+" ");
else
outputWln("-1 ");
}
output("");
try {
out.close();
}
catch (Exception EX){}
}
public static void main(String[] args) throws Exception {
process();
}
static final class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
private int read() throws IOException {
if (curChar >= numChars) {
curChar = 0;
numChars = stream.read(buf);
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public final String readString() throws IOException {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res=new StringBuilder();
do {
res.append((char)c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public final int readInt() throws IOException {
int c = read();
boolean neg=false;
while (isSpaceChar(c)) {
c = read();
}
char d=(char)c;
//log("d:"+d);
if (d=='-') {
neg=true;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
//log("res:"+res);
if (neg)
return -res;
return res;
}
public final long readLong() throws IOException {
int c = read();
boolean neg=false;
while (isSpaceChar(c)) {
c = read();
}
char d=(char)c;
//log("d:"+d);
if (d=='-') {
neg=true;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
//log("res:"+res);
if (neg)
return -res;
return res;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
|
Java
|
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
|
4 seconds
|
["0 98 49 25 114", "0 -1 9"]
|
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
|
Java 11
|
standard input
|
[
"binary search",
"brute force",
"constructive algorithms",
"dp",
"flows",
"graphs",
"shortest paths"
] |
abee4d188bb59d82fcf4579c7416a343
|
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
| 2,200
|
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
|
standard output
| |
PASSED
|
98347176ef33e44d6f02beb041115d5b
|
train_110.jsonl
|
1613658900
|
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
|
512 megabytes
|
import java.util.*;
import java.io.*;
public class _1486_E {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
StringTokenizer line = new StringTokenizer(in.readLine());
int n = Integer.parseInt(line.nextToken());
int m = Integer.parseInt(line.nextToken());
ArrayList<Edge>[] graph = new ArrayList[n];
for(int i = 0; i < n; i++) {
graph[i] = new ArrayList<Edge>();
}
for(int i = 0; i < m; i++) {
line = new StringTokenizer(in.readLine());
int v1 = Integer.parseInt(line.nextToken()) - 1;
int v2 = Integer.parseInt(line.nextToken()) - 1;
int w = Integer.parseInt(line.nextToken());
graph[v1].add(new Edge(v2, w));
graph[v2].add(new Edge(v1, w));
}
long[][] d = new long[n][51];
for(int i = 0; i < n; i++) {
Arrays.fill(d[i], -1);
}
d[0][0] = 0;
PriorityQueue<Step> pq = new PriorityQueue<Step>();
pq.add(new Step(0, 0, 0));
while(pq.size() > 0) {
Step cur = pq.poll();
if(cur.d > d[cur.n][cur.p]) {
continue;
}
if(cur.p == 0) {
for(Edge e : graph[cur.n]) {
if(d[e.n][e.w] == -1 || cur.d < d[e.n][e.w]) {
d[e.n][e.w] = cur.d;
pq.add(new Step(e.n, e.w, cur.d));
}
}
}else {
for(Edge e : graph[cur.n]) {
int weight = (e.w + cur.p) * (e.w + cur.p);
if(d[e.n][0] == -1 || cur.d + weight < d[e.n][0]) {
d[e.n][0] = cur.d + weight;
pq.add(new Step(e.n, 0, cur.d + weight));
}
}
}
}
StringBuilder res = new StringBuilder();
for(int i = 0; i < n; i++) {
res.append(d[i][0]);
res.append(' ');
}
out.println(res.toString());
in.close();
out.close();
}
static class Step implements Comparable<Step> {
int n, p;
long d;
Step(int nn, int pp, long dd) {
n = nn;
p = pp;
d = dd;
}
@Override
public int compareTo(Step o) {
return Long.compare(d, o.d);
}
}
static class Edge {
int n, w;
Edge(int nn, int ww) {
n = nn;
w = ww;
}
}
}
|
Java
|
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
|
4 seconds
|
["0 98 49 25 114", "0 -1 9"]
|
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
|
Java 11
|
standard input
|
[
"binary search",
"brute force",
"constructive algorithms",
"dp",
"flows",
"graphs",
"shortest paths"
] |
abee4d188bb59d82fcf4579c7416a343
|
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
| 2,200
|
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
|
standard output
| |
PASSED
|
e9bc4e41fd918c7306bc6ab610cdd00b
|
train_110.jsonl
|
1613658900
|
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
|
512 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.AbstractQueue;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.AbstractCollection;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Khater
*/
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);
EPairedPayment solver = new EPairedPayment();
solver.solve(1, in, out);
out.close();
}
static class EPairedPayment {
long INF = (long) 1e15;
ArrayList<EPairedPayment.Edge>[] adjList;
long[] dist;
long[] dist2;
int V;
public void solve(int testNumber, Scanner sc, PrintWriter pw) {
int t = 1;
// t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
int m = sc.nextInt();
V = n;
adjList = new ArrayList[n];
for (int i = 0; i < n; i++) adjList[i] = new ArrayList<>();
for (int i = 0; i < m; i++) {
int x = sc.nextInt() - 1;
int y = sc.nextInt() - 1;
long w = sc.nextLong();
adjList[x].add(new EPairedPayment.Edge(y, w));
adjList[y].add(new EPairedPayment.Edge(x, w));
}
}
dijkstra(0, -1);
for (long x : dist) pw.print((x == (long) 1e15 ? -1 : x) + " ");
pw.println();
}
long dijkstra(int S, int T) {
dist = new long[V];
Arrays.fill(dist, INF);
dist2 = new long[V];
Arrays.fill(dist2, INF);
PriorityQueue<EPairedPayment.Edge> pq = new PriorityQueue<EPairedPayment.Edge>();
dist[S] = 0;
pq.add(new EPairedPayment.Edge(S, 0)); //may add more in case of MSSP (Mult-Source)
while (!pq.isEmpty()) {
EPairedPayment.Edge cur = pq.remove();
if (cur.cost > dist[cur.node]) //lazy deletion
continue;
for (EPairedPayment.Edge nxt : adjList[cur.node]) {
if (dist2[nxt.node] > nxt.cost) {
for (EPairedPayment.Edge nxtnxt : adjList[nxt.node]) {
if (nxtnxt.node != cur.node)
if (cur.cost + (nxt.cost + nxtnxt.cost) * (nxt.cost + nxtnxt.cost) < dist[nxtnxt.node])
pq.add(new EPairedPayment.Edge(nxtnxt.node, dist[nxtnxt.node] = cur.cost + (nxt.cost + nxtnxt.cost) * (nxt.cost + nxtnxt.cost)));
}
dist2[nxt.node] = nxt.cost;
}
}
}
return -1;
}
static class Edge implements Comparable<EPairedPayment.Edge> {
int node;
long cost;
Edge(int a, long b) {
node = a;
cost = b;
}
public int compareTo(EPairedPayment.Edge e) {
return Long.compare(cost, e.cost);
}
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
|
Java
|
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
|
4 seconds
|
["0 98 49 25 114", "0 -1 9"]
|
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
|
Java 11
|
standard input
|
[
"binary search",
"brute force",
"constructive algorithms",
"dp",
"flows",
"graphs",
"shortest paths"
] |
abee4d188bb59d82fcf4579c7416a343
|
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
| 2,200
|
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
|
standard output
| |
PASSED
|
94bd1518ed331934b9b5c554e399199f
|
train_110.jsonl
|
1613658900
|
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
|
512 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.AbstractQueue;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.AbstractCollection;
import java.util.StringTokenizer;
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;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
EPairedPayment solver = new EPairedPayment();
solver.solve(1, in, out);
out.close();
}
static class EPairedPayment {
ArrayList<Edge>[] adjList;
int n;
long INF = (long) 1e18;
int m;
long[][] dijkstra(int S) {
long[][] dist = new long[n][51];
for (long[] x : dist)
Arrays.fill(x, INF);
PriorityQueue<Edge> pq = new PriorityQueue<Edge>();
dist[S][0] = 0;
pq.add(new Edge(S, 0, 0)); //may add more in case of MSSP (Mult-Source)
while (!pq.isEmpty()) {
Edge cur = pq.remove();
if (dist[cur.node][cur.prev] < cur.cost)
continue;
for (Edge nxt : adjList[cur.node]) {
if (cur.prev == 0) {
if (dist[nxt.node][(int) nxt.cost] > cur.cost + nxt.cost) {
dist[nxt.node][(int) nxt.cost] = cur.cost + nxt.cost;
pq.add(new Edge(nxt.node, cur.cost, (int) nxt.cost));
}
} else {
if (dist[nxt.node][0] > cur.cost + (cur.prev + nxt.cost) * (cur.prev + nxt.cost)) {
dist[nxt.node][0] = cur.cost + (cur.prev + nxt.cost) * (cur.prev + nxt.cost);
pq.add(new Edge(nxt.node, dist[nxt.node][0], 0));
}
}
}
}
return dist;
}
public void readInput(Scanner sc) {
n = sc.nextInt();
m = sc.nextInt();
adjList = new ArrayList[n];
for (int i = 0; i < n; i++)
adjList[i] = new ArrayList<>();
for (int i = 0; i < m; i++) {
int u = sc.nextInt() - 1, v = sc.nextInt() - 1, cost = sc.nextInt();
adjList[u].add(new Edge(v, cost, 0));
adjList[v].add(new Edge(u, cost, 0));
}
}
public void solve(int testNumber, Scanner sc, PrintWriter pw) {
int q = 1;
while (q-- > 0) {
readInput(sc);
long[][] dist = dijkstra(0);
for (int i = 0; i < n; i++)
pw.print((dist[i][0] >= (long) 1e18 ? -1 : dist[i][0]) + " ");
}
}
class Edge implements Comparable<Edge> {
int node;
long cost;
int prev;
Edge(int a, long b, int prev) {
node = a;
cost = b;
this.prev = prev;
}
public int compareTo(Edge e) {
return Long.compare(cost + prev, e.cost + prev);
}
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() {
try {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
Java
|
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
|
4 seconds
|
["0 98 49 25 114", "0 -1 9"]
|
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
|
Java 11
|
standard input
|
[
"binary search",
"brute force",
"constructive algorithms",
"dp",
"flows",
"graphs",
"shortest paths"
] |
abee4d188bb59d82fcf4579c7416a343
|
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
| 2,200
|
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
|
standard output
| |
PASSED
|
be86665dfb1dabec58b173eb020a067b
|
train_110.jsonl
|
1613658900
|
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
|
512 megabytes
|
// copied
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class Main {
static final int N = (int) (2e5 + 11), INF = (int) (1e9 + 11);
static int n, m, v, u, w;
static ArrayList<int[]> g[] = new ArrayList[N];
static int[][] d;
static PriorityQueue<Node> pq;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
m = Integer.parseInt(st.nextToken());
for (int i = 0; i < n; ++i)
g[i] = new ArrayList<>();
while (m-- > 0) {
st = new StringTokenizer(br.readLine());
v = Integer.parseInt(st.nextToken());
u = Integer.parseInt(st.nextToken());
w = Integer.parseInt(st.nextToken());
--v;
--u;
g[v].add(new int[] { u, w });
g[u].add(new int[] { v, w });
}
d = new int[n][];
for (int i = 0; i < n; ++i) {
d[i] = new int[51];
for (int j = 0; j < 51; ++j)
d[i][j] = INF;
}
d[0][0] = 0;
Node V;
pq = new PriorityQueue<Node>();
pq.add(new Node(0, 0, d[0][0]));
while (pq.size() > 0) {
V = pq.remove();
int v = V.v;
int lvl = V.lvl;
int cost = V.cost;
if (d[v][lvl] != cost)
continue;
for (int[] u : g[v]) {
int to = u[0], w = u[1], lvl1;
if (lvl == 0) {
lvl1 = w;
w = w * w;
} else {
lvl1 = 0;
w = w * w + 2 * lvl * w;
}
if (d[to][lvl1] > w + d[v][lvl]) {
d[to][lvl1] = w + d[v][lvl];
pq.add(new Node(to, lvl1, d[to][lvl1]));
}
}
}
for (int i = 0; i < n; ++i)
if (d[i][0] == INF)
out.print("-1 ");
else
out.print(d[i][0] + " ");
out.close();
}
static class Node implements Comparable<Node> {
public int v, lvl, cost;
Node(int v1, int lvl1, int cost1) {
v = v1;
lvl = lvl1;
cost = cost1;
}
@Override
public int compareTo(Node a) {
return Integer.compare(cost, a.cost);
}
}
}
|
Java
|
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
|
4 seconds
|
["0 98 49 25 114", "0 -1 9"]
|
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
|
Java 11
|
standard input
|
[
"binary search",
"brute force",
"constructive algorithms",
"dp",
"flows",
"graphs",
"shortest paths"
] |
abee4d188bb59d82fcf4579c7416a343
|
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
| 2,200
|
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
|
standard output
| |
PASSED
|
7e3426a56f9fa7c5fb2bb3ef7d707e91
|
train_110.jsonl
|
1613658900
|
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
|
512 megabytes
|
import java.util.*;
import java.io.*;
public class A{
public static void main(String [] args)throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
FastReader sc=new FastReader();
PrintWriter pw=new PrintWriter(System.out);
int test=1;
while(test-->0){
int n=sc.nextInt();
int m=sc.nextInt();
ArrayList<Pair> arr[]=new ArrayList[n+1];
for(int i=0;i<=n;i++) arr[i]=new ArrayList<Pair>();
try{
while(m-->0){
int source=sc.nextInt();
int dest = sc.nextInt();
int weight = sc.nextInt();
arr[source].add(new Pair(dest,weight));
arr[dest].add(new Pair(source,weight));
}
}
catch(Exception e){
}
int [][] d=djikstra(1,n,arr);
for(int i=1;i<=n;i++){
if(d[i][0] == Integer.MAX_VALUE) d[i][0]=-1;
pw.print(d[i][0]+" ");
}
pw.println();
pw.close();
}
}
static class Pair{
int dest=0;
int wt=0;
int lastEdg=0;
Pair(){}
Pair(int d,int w){
dest=d;
wt =w;
}
Pair(int d,int v,int lastEdg){
dest=d;
wt=v;
this.lastEdg=lastEdg;
}
}
static class customSort implements Comparator<Pair>{
public int compare(Pair a,Pair b){
if(a.wt<b.wt){
return -1;
}
else if(a.wt>b.wt){
return 1;
}
return 0;
}
}
public static int [][] djikstra(int source,int n,ArrayList<Pair> arr[]){
int dp[][]=new int[n+1][51];
for(int i=0;i<=n;i++) Arrays.fill(dp[i], Integer.MAX_VALUE);
PriorityQueue<Pair> pq=new PriorityQueue<>(new customSort());
boolean vis[][]=new boolean[n+1][51];
pq.add(new Pair(source,0));
dp[1][0]=0;
while(!pq.isEmpty()){
Pair x=pq.poll();
int nd =x.dest;
int wt =x.wt;
int lastEdg =x.lastEdg;
if(vis[nd][lastEdg]){
continue;
}
vis[nd][lastEdg]=true;
for(int i=0;i<arr[nd].size();i++){
Pair y=arr[nd].get(i);
int ch=y.dest;
int wtc=y.wt;
int newDist = wt;
if(lastEdg>0) {
newDist +=((lastEdg+wtc)*(lastEdg+wtc));
wtc=0;
}
if(dp[ch][wtc]>newDist) {
dp[ch][wtc]=newDist;
pq.add(new Pair(ch,newDist,wtc));
}
}
}
return dp;
}
/**
* Fast I/O
*/
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
}
|
Java
|
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
|
4 seconds
|
["0 98 49 25 114", "0 -1 9"]
|
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
|
Java 11
|
standard input
|
[
"binary search",
"brute force",
"constructive algorithms",
"dp",
"flows",
"graphs",
"shortest paths"
] |
abee4d188bb59d82fcf4579c7416a343
|
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
| 2,200
|
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
|
standard output
| |
PASSED
|
a3e2982a93a08b7b6adee90469308b5a
|
train_110.jsonl
|
1613658900
|
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
|
512 megabytes
|
import java.util.*;
import java.io.*;
public class A{
public static void main(String [] args)throws IOException{
// BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
FastReader sc=new FastReader();
PrintWriter pw=new PrintWriter(System.out);
int test=1;
while(test-->0){
int n=sc.nextInt();
int m=sc.nextInt();
ArrayList<Pair> arr[]=new ArrayList[n+1];
for(int i=0;i<=n;i++) arr[i]=new ArrayList<Pair>();
while(m-->0){
int source=sc.nextInt();
int dest = sc.nextInt();
int weight = sc.nextInt();
arr[source].add(new Pair(dest,weight));
arr[dest].add(new Pair(source,weight));
}
int [][] d=djikstra(1,n,arr);
for(int i=1;i<=n;i++){
if(d[i][0] == Integer.MAX_VALUE) d[i][0]=-1;
pw.print(d[i][0]+" ");
}
pw.println();
pw.close();
}
}
static class Pair{
int dest=0;
int wt=0;
Pair(){}
Pair(int d,int w){
dest=d;
wt =w;
}
}
static class customSort implements Comparator<Pair>{
public int compare(Pair a,Pair b){
if(a.wt<b.wt){
return -1;
}
else if(a.wt>b.wt){
return 1;
}
return 0;
}
}
public static int [][] djikstra(int source,int n,ArrayList<Pair> arr[]){
int dist[][]=new int[n+1][52];
boolean vis[][]=new boolean[n+1][52];
for(int i=0;i<=n;i++) Arrays.fill(dist[i], Integer.MAX_VALUE);
PriorityQueue<Pair> pq=new PriorityQueue<>(new customSort());
pq.add(new Pair(1*55+0,0));
while(!pq.isEmpty()) {
Pair x=pq.poll();
int nd =x.dest/55;
int lastEdgWt =x.dest%55;
int distance =x.wt;
if(vis[nd][lastEdgWt]) {
continue;
}
vis[nd][lastEdgWt]=true;
dist[nd][lastEdgWt]=distance;
for(Pair y:arr[nd]) {
int newWt= y.wt;
int newDistance =distance;
if(lastEdgWt>0) {
newDistance +=((newWt+lastEdgWt)*(newWt+lastEdgWt));
newWt=0;
}
if(dist[y.dest][newWt] <= newDistance) continue;
dist[y.dest][newWt] =newDistance;
pq.add(new Pair(((y.dest*55)+newWt),newDistance));
}
}
return dist;
}
/**
* Fast I/O
*/
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
}
|
Java
|
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
|
4 seconds
|
["0 98 49 25 114", "0 -1 9"]
|
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
|
Java 11
|
standard input
|
[
"binary search",
"brute force",
"constructive algorithms",
"dp",
"flows",
"graphs",
"shortest paths"
] |
abee4d188bb59d82fcf4579c7416a343
|
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
| 2,200
|
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
|
standard output
| |
PASSED
|
6b39e638709d39adca0ba37d7d229293
|
train_110.jsonl
|
1613658900
|
There are $$$n$$$ cities and $$$m$$$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter $$$w$$$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $$$a$$$ to city $$$b$$$ and then from city $$$b$$$ to city $$$c$$$) and you will have to pay $$$(w_{ab} + w_{bc})^2$$$ money to go through those roads. Find out whether it is possible to travel from city $$$1$$$ to every other city $$$t$$$ and what's the minimum amount of money you need to get from $$$1$$$ to $$$t$$$.
|
512 megabytes
|
import java.io.*;
import java.util.*;
public class CF703E {
static final int N = (int)(2e5 + 11), INF = (int)(1e9 + 11);
static int n, m, v, u, w;
static ArrayList< int[] > g[] = new ArrayList[N];
static int[][] d;
static PriorityQueue<Node> pq;
public static void main (String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
m = Integer.parseInt(st.nextToken());
for (int i = 0; i < n; ++i)
g[i] = new ArrayList<>();
while (m-- > 0) {
st = new StringTokenizer(br.readLine());
v = Integer.parseInt(st.nextToken());
u = Integer.parseInt(st.nextToken());
w = Integer.parseInt(st.nextToken());
--v;
--u;
g[v].add(new int[] {u, w});
g[u].add(new int[] {v, w});
}
d = new int[n][];
for (int i = 0; i < n; ++i) {
d[i] = new int[51];
for (int j = 0; j < 51; ++j)
d[i][j] = INF;
}
d[0][0] = 0;
Node V;
pq = new PriorityQueue<Node>();
pq.add(new Node(0, 0, d[0][0]));
while (pq.size() > 0) {
V = pq.remove();
int v = V.v;
int lvl = V.lvl;
int cost = V.cost;
if (d[v][lvl] != cost)
continue;
for (int[] u : g[v]) {
int to = u[0], w = u[1], lvl1;
if (lvl == 0) {
lvl1 = w;
w = w*w;
} else {
lvl1 = 0;
w = w*w + 2*lvl*w;
}
if (d[to][lvl1] > w + d[v][lvl]) {
d[to][lvl1] = w + d[v][lvl];
pq.add(new Node(to, lvl1, d[to][lvl1]));
}
}
}
for (int i = 0; i < n; ++i)
if (d[i][0] == INF)
out.print("-1 ");
else
out.print(d[i][0] + " ");
out.close();
}
static class Node implements Comparable<Node> {
public int v, lvl, cost;
Node (int v1, int lvl1, int cost1) {
v = v1;
lvl = lvl1;
cost = cost1;
}
@Override
public int compareTo (Node a) {
return Integer.compare(cost, a.cost);
}
}
}
|
Java
|
["5 6\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n2 4 2", "3 2\n1 2 1\n2 3 2"]
|
4 seconds
|
["0 98 49 25 114", "0 -1 9"]
|
NoteThe graph in the first example looks like this.In the second example the path from $$$1$$$ to $$$3$$$ goes through $$$2$$$, so the resulting payment is $$$(1 + 2)^2 = 9$$$.
|
Java 11
|
standard input
|
[
"binary search",
"brute force",
"constructive algorithms",
"dp",
"flows",
"graphs",
"shortest paths"
] |
abee4d188bb59d82fcf4579c7416a343
|
First line contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m \leq min(\frac{n \cdot (n - 1)}{2}, 2 \cdot 10^5)$$$). Next $$$m$$$ lines each contain three integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ ($$$1 \leq v_i, u_i \leq n$$$, $$$1 \leq w_i \leq 50$$$, $$$u_i \neq v_i$$$). It's guaranteed that there are no multiple edges, i.e. for any edge $$$(u_i, v_i)$$$ there are no other edges $$$(u_i, v_i)$$$ or $$$(v_i, u_i)$$$.
| 2,200
|
For every city $$$t$$$ print one integer. If there is no correct path between $$$1$$$ and $$$t$$$ output $$$-1$$$. Otherwise print out the minimum amount of money needed to travel from $$$1$$$ to $$$t$$$.
|
standard output
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.