POJ 1505 (Copying Books)(經典二分)
阿新 • • 發佈:2019-01-23
Description
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
Input
Output
If there is more than one solution, print the one that minimizes the work assigned to the first scriber, then to the second scriber etc. But each scriber must be assigned at least one book.
Sample Input
2 9 3 100 200 300 400 500 600 700 800 900 5 4 100 100 100 100 100
Sample Output
100 200 300 400 500 / 600 700 / 800 900 100 / 100 / 100 / 100 100
Source
題意:給你n本書,k個人翻譯,問怎樣分配一個人單獨翻譯的最大值最小,換而言之,每個人翻譯的差不多,
還有一個要求,就是如果可以,儘量讓第一個人翻譯的少
思路:先二分找出一個人翻譯的最大值,然後找出每個人的翻譯的(從後到前找),有一個bug,讓我cuo了11發,%>_<%
我在程式碼中說明
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdio>
using namespace std;
#define N 505
int a[N],vis[N];
int n,k;
int seach(int mid) //每個人翻譯mid本書,看看需要的人數能不能少於等於k
{
int step=1,cur=0,i;
for(i=1;i<=n;i++)
if(cur+a[i]<=mid)
cur+=a[i];
else
{
step++;
cur=a[i];
}
if(step<=k) return 1;
return 0;
}
int main()
{
int i,t,le,ri;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&k);
le=ri=0;
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
if(a[i]>le) le=a[i];
ri+=a[i];
}
int ans,mid;
while(le<=ri)
{
mid=(le+ri)/2;
if(seach(mid))
{
ans=mid;
ri=mid-1;
}
else
le=mid+1;
}
memset(vis,0,sizeof(vis));
int x=k,j,temp=0;
for(i=n;i>=1;i--)
{
if(x>i) //這是bug關鍵,如果人數比數的本書多,後面的人一人一本
{ //這裡情況很複雜 請認真結合我下面給的樣例想想,=和>的區別
//我比賽時錯了 11發(就是這沒考慮)
for(i;i>=1;i--)
vis[i]=1;
break;
}
temp+=a[i];
if(temp>ans)
{
temp=a[i];
vis[i]=1;
x--; //人數減一
}
}
for(i=1;i<=n;i++)
{
if(i==1)
printf("%d",a[i]);
else
printf(" %d",a[i]);
if(vis[i]) printf(" /");
}
printf("\n");
}
return 0;
}
// n=4 k=4
//當ans=200
// 20 100 100 200
//如果我上面強調的(x>i),那麼100 和 100之間不會有 /
//還有為什麼是 > 不是 >= 呢,再給一組資料
// n=6,k=5,ans=200
// 50 100 50 50 50 200
//結果 50/100/50/50/50/200,就會出錯,請認真思考(畢竟我當時快崩潰了)
我錯了11次,當時ac簡直無法形容我的感覺,如有解釋不當的地方,歡迎指出
上面二分簡單就沒有解釋多少,請注意我強調的地方