uva714 - Copying Books 入门经典II 第八章 例题8-10

题目链接:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=9&page=show_problem&problem=655


有些细节还是需要练习。看了书上的思路:二分+贪心,然后看了原版代码后写了一下


#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn = 500 + 10;
int p[maxn],last[maxn],m,k;

int solve(long long M){
    int tot=1;
    long long done=0;
    for(int i=0;i<m;i++){
        if(done+p[i]>M){
            tot++;
            done=p[i];
        }else
            done+=p[i];
    }
    return tot;
}

void print(long long ans){
    memset(last,0,sizeof(last));
    long long done =0;
    int remain=k;//代表剩余的,如果剩余x个斜杠,并且,还有x+1个数,则每个数中间都有一个斜杠
    for(int i=m-1;i>=0;i--){
        if(done + p[i]>ans || i+1<remain){
            remain--;
            last[i]=1;
            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;
    cin >>T;
    while(T--){
        cin>>m>>k;
        long long tot=0;
        int maxp=-1;
        for(int i=0;i<m;i++){
            cin >> 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;
}



汝佳提供的代码:

// 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;
}




你可能感兴趣的:(uva714 - Copying Books 入门经典II 第八章 例题8-10)