题目的来源是微软公司2016年的春季校招笔试。
我又被人抱了大腿。(啥?为什么这是第一题?因为我水呀。XD)
Steven loves reading book on his phone. The book he reads now consists of N paragraphs and the i-th paragraph contains ai characters.
Steven wants to make the characters easier to read, so he decides to increase the font size of characters. But the size of Steven’s phone screen is limited. Its width is W and height is H. As a result, if the font size of characters is S then it can only show ⌊W / S⌋ characters in a line and ⌊H / S⌋ lines in a page. (⌊x⌋ is the largest integer no more than x)
So here’s the question, if Steven wants to control the number of pages no more than P, what’s the maximum font size he can set? Note that paragraphs must start in a new line and there is no empty line between paragraphs.
Input may contain multiple test cases.
The first line is an integer TASKS, representing the number of test cases.
For each test case, the first line contains four integers N, P, W and H, as described above.
The second line contains N integers a1,a2,…,aN , indicating the number of characters in each paragraph.
For all test cases,
There is always a way to control the number of pages no more than P.
For each testcase, output a line with an integer Ans, indicating the maximum font size Steven can set.
这个问题可以转换为:
本还想二分搜索什么的,结果一次顺序遍历也不会超时。
一开始没有使用Math.floor
函数,结果只能通过30%的数据。完全不能理解为什么。
Math.floor(height / currentFontSize)
和height / currentFontSize
不是等价的吗?
package edu.hit;
import java.util.Scanner;
public class Solution {
public int getFontSize(int numberOfParagraphs, int[] numberOfCharacters,
int numberOfPages, int width, int height) {
int minFontSize = 1,
maxFontSize = width;
for ( int currentFontSize = maxFontSize; currentFontSize >= minFontSize; -- currentFontSize ) {
double linesOccupied = 0,
totalLines = numberOfPages * Math.floor(height / currentFontSize);
for ( int i = 0; i < numberOfParagraphs; ++ i ) {
linesOccupied += Math.ceil(numberOfCharacters[i] / Math.floor(width / currentFontSize));
}
if ( linesOccupied <= totalLines ) {
return currentFontSize;
}
}
return 1;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Solution s = new Solution();
int numberOfTestCases = in.nextInt();
for ( int i = 0; i < numberOfTestCases; ++ i ) {
int numberOfParagraphs = in.nextInt(),
numberOfPages = in.nextInt(),
width = in.nextInt(),
height = in.nextInt();
int[] numberOfCharacters = new int[numberOfParagraphs];
for ( int j = 0; j < numberOfParagraphs; ++ j ) {
numberOfCharacters[j] = in.nextInt();
}
int fontSize = s.getFontSize(numberOfParagraphs, numberOfCharacters, numberOfPages, width, height);
System.out.println(fontSize);
}
in.close();
}
}