题目:题目是要对输入的每组文件名进行规则化输出,除了最后一列,其他列的宽度为maxlen+2,最后一列宽度为maxlen。maxlen为最长字符串的长度。(这个题看了好几遍都没看懂题意,最后google出来的才从博客明白此题题意。。之前自己一直是在数每列最长字符串后的空格数,总是明白不了题意。The rightmost column will be the width of the longest filename and all other columns will be the width of the longest filename plus 2.)
思路:对字符串排序,然后计算相应长度,得出maxlen。现在需要确定列数和行数。列数:设有n+1列。则(maxlen+2)*n+maxlen<=60,则n<=(60-maxlen)/(maxlen+2),n是整数,且n需要最大化,则n即为右边值。行数:对( q 除以 lie )取上整,这里的q是总共字符串数。这里是从左往右排,一列排满了再排下一列。
注意:总是在输入数据的for循环里对刚输入的数据进行strlen啊或字母排序处理,结果这个for循环结束之后,又对它进行了qsort,则导致不一一对应了。(错两次了,上次好像是边输入边对副本进行字母排序了,出了循环又qsort了,不能一一对应)
Code:
//#define LOCAL #include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> #define M 110 #define N 70 int cmp_string(const void *_a, const void *_b); char fname[M][N]; int flen[M]; int main() { #ifdef LOCAL freopen("data400.in","r",stdin); freopen("data400.out","w",stdout); #endif int n; while(scanf("%d",&n)!=EOF) { printf("------------------------------------------------------------\n"); int maxlen=0; for(int i=0;i<n;++i) scanf("%s",fname[i]); qsort(fname,n,sizeof(fname[0]),cmp_string); for(int i=0;i<n;++i) {//注意这里这两句应该在qsort后执行,不要写在上个输入数据的循环里了 flen[i]=strlen(fname[i]); maxlen=maxlen>flen[i]?maxlen:flen[i]; } int lie=(60-maxlen)/(maxlen+2)+1; int row=(int)ceil((n+0.0)/lie); //fprintf(stderr,"lie:%d\n",lie); //fprintf(stderr,"row:%d\n",row); for(int i=0;i<row;++i) for(int j=0;j<lie;++j) { int x=j*row+i; if(x<n) printf("%s",fname[x]); if(j!=lie-1) { //fprintf(stderr,"maxlen:%d\n",maxlen); //fprintf(stderr,"%s %d\n",fname[x],flen[x]); //fprintf(stderr,"n:%d\n",n); for(int k=flen[x];k<maxlen+2;++k) printf(" "); } else { for(int k=flen[x];k<maxlen;++k) printf(" "); printf("\n"); }//else }//for }//while return 0; } int cmp_string(const void *_a, const void *_b) { char *a=(char*)_a; char *b=(char*)_b; return strcmp(a,b); }
UVa 400 Unix的ls命令,布布扣,bubuko.com
原文:http://blog.csdn.net/buxizhizhou530/article/details/21352819