算法竞赛入门经典 例题5-8

UVa400

Unix ls

非常不明白为什么UNIX上的ls命令会按照一列一列竖着的方式输出,反正这道题目很难写,主要有下面几个坑:

  • 输出时候只能按照行输出,但是字典序是按照列排列的,数组索引需要仔细斟酌一下
  • 文件名长度不足M要用空格补齐,即使是这一行最后的文件名,否则uDebug的例子过不去
  • 其实是每一行第一列的文件名补齐为M,如果有下一列,再输出那个2。这一点和书上的代码不一样,不知道书上的能不能AC,反正我的AC了
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;

int main()
{
	int n = 0;
	while (cin >> n){
		cin.get();
		vector<string> vecstr;
		string strFile;
		size_t M = 0;
		for (int i = 0; i < n; i++)
		{
			cin >> strFile;
			if (strFile.size() > M) M = strFile.size();
			vecstr.push_back(strFile);
		}
		sort(vecstr.begin(), vecstr.end());
		//col * M + (col - 1) * 2 <= 60
		//col = 62 / (M + 2)
		size_t col = 62 / (M + 2);
		size_t row = vecstr.size() / col;
		if (row * col < vecstr.size()) row++;
		cout << "------------------------------------------------------------" << endl;
		for (size_t i = 0; i < row; i++)
		{
			cout << vecstr[i] << string(M - vecstr[i].size(), ' ');
			for (size_t j = 1; j < col; j++)
			{
				size_t idx = j * row + i;
				if (idx < vecstr.size()){
					cout << "  " << vecstr[idx] << string(M - vecstr[idx].size(), ' ');
				}
				else break;
			}
			cout << endl;
		}
	}
	return 0;
}
/*
10
tiny
2short4me
very_long_file_name
shorter
size-1
size2
size3
much_longer_name
12345678.123
mid_size_name
12
Weaser
Alfalfa
Stimey
Buckwheat
Porky
Joe
Darla
Cotton
Butch
Froggy
Mrs_Crabapple
P.D.
19
Mr._French
Jody
Buffy
Sissy
Keith
Danny
Lori
Chris
Shirley
Marsha
Jan
Cindy
Carol
Mike
Greg
Peter
Bobby
Alice
Ruben
*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值