Blue Bridge Cup Chocolate (Java)

Title description

On Children's Day, K children visited Xiao Ming's house as guests. Xiao Ming took out a collection of chocolates to entertain the children.
Xiao Ming has N pieces of chocolate in total, of which the i-th piece is a rectangle composed of Hi x Wi squares.

为了公平起见,小明需要从这 N 块巧克力中切出K块巧克力分给小朋友们。切出的巧克力需要满足:

1. 形状是正方形,边长是整数  
2. 大小相同  

For example, a piece of 6x5 chocolate can cut 6 pieces of 2x2 chocolate or 2 pieces of 3x3 chocolate.

Of course, kids want to get as big chocolate as possible. Can you help Little Hi calculate the maximum side length?

Input The
first line contains two integers N and K. (1 <= N, K <= 100000)
Each of the following N lines contains two integers Hi and Wi. (1 <= Hi, Wi <= 100000)
Enter to ensure that each child can get at least a 1x1 chocolate.

Output
Output the maximum possible side length of the cut square chocolate.

Sample input:
2 10
6 5
5 6

Sample output:
2

Resource agreement:
Peak memory consumption (including virtual machines) <256M
CPU consumption <1000ms

Thinking analysis:

Knowing that most people choose binary search for this question, I used trial and error to enumerate violently. Suppose I cut with side length 1, to see if all the chocolate meets the requirements after cutting, and if so, then the side length is used. 2 Cut, keep trying repeatedly until the chocolate is not cut enough when the side length is n, then the maximum divided side length must be n-1.

package 蓝桥杯;

import java.util.*;

public class 分巧克力 {
    
    
	public static void main(String[] args) {
    
    
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();
		int k = in.nextInt();
		int[][] qkl = new int[n][2];
		int size = 1;
		//存储所有巧克力信息
		for(int i = 0;i < n;i++) {
    
    
			qkl[i][0] = in.nextInt();
			qkl[i][1] = in.nextInt();
		}
		int flag = 0;
		int sum = 0;
		//遍历以当前边计算,能否满足
		while(true) {
    
    
			sum = 0;flag = 0;
			for(int i = 0;i < n;i++) {
    
    
				int a = qkl[i][0];//表示长
				int b = qkl[i][1];//表示宽
				sum += (a/size)*(b/size);//当前块以当前尺寸分能分多少块
				if(sum >= k) {
    
    
					size++;
					flag = 1;
					break;
				}
			}
			if(flag == 0)
				break;
				
		}
		System.out.print(size-1);
	}
}

Guess you like

Origin blog.csdn.net/baldicoot_/article/details/109563974