题意:给出一段文章,要求将里面的单词按照n个字符一行来分,不够一行的可以在单词间插入空格来得到,一行有一个basness值,为一个每个gap之间的空格数-1的平方,求badness总和最少的分隔方式.
经典DP,设dp[i]为从第i开始到第n单词的最少badness和分隔方式,那么dp[i] = min(dp[j + 1] + badness(i, j)).badness函数计算第i个单词到第j个单词作为一行的badness值.
ZOJ上PE,不知道ZOJ的单词定义算不算上空格.
#include <cstdio>
#include <string>
#include <string.h>
using namespace std;
const int MAX = 10211;
int dp[MAX], cut[MAX], n;
char line[MAX];
string words[MAX];
int sum[MAX];
int S(int x, int y){
return sum[y] - sum[x - 1];
}
int square(int x){
return x * x;
}
int badness(int i, int j){
if(i == j){
return 500;
}else{
int num_of_words = j - i + 1;
int gaps = num_of_words - 1;
int total_spaces = n - S(i, j);
int rem = total_spaces % gaps;
int gap_len = total_spaces / gaps;
return (gaps - rem) * square(gap_len - 1) + rem * square(gap_len);
}
}
int main(int argc, char const *argv[]){
while(scanf("%d", &n)){
getchar();
if(n == 0)break;
int nw = 1;
while(gets(line)){
char * ptr = strtok(line, " ");
if(ptr == NULL) break;
while(ptr){
words[nw] = string(ptr);
sum[nw] = sum[nw - 1] + words[nw].length();
++nw;
ptr = strtok(NULL, " ");
}
}
memset(dp, 0x6f, sizeof(dp));
dp[nw] = 0;
for(int i = nw - 1; i >= 1; --i){
for(int j = i; j < nw && S(i, j) + (j - i) <= n; ++j){
int t = badness(i, j) + dp[j + 1];
if(dp[i] >= t){
dp[i] = t;
cut[i] = j;
}
}
}
//printf("%d\n", dp[1]);
for(int i = 1; i < nw; i = cut[i] + 1){
if(i == cut[i]){
printf("%s", words[i].c_str());
int num_of_spaces = n - words[i].length();
printf("%*c", num_of_spaces, ' ');
}else{
int num_of_words = cut[i] - i + 1;
int gaps = num_of_words - 1;
int total_spaces = n - S(i, cut[i]);
int rem = total_spaces % gaps;
int gap_len = total_spaces / gaps;
for(int j = 0; j < num_of_words; ++j){
printf("%s", words[i + j].c_str());
int sp;
if(gaps - rem <= j){
sp = gap_len + 1;
}else{
sp = gap_len;
}
if(j < num_of_words - 1){
printf("%*c", sp, ' ');
}
}
}
printf("\n");
}
printf("\n");
}
return 0;
}

本文介绍了一种使用动态规划解决的问题,即在给定的一段文章中,如何通过在单词之间添加适当的空格来使得每行单词的'坏处'最小。'坏处'定义为每两个单词之间空格数减一的平方。文章详细解释了如何通过迭代过程找到最优的分隔方案。

325

被折叠的 条评论
为什么被折叠?



