问题链接:HDU3753 Alignment of Code。
问题描述:参见上文。
问题分析:
输入有若干行,每行有若干单词,让各行的单词对齐。这应该是一个单词矩阵。
输出时,需要构造好这个矩阵。同时,需要分别对各个列的单词计算其最长的长度。有了这两点,输出就不是问题了。
程序说明:
数组maxlen[]用于存储各个列的单词的最长长度,maxlen[i]=k表示第i列单词的最长为k。
数组wordcount[]用于存储各个行的单词数量。
二维字符串数组words[]用于存储各个行的单词,words[i]中存储第i行的各个单词。
C++的输出格式控制需要用到库iomanip。
由于HDU机器运行速度慢,所以没有使用字符串向量数组,而是使用二维字符串数组。
HDU的这个问题,输入格式与《UVALive4983 UVa1593 POJ3959 Alignment of Code》是不同的,所以另外写了这个程序。
参考链接:UVALive4983 UVa1593 POJ3959 Alignment of Code。
题记:仅仅是逻辑正确是不够的,还需要考虑时间和空间。
AC的C++语言程序:
/* HDU3753 Alignment of Code */
#include <iostream>
#include <string>
#include <sstream>
#include <cstring>
#include <iomanip>
using namespace std;
const int N = 180;
const int N2 = 1000;
int maxlen[N], wordcount[N2+1];
string words[N2+1][N];
int main()
{
int t;
string line, word;
cin >> t;
while(t--) {
memset(maxlen, 0, sizeof(maxlen));
memset(wordcount, 0, sizeof(wordcount));
int linecount = 0;
while(getline(cin,line) && line != "@"){
if(line == "")
continue;
stringstream ss(line);
int i = 0;
while(ss >> word) {
maxlen[i] = max((int)word.length(), maxlen[i]);
words[linecount][i++] = word;
}
wordcount[linecount++] = i;
}
cout << setiosflags(ios::left);
for(int i=0; i <linecount; i++) {
int j;
for(j=0; j<wordcount[i]-1; j++)
cout << setw(maxlen[j] + 1) << words[i][j];
cout << words[i][j] << endl;
}
}
return 0;
}