这道题的要点是首先必须算出最少要分的行数,也就是求最多可以分多少列,分的列数如果使得一行的总宽度大于60就到达列数的上界了,根据分的列数和行数以及单词的序号可以求出单词在最后打印出来的时候的行数和列数,根据这个行数和列数更新打印的缓存就行了,最后一次把缓存全部打印出来就行了,不要用printf一行一行地打印,这样去判断对齐不是很方便,直接用一块二维矩阵缓存所有最后要打印的内容要方便得多。
#include <stdio.h>
#include <string.h>
#include <algorithm>
#define MAX_LEN 105
#define WORD_LEN 70
struct word
{
char value[WORD_LEN];
};
struct word words[MAX_LEN];
int col_width[70];
int max_word_len;
char print_buffer[MAX_LEN][61]; //每行的最后一个位置存'\0'
int get_line_num(int n) //得出最多可以分的列数
{
int col = (60+2)/(max_word_len+2);
if(n%col == 0)
return n/col;
else
return n/col + 1;
}
int cmp(const void *a, const void *b)
{
struct word *pa = (struct word*)a;
struct word *pb = (struct word*)b;
return strcmp(pa->value, pb->value);
}
void func(int len)
{
int col, line;
int i;
int r, c;
qsort((void*)(words+1), len, sizeof(struct word), cmp);
col = (60+2)/(max_word_len+2);
line = get_line_num(len);
//printf("%d lines\n", line);
memset(print_buffer, '-', 60);
print_buffer[0][60] = '\0';
for(i=1; i<=line; i++)
{
memset(print_buffer+i, ' ', 60);
print_buffer[i][60] = '\0';
}
for(i=1; i<=len; i++)
{
//算出该单词所在的行数和列数
c = (i-1)/line+1;
r = (i-1)%line+1;
memcpy(print_buffer[r]+(c-1)*(max_word_len+2), words[i].value, strlen(words[i].value));
}
for(i=0; i<=line; i++)
{
printf("%s\n", print_buffer+i);
}
}
int main(void)
{
int n, i;
while(scanf("%d",&n) != EOF)
{
max_word_len = 0;
for(i=1; i<=n; i++)
{
scanf("%s", words[i].value);
if(strlen(words[i].value) > max_word_len)
max_word_len = strlen(words[i].value);
}
/*
printf("words:\n");
for(i=0; i<n; i++)
printf("%s\n", words[i]);
*/
func(n);
}
return 0;
}