题目描述
Before the invention of book-printing, it was very hard to make a copy of a book. All the contents had to be re-written by hand by so called scribers. The scriber had been given a book and after several months he finished its copy. One of the most famous scribers lived in the 15th century and his name was Xaverius Endricus Remius Ontius Xendrianus (Xerox). Anyway, the work was very annoying and boring. And the only way to speed it up was to hire more scribers.
Once upon a time, there was a theater ensemble that wanted to play famous Antique Tragedies. The scripts of these plays were divided into many books and actors needed more copies of them, of course. So they hired many scribers to make copies of these books. Imagine you have m books (numbered 1, 2 … m) that may have different number of pages (p1, p2 … pm) and you want to make one copy of each of them. Your task is to divide these books among k scribes, k <= m. Each book can be assigned to a single scriber only, and every scriber must get a continuous sequence of books. That means, there exists an increasing succession of numbers 0 = b0 < b1 < b2, … < bk-1 <= bk = m such that i-th scriber gets a sequence of books with numbers between bi-1+1 and bi. The time needed to make a copy of all the books is determined by the scriber who was assigned the most work. Therefore, our goal is to minimize the maximum number of pages assigned to a single scriber. Your task is to find the optimal assignment.
算法思路
- 这一题要求我们将一个大的数列分解成多个连续的小的数列,并且要求在满足条件的情况下越靠前面的数列所含的数越少。所以满足贪心的性质。(想了好久才看出来)。
- 要求每个抄写员至少分到一本书,所以搜索的下界是那本页数最大的那本书。而搜索的上界是页码的总和。
- 要搜索的是找到一个最小的页数,可以将这个数列分解成的数列数不大于k.如果分隔的子数列的数量不足k,根据贪心的性质,我们尽量在前面再划分数列。可以得到题目要求的解。
代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
#define MAXN 505
int n,m,Arr[MAXN],sum,t;
int flag[MAXN];
int test(int interval)
{
int i,sum=0;
int cnt=0;
memset(flag,0,sizeof(flag));
for(i=n;i>=1;i--){
sum += Arr[i];
if(sum>interval){
sum = Arr[i];
cnt++;
flag[i]=1;
}
}
return cnt+1;
}
int main()
{
freopen("input","r",stdin);
int L,R,i;
scanf("%d",&t);
while(t--){
scanf("%d%d",&n,&m);
sum = 0;
L = 0;
for(i=1;i<=n;i++){
scanf("%d",&Arr[i]);
//the lower bound of search is the maximum of the book
L = max(L,Arr[i]);
sum += Arr[i];
}
R = sum;
//search for the target
while(L < R){
int mid = L + (R-L)/2;
if(test(mid)>m)L=mid+1;
else R = mid;
}
int num = test(R);
//add interval in the front of the array
for(i=1;i<=n&&num<m;i++){
if(!flag[i]){
num++;
flag[i]=1;
}
}
for(i=1;i<=n;i++){
printf("%d",Arr[i]);
if(flag[i])printf(" /");
if(i<n)printf(" ");
}
printf("\n");
}
return 0;
}