50 likes | 70 Views
Word Wrap. HKOI 2005 Junior Q3. Problem. Word wrap – a common feature of text editors / text processors Given an stream of words, place line breaks appropriately such that each line has the “maximum possible” number of words that do not exceed the limit of W words per line. How to do it?.
E N D
Word Wrap HKOI 2005 Junior Q3
Problem • Word wrap – a common feature of text editors / text processors • Given an stream of words, place line breaks appropriately such that each line has the “maximum possible” number of words that do not exceed the limit of W words per line.
How to do it? • For every word, we need to consider whether to put a word on the current line, or on the next line • (We can also observe that the arrangement of lines in the input does not matter) • So we need to convert the lines of the input into words
Implementation • Suppose we read a line from input each time • Split the line into words • We can choose to immediately output the words, or we can choose to store the words in an array to be used later • During output, consider the length l of the “current” line. If (l + 1 + length(next word) > W), then go on to the next line.
Notes • For C++, you can efficiently read in just a “word” by cin >> a, where a is a string • For pascal, functions like “pos” and “copy” are useful. You may also choose to handle the string as an array of characters. • The size of the problem is quite small, solutions should be in linear time, runtime is not a major concern. • A problem that assesses basic data processing and string manipulation of contestants.