[较难] UVa OJ 714 Copying books

题目描述

本题比较难,本人自己写了一份代码,但没有AC,下面给出《算法竞赛入门经典》书上代码,书上页码244

本题较难,仅Mark

// UVa714 Copying Books
// Rujia Liu
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxm = 500 + 5;
int m, k, p[maxm];

// how many scribers needed if each scriber can work on at most maxp pages
int solve(long long maxp) {
  long long done = 0;
  int ans = 1;
  for(int i = 0; i < m; i++) {
    if(done + p[i] <= maxp) done += p[i];
    else { ans++; done = p[i]; }
  }
  return ans;
}

int last[maxm]; // last[i] = 1 iff i is the last book assigned to someone
void print(long long ans) {
  long long done = 0;
  memset(last, 0, sizeof(last));
  int remain = k;
  for(int i = m-1; i >= 0; i--) {
    if(done + p[i] > ans || i+1 < remain) {
      last[i] = 1; remain--; done = p[i];
    }
    else {
      done += p[i];
    }
  }
  for(int i = 0; i < m-1; i++) {
    printf("%d ", p[i]);
    if(last[i]) printf("/ ");
  }
  printf("%d\n", p[m-1]);
}

int main() {
  int T;
  scanf("%d", &T);
  while(T--) {
    scanf("%d%d", &m, &k);
    long long tot = 0;
    int maxp = -1;
    for(int i = 0; i < m; i++) {
      scanf("%d", &p[i]);
      tot += p[i];
      maxp = max(maxp, p[i]);
    }
    long long L = maxp, R = tot;
    while(L < R) {
      long long M = L + (R-L)/2;
      if(solve(M) <= k) R = M; else L = M+1;
    }
    print(L);
  }
  return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值