0
点赞
收藏
分享

微信扫一扫

算法修炼23招---第二招:二分

小猪肥 2022-05-06 阅读 76

✨例1:木材加工

package 高校算法社区每日一题;

import java.util.Scanner;

/**
* @author yx
* @date 2022-04-27 11:28
*/

public class 洛谷P2440木材加工__二分 {
static int tree[]=new int[100008];
static int n;
static int m;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
n=scanner.nextInt();
m=scanner.nextInt();
int left=0;
int right=0;
for (int i = 1; i <=n ; i++) {
tree[i]=scanner.nextInt();
right=Math.max(right,tree[i]);
}
while (left<right){
int mid=(left+right+1)>>1;
if(check(mid)>=m){
left=mid;
}else {
right=mid-1;
}
}
System.out.println(left);
}
static long check(int mid){
long sum=0;
for (int i = 1; i <=n ; i++) {
if(tree[i]>mid){
sum+=tree[i]/mid;
}
}
return sum;
}
}

✨例2:砍树

package 高校算法社区每日一题;

import java.io.*;
import java.util.regex.Matcher;

/**
* @author yx
* @date 2022-04-26 20:53
*/

public class 洛谷P1873砍树__二分__快读 {
static int n=1000010;
static int[] tree=new int[n];
static int N;
static long M;
//快读模板
static class Reader {
public BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public StreamTokenizer st = new StreamTokenizer(br);
public void token() {
try {
st.nextToken();
} catch (IOException e) {}
}

public int nextInt() {
token();
return (int)st.nval;
}

public String next() {
token();
return st.sval;
}
}
public static void main(String[] args) {
Reader sc=new Reader();
N=sc.nextInt();
M=sc.nextInt();
int left=0;
int right=0;
for (int i = 1; i <=N ; i++) {
tree[i]=sc.nextInt();
right= Math.max(right,tree[i]);
}
while (left<right){
//自己一步步推导一下
int mid=(left+right+1)>>1;//(r+l+1)中的+1是为了防治死循环
if(check(mid)>=M){
left=mid;
}else{
right=mid-1;
}
}
System.out.println(left);
}
static long check(int mid){
long sum=0;
for (int i = 1; i <=N ; i++) {
if(tree[i]>mid){
sum+=(tree[i]-mid);
}
}
return sum;
}
}

🚀写在最后 

最近有点迷,经常性迷茫可能是当代大学生的通病吧,大学的前两年过的很累,但也充实,emm,做过很多尝试,打过很多比赛,时间过的很紧凑,仿佛每天都在忙碌,但似乎留给自己去思考的时间并不是很多,在接下来大学的后两年生活里,我想卸下一些担子,全身心去做自己真正想做的事情,而不是陷入无限的内耗,正值年少风华正茂,我们不应该被束缚!

举报

相关推荐

0 条评论