Longest Word
National Olympiad — National round (2011 season)
Submission name: words.cpp
Problem summary
Find the longest input word. Break equal-length ties by the smallest first letter; if that also ties, retain the earliest word.
Input
One line of lowercase Latin words separated by one or more spaces.
Output
The length and chosen word, separated by one space.
Constraints
At most 100 input characters.
Worked example
An independently prepared example for this explanation.
Input
oko banan liniq more
Output
5 banan
Solution analysis
- Read words with the extraction operator, which skips any number of spaces. Keep one best word.
- Replace the best if the new word is longer, or if equal length and its first letter is smaller. Do not compare the remaining letters.
- Both banan and liniq have length 5. Since b comes before l, choose banan and print 5 banan.
Why it works
After each word, best is the required winner among the processed words. The replacement rule is exactly the stated priority order, so the invariant holds until all words are read.
Watch out. A full lexicographic comparison gives the wrong tie rule. Equal first letters preserve input order.
Commented C++17 solution
An independently written complete program with standard headers.
#include <iostream>
#include <string>
using namespace std;
int main() {
string word, best;
while (cin >> word) {
// Compare only the first letter when lengths tie.
if (best.empty() || word.size() > best.size() || (word.size() == best.size() && word[0] < best[0])) {
best = word;
}
}
cout << best.size() << ' ' << best << '\n';
}