cppAcademy
FROM LEARNING TO COMPETING

Beginner.
Your first challenges.

Bulgarian Informatics Group E · 2007–2026

270 independently explained problems: 54 Municipal, 54 Regional, 105 National Olympiad tasks and 57 Autumn Tournament tasks. Start with the easier tasks and work upwards. Difficulty labels are learning estimates, not official ratings; Group E also includes challenging national-level problems. Years follow Arena’s competition-season labels. Source clarifications are noted on affected tasks.
GROUP E2011 · EasyString scans

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

  1. Read words with the extraction operator, which skips any number of spaces. Keep one best word.
  2. 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.
  3. 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.

Complexity: O(L) time and O(L) space for L input characters.

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';
}

Source: Arena Olimpiici ↗