POJ 1093 Formatting Text(DP)

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

题意:给出一段文章,要求将里面的单词按照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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值