心如止水
Je n'ai pas le temps
posts - 400,comments - 130,trackbacks - 0

题目要求模拟Unix下ls命令。给出一些列文件名,按字典序排序之后,以列优先的方式输出。除了最后一列之外,其余各列所占的字符数为最长文件名长度加2,最后一列所占数目为最长文件名长度。每行字符数不能超过60,要求最终的行数最少。
WA了2次,实在不应该,列输出方式没有控制好。我的做法是先输出到二维string数组中,因为这个数组并不一定被填满,这样一来接下来输出时有多种选择:1、做标记,没有被标记的元素不用输出(我最初这一步没有做好);2、判断(i,j)对应的文件名数组中的位置是否越界(不占用额外空间,不用对二维string数组赋值)。
以下是我的代码:

#include<iostream>
#include
<string>
#include
<algorithm>
#include
<cstdio>
using namespace std;
const int kMaxn(107);

string r[kMaxn],ls[kMaxn][kMaxn];

int main()
{
    
/*
    freopen("data.in","r",stdin);
    freopen("data.out","w",stdout);
    //
*/

    
int n;
    
while(cin>>n)
    {
        
int max_length(0);
        
for(int i=1;i<=n;i++)
        {
            cin
>>r[i];
            max_length
=max(max_length,static_cast<int>(r[i].size()));
        }

        sort(r
+1,r+n+1);
        
int row_num,column_num;
        
for(row_num=1;row_num<=n;row_num++)
        {
            column_num
=n/row_num;
            
if(n%row_num)
                column_num
++;
            
if((max_length+2)*(column_num-1)+max_length<=60)
                
break;
        }
        
for(int i=1,x=1,y=1;i<=n;i++)
        {
            ls[x][y]
=r[i];
            x
++;
            
if(x>row_num)
            {
                x
=1;
                y
++;
            }
        }

        
for(int i=1;i<=60;i++)
            cout
<<"-";
        cout
<<endl;
        
for(int i=1;i<=row_num;i++)
        {
            
for(int j=1;j<=column_num;j++)
            {
                
if((j-1)*row_num+i<=n)
                {
                    cout
<<ls[i][j];
                    
for(int k=ls[i][j].size();k<(j==column_num?max_length:(max_length+2));k++)
                        cout
<<" ";
                }
            }
            cout
<<endl;
        }
    }

    
return 0;
}
posted on 2011-04-09 17:24 lee1r 阅读(1142) 评论(0)  编辑 收藏 引用 所属分类: 题目分类:字符串处理题目分类:排序

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理