我是这样状态转移的,一维dp[i]表示前i个字符的badness的最小值,且i为最后一行的最后一个字符,这样可以保证dp最后一定是最小值,但题目要求输出开始的badness最小的情况,光有状态转移是不能保证这个条件的,开始我想的是,使i所在的那行单词尽量少,这样前面的单词尽量多就可以在总体上保证前面的badness最小,但交上去wa,后来想了一下,这样只是总体最小,不一定前面的某个局部最小,于是状态转移的时候还要考虑让前面的行数尽量少,这样就可以保证最开始的badness最小
//#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<cstdio>
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#define MAXN 10010
#define MAXM 85
using namespace std;
int n,words,len[MAXN],sumlen[MAXN];
char word[MAXN][MAXM];
int dp[MAXN],father[MAXN],lines[MAXN];
void init(){
getchar();
words=1;
int index,inputindex;
char input[MAXN];
memset(word,0,sizeof(word));
sumlen[0]=0;
while(gets(input)!=NULL&&strcmp(input,"")){
//puts(input);
inputindex=0;
while(input[inputindex]){
//cout<<*input;
if(input[inputindex]!=' '){
index=0;
while(input[inputindex]&&input[inputindex]!=' '){
word[words][index++]=input[inputindex++];
}
len[words]=index;
sumlen[words]=len[words]+sumlen[words-1];
words++;
}
else
inputindex++;
}
}
/*for(int i=1;i<words;i++){
puts(word[i]);
cout<<len[i]<<' '<<sumlen[i]<<endl;
}*/
memset(dp,0x7f,sizeof(dp));
dp[0]=0;
memset(lines,0,sizeof(lines));
}
void print(int last){
// cout<<'a';
if(last<=0)
return ;
print(father[last]);
if(father[last]==last-1){
printf("%s",word[last]);
// for(int i=0;i<n-len[words-1];i++)putchar(' ');
}
else{
int x=n-(sumlen[last]-sumlen[father[last]]);
int help=(last-father[last]-1);//y=help
int a=x-x/help*help;
for(int i=father[last]+1,j=0;i<=last;i++,j++){
printf("%s",word[i]);
if(j<(help-a)){
for(int t=0;t<x/help;t++)putchar(' ');
}
else if(j<help){
for(int t=0;t<x/help+1;t++)putchar(' ');
}
}
}
puts("");
}
void solve(){
for(int i=1;i<words;i++){
for(int j=1;i-j>=0&&sumlen[i]-sumlen[i-j]+j-1<=n;j++){
// cout<<'b';
if(j==1){
int t=dp[i-1]+((len[i]==n)?0:500);
if(t<dp[i]){//等于号?
dp[i]=t;
father[i]=i-1;
lines[i]=lines[i-1]+1;
}
}
else{
int x=n-(sumlen[i]-sumlen[i-j]);
int a=x-x/(j-1)*(j-1);
int t=dp[i-j]+(j-1-a)*(x/(j-1)-1)*(x/(j-1)-1)+a*(x/(j-1))*(x/(j-1));
if(t<dp[i]){
dp[i]=t;
father[i]=i-j;
lines[i]=lines[i-j]+1;
}
else if(t==dp[i]&&lines[i-j]+1<lines[i]){
dp[i]=t;
father[i]=i-j;
lines[i]=lines[i-j]+1;
}
}
}
}
print(words-1);
puts("");
//cout<<dp[words-1]<<endl;
}
int main(){
while(scanf("%d",&n)&&n){
init();
solve();
}
return 0;
}