題目要求模擬Unix下ls命令。給出一些列文件名,按字典序排序之后,以列優(yōu)先的方式輸出。除了最后一列之外,其余各列所占的字符數(shù)為最長(zhǎng)文件名長(zhǎng)度加2,最后一列所占數(shù)目為最長(zhǎng)文件名長(zhǎng)度。每行字符數(shù)不能超過(guò)60,要求最終的行數(shù)最少。
WA了2次,實(shí)在不應(yīng)該,列輸出方式?jīng)]有控制好。我的做法是先輸出到二維string數(shù)組中,因?yàn)檫@個(gè)數(shù)組并不一定被填滿,這樣一來(lái)接下來(lái)輸出時(shí)有多種選擇:1、做標(biāo)記,沒(méi)有被標(biāo)記的元素不用輸出(我最初這一步?jīng)]有做好);2、判斷(i,j)對(duì)應(yīng)的文件名數(shù)組中的位置是否越界(不占用額外空間,不用對(duì)二維string數(shù)組賦值)。
以下是我的代碼:
#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 閱讀(1185)
評(píng)論(0) 編輯 收藏 引用 所屬分類:
題目分類:字符串處理 、
題目分類:排序