微软2016实习生笔试题 - Font Size

描述

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,
1 <= N <= 103,
1 <= W, H, ai <= 103,
1 <= P <= 106,

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.

样例输入

2
1 10 4 3
10
2 10 4 3
10 10

样例输出

3
2

思路

遍历S=1,2,3,...,min(w,h)
逐个计算该S对应的每行可容纳字符数,每页可容纳行数。随后计算总计需要的行数。
若在允许的总页数范围内,查看是否为最大的S值。

实现代码 C++

#include<iostream>
#include<cstring>

using namespace std;

int paragraphs[1000000+5];
int n,p,w,h;
int maxn;

int calLines(int char_each_line){
  int total = 0;
  for( int i = 0 ; i < n ; i ++ ){
    total += paragraphs[i] / char_each_line;
    if( paragraphs[i] % char_each_line != 0){
      total ++;
    }
  }
  return total;
}

void solve(){
  int min = (w>h)?h:w;
  int currentS = 1;
  while(currentS <= min){
    int char_each_line = w/currentS;
    int lines_each_page = h/currentS;
    int needLines = calLines(char_each_line);
    int pages = needLines / lines_each_page;
    if(needLines%lines_each_page!=0){
      pages++;
    }
    if( pages <= p && currentS > maxn ){
      maxn = currentS;
    }
    currentS ++;
  }
}

int main(){
  int caseNumber = 0;
  cin >> caseNumber;
  int currentCase = 0;
  while (currentCase < caseNumber) {
    maxn = 0;
    cin>>n>>p>>w>>h;
    for(int i = 0 ; i < n ; i ++){
      cin>>paragraphs[i];
    }
    solve();
    cout<<maxn<<endl;
    currentCase ++;
  }
  return 0;
}
返回文章列表 文章二维码
本页链接的二维码
打赏二维码