UVa400 Unix ls命令

題目:VJ:UVa400

代碼實現:

#include<iostream>
#include<vector>
#include<string>
#include<algorithm>

using namespace std;

int main()
{
	int N;
	while(scanf("%d",&N) == 1){
		vector<string> strvec;	//文件名數組 
		string fn;
		int maxsize;	//輸入文件名最大長度
		//輸入 
		for(int i = 0; i < N; ++i){
			cin >> fn;
			if(i == 0)
				maxsize = fn.size();
			if(maxsize < fn.size())
				maxsize = fn.size();
			strvec.push_back(fn);
		}
		sort(strvec.begin(),strvec.end());
		//計算行列數
		int fsize = strvec.size();	//文件名數量 
		int col = (60-maxsize)/(maxsize+2)+1; 
		int row = (fsize - 1)/col + 1;
		/*
		int row = fsize/col;
		if(fsize%col != 0)
			++row;
		*/
		//輸出 
		cout << string(60,'-') << endl;
		for(int i = 0; i < row; ++i){
			for(int j = 0; j < col; ++j){
				int n = j * row + i;
				if(n < fsize){
					string ts = strvec[n];
					ts += string(maxsize-ts.size(),' ');
					if(j != col-1)
						ts += string(2,' ');
					cout << ts;
				} 
			}
			cout << endl;
		}
	}
	return 0;
}

總結:

1.剛開始寫的時候使用set來存放文件名,順便就排序了,但要進行輸出時,發現要求是按列排序的,沒想到怎樣格式化輸出字符串,參考書中的代碼,醒悟可以逆向來做,按表輸出,把表中的位置定位到文件名數組中。

2.書中求row行數時也用了一個美好結論,學習了!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章