Problem Info
Type: Regional
Continent: Africa and Arab
Year: 2000
Link: 2169 - Text Justification/Wrapping
Problem Statement
For this problem, assume that words are not to be split between lines and that each line is to be both left and right justified, except for the last line of text. Any extra blank characters which are required in the justification of the text are to be distributed as uniformly as possible between the words of a line. Furthermore, we assume that there are no paragraphs and that pagination and indentation are not required. Finally, each word in the input text is separated from every other word by a blank, and each punctuation symbol is followed by a blank.
For the output, assume 50 characters per line.
Explanation
The solution for this problem is an ad-hoc solution.
We take the words as they come and as soon as there are enough words to print a line it is printed with the corresponding spaces.
Code
The C++ that solves the problem is the following(2169.cpp):
#include <iostream> #include <string> #include <vector> using namespace std; int main() { string word; vector<string> wordlist; int count = 0; while (cin >> word) { if (count + wordlist.size() + word.size() > 50) { // Print a line int each, rem; if (wordlist.size() == 1) { each = 50 - wordlist[0].size() - 1; rem = 0; } else { each = (50 - count - (wordlist.size() - 1)) / (wordlist.size() - 1); rem = (50 - count - (wordlist.size() - 1)) % (wordlist.size() - 1); } for (int i = 0; i < wordlist.size() - 1; ++i) { cout << wordlist[i]; for (int j = 0; j < (1 + each); j++) cout << " "; if (i < rem) cout << " "; } cout << *wordlist.rbegin() << '\n'; wordlist.clear(); wordlist.push_back(word); count = word.size(); } else { wordlist.push_back(word); count += word.size(); } } if (wordlist.size() > 0) { for (int i = 0; i < wordlist.size() - 1; ++i) { cout << wordlist[i]; cout << " "; } cout << *wordlist.rbegin() << '\n'; } return 0; }