标签:
题目大意:一个字符串,去掉空格和符号后变成"plaintext"。另一个字符串叫"keyword"。将plaintext排成多行,每行有keyword.size的宽度,不能排满一列的用别的字符填满,生成了字符矩阵。每次选取keyword中字典序最小的字符对应的列,作为需要选取的矩阵的列,被选择过的字符不再被选择,最后形成一行新的字符串,作为输出字符串。
解题思路:对keyword中的字符及其对应的列进行排序,利用排序结果还原成字符矩阵,然后按行输出字符矩阵。
代码如下:
1 #include <iostream> 2 #include <string> 3 #include <vector> 4 using namespace std; 5 6 const int COLS = 15; 7 const int ROWS = 105; 8 9 string kw; 10 string ct; 11 12 char m[ROWS][COLS]; 13 14 void init() { 15 for (int i = 0; i < ROWS; i++) { 16 for (int j = 0; j < COLS; j++) { 17 m[i][j] = 0; 18 } 19 } 20 } 21 22 struct Elem { 23 char ch; 24 int col; 25 }; 26 27 Elem elems[COLS]; 28 29 bool cmp(const Elem & e1, const Elem &e2) { 30 /*if (e1.ch > e2.ch) { 31 return true; 32 } else if (e1.ch < e2.ch) { 33 return false; 34 } else { 35 if (e1.col > e2.col) { 36 return true; 37 } else if (e1.col < e2.col){ 38 return false; 39 } else { 40 return false; 41 } 42 }*/ 43 44 return (e1.ch > e2.ch) || (e1.ch == e2.ch && e1.col > e2.col); 45 } 46 47 int main() { 48 string end = "THEEND"; 49 50 while (cin >> kw, kw != end) { 51 cin >> ct; 52 int c = kw.size(); 53 int r = ct.size() / kw.size(); 54 55 for (int i = 0; i < c; i++) { 56 elems[i].ch = kw[i]; 57 elems[i].col = i; 58 } 59 60 for (int i = 0; i < c; i++) { 61 for (int j = 0; j < c - i - 1; j++) { 62 if (cmp(elems[j], elems[j + 1])) { 63 Elem elem = elems[j]; 64 elems[j] = elems[j+1]; 65 elems[j+1] = elem; 66 } 67 } 68 } 69 70 for (int i = 0; i < c; i++) { 71 int begin = r * i; 72 //int end = begin + r; 73 int col = elems[i].col; 74 75 for (int j = 0; j < r; j++) { 76 m[j][col] = ct[begin + j]; 77 } 78 } 79 80 for (int i = 0; i < r; i++) { 81 for (int j = 0; j < c; j++) { 82 cout << m[i][j]; 83 } 84 } 85 86 cout << endl; 87 } 88 89 return 0; 90 }
标签:
原文地址:http://www.cnblogs.com/mchcylh/p/4856348.html