Algorithm Improvement Packing

Resource limit
Memory limit: 256.0MB C/C++ time limit: 1.0s Java time limit: 3.0s Python time limit: 5.0s
Problem description
  Lazy has N gifts that need to be packaged into M packages and mailed to M individuals. Cheap, but heavy. Lazy hopes that the numbers of the gifts everyone gets are consecutive. To avoid paying high overweight fees, he also wanted to keep the maximum weight of the package to a minimum.
Input format
  Two integers N and M on a line.
  A row of N integers represents the weight of N gifts.
output format
  An integer representing the minimum and maximum weight.
Sample input
3 2
1 1 2
Sample output
2
Data size and convention
  N, M <= 100,000
  Weight <= 1,000

import java.util.*;

public class Main {
    
    
	public static void main(String[] args) {
    
    
		Scanner sc=new Scanner(System.in);
		int num=sc.nextInt();
		int pack=sc.nextInt();
		int[] weight=new int[num];
		int right=0,left=0;//right为sum总和,left为weight[i]中最大的
		for(int i=0;i<num;i++) {
    
    
			weight[i]=sc.nextInt();
			right+=weight[i];
			if(weight[i]>left)left=weight[i];
		}
		int mid=0;//mid是最大重量,包裹在pack内最小(将pack用完)
		//在Max(weight[i])与sum之间二分查找mid
		while(left<right) {
    
    
			mid=(left+right)/2;
			if(judge(weight,mid,pack)) {
    
    
				right=mid;
			}
			else {
    
    
				left=mid+1;
			}
		}
		System.out.println(left);
	}
	private static boolean judge(int[]weight,int mid,int pack) {
    
    
		int W=0;//当前包的总重量
		int P=1;//包的总数量
		for(int val:weight) {
    
    
			W+=val;
			//如果weight超过了最大重量
			if(W>mid) {
    
    
				W=val;//重新开始打包
				P+=1;//包的数量加1
			}
		}
		return P<=pack;//取=表示可能还可以用
	}
}

Guess you like

Origin blog.csdn.net/qq_54537215/article/details/123935932