AcWing 4665. 最少刷题数 java 二分
原题链接
简单
作者:
不羁_4
,
2024-11-16 12:38:34
,
所有人可见
,
阅读 2
java代码,三个二分,码风还可以我觉得
import java.util.*;
import java.io.*;
public class Main{
private static int N=(int)1e5+10;
private static int n;
private static int a[]=new int[N],b[]=new int[N];
public static void main(String fasd[]) throws Exception{
BufferedReader rd=new BufferedReader(new InputStreamReader(System.in));
BufferedWriter wd=new BufferedWriter(new OutputStreamWriter(System.out));
n=Integer.parseInt(rd.readLine());
String s[]=rd.readLine().split(" ");
for(int i=0;i<n;i++) a[i]=b[i]=Integer.parseInt(s[i]);
Arrays.sort(b,0,n);
for(int i=0;i<n;i++){
int l=0,r=N;
int ans=-1;
while(l<=r){
int mid=(l+r)/2;
if(check(a[i]+mid,i)){
ans=mid;
r=mid-1;
}
else l=mid+1;
}
wd.write(l+" ");
}
wd.flush();
}
public static boolean check(int x,int id){
int lcnt=0,rcnt=0;
int l=0,r=n-1;//先找小于等于x-1的个数
//再找大于等于x+1的个数
int as=-1;
while(l<=r){
int mid=(l+r)/2;
if(b[mid]<=x-1){
as=mid;
l=mid+1;
}
else r=mid-1;
}
if(as!=-1){
lcnt=as+1;
if(a[id]<=x-1) lcnt--;
}
as=-1;
l=0;
r=n-1;
while(l<=r){
int mid=(l+r)/2;
if(b[mid]>=x+1){
as=mid;
r=mid-1;
}
else l=mid+1;
}
if(as!=-1) rcnt=n-1-as+1;
return rcnt<=lcnt;
}
}