Learn C++ STL

Lesson 8 of 9 · From C to Just-Enough C++

Module 1 · From C to Just-Enough C++

Problems: Just-Enough C++

FreeProblems

In this lesson

  • Write the fixed shape every STL problem in this track takes: the two fast-input lines, read with std::cin, compute, print with '\n'.
  • Read input whose length nobody gives you, value by value or line by line, and choose long long wherever a total can pass 2147483647.
  • Test the edges a hidden test will try, before you submit: empty input, n = 1, all values equal, the largest n.

Ten problems, graded against hidden tests. Each one uses one or two lessons of this module. You met every one of them already, as an exercise beside the lesson that teaches it. Here they sit together, each with a ladder of two hints and a worked solution.

Lesson 02 measured a million numbers. These problems are the first place where that habit meets a judge. The judge runs your whole program on an input you never see and compares what it prints. Bob reads the sample, writes a loop and submits. Zara reads the constraints first, then runs an empty input, a single value and the largest values before the sample. In this set, Zara's habit earns the marks.

The shape every STL problem here takes

Every starter below has the same skeleton, and so will every problem in this track. It is the C problem shape with C++ words.

#include <iostream>

int main()
{
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);

    int n = 0;
    std::cin >> n;

    long long total = 0;
    for (int i = 0; i < n; i++) {
        long long x = 0;
        std::cin >> x;
        total += x;
    }
    std::cout << total << '\n';
    return 0;
}
12

That output is for the input 3 and 4 -2 10. The two lines after the brace are lesson 02's: they cut std::cin loose from C's input and stop it flushing std::cout before every read. Every line of output ends with '\n', never std::endl, so nothing is flushed early.

The judge compiles your file as C++17 with GCC 12 at -O2, the Playground's c++17. It gives each test 1 second for the whole program, reading included. It compares your output with the expected output line by line. Spaces at the end of a line, and blank lines at the very end, are ignored. Nothing else is forgiven: a label such as Sum: , a missing line or a blank line between two answers fails the test.

So the shape is fixed: two lines, read, compute, print exactly what the statement asks, one '\n' per line.

When nobody says how many

Three problems in this set do not give a count first. Lesson 02 taught both ways to read such input, and the table says which problem needs which.

The input isThe loopProblems
values, any number of them, to the endwhile (std::cin >> x)sum-until-end
n, then n lines of textstd::cin >> n, one throwaway std::getline, then n morewords-per-line
lines, any number of them, to the endwhile (std::getline(std::cin, line))line-totals

Each loop stops when a read fails, and at the end of the input every read fails. So an empty input is a legal test: the loop body never runs, and your program must still print the right answer for "nothing". For sum-until-end that answer is 0 0.

The middle row is the trap of lesson 02. After std::cin >> n, the newline that ended the first line is still waiting. A std::getline straight after it returns that empty remainder, so every line you read is one line late. Here is the run that shows it, on the sample of words-per-line, with a program that prints each line it gets in brackets.

#include <iostream>
#include <string>

int main()
{
    int n = 0;
    std::cin >> n;

    std::string line;
    for (int k = 1; k <= n; k++) {
        std::getline(std::cin, line);
        std::cout << k << ": [" << line << "]\n";
    }
    return 0;
}
1: []
2: [the cat sat]
3: []

That output is for the input 3, then the cat sat, an empty line and on the mat. Line 1 came back empty, the real line 1 arrived as line 2, and the last line was never read. So when n comes before the lines, throw away the rest of n's line first. When no count comes at all, loop until a read fails.

Which totals need long long

An int on the Playground holds up to 2147483647, a little over 2 x 109. The values in this set reach 109, and in one problem 2 x 109. So a single value fits, and three of them added together do not. Read two numbers off every statement: the largest value and the largest count. Their product is the largest total.

ProblemLargest valueLargest countLargest total or resultType
sum-until-end109800008 x 1013long long
doubled2 x 109800004 x 109, one value doubledlong long
line-totals109800008 x 1013long long
the other seven109up to 80000no total is formedint

Every test of every problem is at most 1 MiB, the judge's limit on a single test. That is why the counts stop at 80000 rather than a million: 80000 values of 11 or 12 characters fill most of a megabyte. At that size the time limit is generous. On the largest test of line-totals, 20000 lines and 80000 numbers in 831661 bytes, the reference solution took these times. Each is one run on Compiler Explorer, x86-64 GCC 12.2, at the Playground's -O2 -std=c++17, timed inside the program with its output sent to a file.

Input and output setupTime for the whole input
the two lines, '\n'9.9 ms
neither line, std::endl28.8 ms
neither line, '\n'32.5 ms
the two lines, std::endl38.5 ms
line-totals, largest test: four input and output setups two lines, '\n' 9.9 ms neither line, std::endl 28.8 ms neither line, '\n' 32.5 ms two lines, std::endl 38.5 ms One run each, GCC 12.2, -O2 -std=c++17. The 1 s limit would be about 26 times the longest bar.

All four are far inside 1 second, so no test here can punish slow input by itself. The habit is for later. Lesson 02's million numbers took 750 ms the slow way and 58 ms the fast way, and the contests of Module 16 go there. So the totals decide the type, and the two lines are a habit this set lets you build cheaply.

The forms these ten problems need

std::ios::sync_with_stdio(false);      the first fast-input line (lesson 02)
std::cin.tie(nullptr);                 the second one
while (std::cin >> x) { ... }          read values until the input ends
std::getline(std::cin, line);          read one whole line into a std::string
while (std::getline(std::cin, line))   read lines until the input ends
std::istringstream in(line);           read values out of a line (<sstream>)
long long total = 0;                   a total that can pass 2147483647
void order(int& a, int& b)             a function that changes its caller's variables
for (long long& x : values)            a range-for that changes every element
std::max(best, x)                      the larger of two values of the same type
std::pair<std::string, int> best;      two values under one name
return {lo, hi};                       return a pair from a function
auto [lo, hi] = minMax(a, k);          name both parts of a returned pair
std::sort(v.begin(), v.end());         sort a vector, pairs by first then second
  • Every starter declares what the statement names and reads the input where the reading is not the point. Keep those lines and write your code where the comment says.
  • Values on one line are separated by single spaces, and every answer line ends in '\n'.
  • Test the edges before the sample: the empty input where the statement allows it, n = 1, all values equal, all negative, and the largest values.
Example 1: the shape, on a small task

Alice counts how many of n game scores are even. The statement gives n first, so a counted loop reads it.

#include <iostream>

int main()
{
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);

    int n = 0;
    std::cin >> n;

    int even = 0;
    for (int i = 0; i < n; i++) {
        int x = 0;
        std::cin >> x;
        if (x % 2 == 0) {
            even++;
        }
    }
    std::cout << even << '\n';
    return 0;
}
3

That output is for the input 5 and 4 7 -2 0 9. Zero and -2 are even, as the % of C says. The output is the bare number, because the statement asks for nothing else.

Run in Compiler
Example 2: pairs of values until the input ends

Kenji logs each game as a name and a score, with no count first. >> can read two values per pass, and the loop stops when the pair cannot be read.

#include <iostream>
#include <string>

int main()
{
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);

    std::string name;
    int score = 0;
    int games = 0;
    long long total = 0;

    while (std::cin >> name >> score) {
        games++;
        total += score;
    }
    if (games == 0) {
        std::cout << "no games\n";
    } else {
        std::cout << games << " games, average " << (double)total / games << '\n';
    }
    return 0;
}
4 games, average 62.5

That output is for the input chess 70, go 45, chess 80 and go 55, one game per line. With an empty input the loop never runs, and the if keeps the program from dividing by zero. Zara runs that case first.

Run in Compiler
Example 3: Amara's step report, all of it

Amara has n days of step counts. She wants the total, the best day (counted from 1, the first if tied) and how many days beat the average. The average needs every count first, so the counts wait in an array.

#include <iostream>

const int MAX_N = 100000;

int steps[MAX_N];

int main()
{
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);

    int n = 0;
    std::cin >> n;
    for (int i = 0; i < n; i++) {
        std::cin >> steps[i];
    }

    long long total = 0;
    int bestDay = 0;
    for (int i = 0; i < n; i++) {
        total += steps[i];
        if (steps[i] > steps[bestDay]) {
            bestDay = i;
        }
    }

    int aboveAverage = 0;
    for (int i = 0; i < n; i++) {
        if ((long long)steps[i] * n > total) {
            aboveAverage++;
        }
    }
    std::cout << total << '\n';
    std::cout << bestDay + 1 << '\n';
    std::cout << aboveAverage << '\n';
    return 0;
}
45500
3
2

That output is for the input 5 and 8000 6500 12000 9000 10000. The average is 9100, and two days beat it. Comparing steps[i] * n with the total avoids a fraction altogether. The cast makes that product a long long, because 100000 days of a million steps would pass the int limit.

The array sits outside main, so it is not on the stack, the C track's rule for an array this big. In C++ a const int sizes it, as lesson 03 said.

Run in Compiler

Where this is used

  • Progsity's judge. Each problem here is a judge problem with an exact checker and all-or-nothing scoring: every hidden test must pass, and the sample is test 1.
  • Codeforces. A rejected submission names the first test it failed, as in "Wrong answer on test 3". The time limit is per test, for the whole program.
  • AtCoder. Its verdicts are the same family, AC, WA, TLE and RE, and most of its problems read everything from standard input in exactly this shape.

Common mistakes

1. An int total.

int sum = 0;
int x = 0;
while (std::cin >> x) {
    sum += x;
}

No message at any command line, the Playground's or -Wall -Wextra. On the input 1000000000 1000000000 1000000000, one run on Compiler Explorer at the Playground's flags printed -1294967296 3. The true sum, 3000000000, does not fit an int, and signed overflow is undefined behaviour, as in C. Make the total long long. You will write int because the sample's numbers are small.

2. std::getline straight after std::cin >> n.

std::cin >> n;
for (int k = 1; k <= n; k++) {
    std::getline(std::cin, line);
}

No message at any command line; the run above shows the cost. Every line arrives one place late and the last is lost. Read the rest of n's line once before the loop. You will forget because >> skipped the newlines for you in every earlier program.

3. Printing more than the statement asks for.

std::cout << "Sum: " << sum << ", count: " << count << '\n';

No message anywhere, and every test fails, because the judge compares characters and the statement asked for 6 3. Print exactly the format of the Output section. You will add labels because they make the Playground's output easier to read; take them out before you submit.

4. A starting value that is not a real value.

int best = 0;
for (int i = 0; i < n; i++) {
    std::cin >> x;
    best = std::max(best, x);
}

No message anywhere, and the answer is 0 whenever every value is negative. Start from the first value you read. You will start at 0 because the samples are full of positive numbers; Zara's all-negative test is the cure.

Brain teaser

Bob writes all ten solutions with int everywhere and never long long, even where a starter offers one. Some still pass every test. Which of the ten problems can a hidden test break, and what is the shortest input that breaks each of them?

An int stops at 2147483647. Look for the problems that add values together, and the one whose values alone come close to the limit.

Problem 1: sum-until-endEasyFree

Zara's step counter does not say how many readings it saved. It pours them out, some on one line and some on the next, until it runs out. She wants the total and how many there were.

Input. Zero or more integers, separated by spaces and newlines, until the end of the input.

Output. One line: the sum, one space, the count. With no integers at all, print 0 0.

Constraints. At most 80000 integers, each between -1000000000 and 1000000000.

Sample. Input 3 5 and -2 on two lines gives 6 3.

#include <iostream>

int main()
{
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    // Read integers until the input ends. Print their sum and how many
    // there were, on one line, separated by one space.

    return 0;
}
Run in Compiler

Hint 1

No count comes first, so a counted loop has nothing to count to. Which loop of lesson 02 ends by itself when the input runs out? And how large can the sum get?

Hint 2

Loop on while (std::cin >> x), adding x to a long long sum and adding 1 to a count. Print both after the loop, so the empty input prints the starting values, 0 and 0.

Solution

The condition std::cin >> x is true while a value was read and false once the input is exhausted. A line break is only more space between numbers, so values spread over several lines need nothing special. Declaring x as long long as well keeps every type in the sum the same.

The sum needs long long: 80000 values of 109 total 8 x 1013. Three of them already pass the int limit, and the hidden tests check that. An if for the empty input is not needed, because the loop's body simply never runs. Reading the first value before the loop, Bob's habit, breaks exactly that test.

Problem 2: max-and-positionEasyFree

Kenji logs the score of every game in a tournament. He wants the best score and which game it came from, games counted from 1. If the best score appears twice, he wants the first game.

Input. The first line holds n. The second holds n integers.

Output. One line: the largest score, one space, its first position.

Constraints. 1 <= n <= 80000. Each score is between -1000000000 and 1000000000.

Sample. Input 5 and 4 9 2 9 1 gives 9 2.

#include <iostream>

int main()
{
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    int n = 0;
    std::cin >> n;

    // Read the n integers. Print the largest one and its position
    // (the first integer is position 1), separated by one space.
    // If the largest appears more than once, print its first position.

    return 0;
}
Run in Compiler

Hint 1

What should the best score be before you have read any? Try your idea on a list where every score is negative. And on a tie, which comparison keeps the earlier game?

Hint 2

Read the first score into best with position 1. Then for positions 2 to n, read a score and replace the best only when the new score is strictly greater.

Solution

Starting from the first real score removes the need for a guess such as 0 or "a very small number". A guess of 0 fails every all-negative test, and a hidden test has one. Counting the positions from 2, because position 1 is already read, keeps the printed position in the statement's 1-based form with no + 1 to forget.

Strictly greater, >, keeps the first of equal scores; >= would move to the last and fail the tie tests. No array is needed, because each score is looked at once, as it arrives.

Problem 3: order-threeMediumPro

Maria lines up three parcels by weight, lightest on the left. Her only move is to swap two neighbours if the left one is heavier. Three such moves always do the job. The starter gives that move as void order(int& a, int& b).

Input. The first line holds t. Each of the next t lines holds three integers.

Output. t lines, each with its three integers in increasing order, separated by single spaces.

Constraints. 1 <= t <= 10000. Each integer is between -1000000000 and 1000000000.

Sample. Input 3, then 3 1 2, 5 5 1 and -1 -2 -3, gives 1 2 3, 1 5 5 and -3 -2 -1.

#include <iostream>

// Put a and b in order: after the call, a <= b.
void order(int& a, int& b)
{
    // your code
}

int main()
{
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    int t = 0;
    std::cin >> t;
    for (int i = 0; i < t; i++) {
        int a = 0;
        int b = 0;
        int c = 0;
        std::cin >> a >> b >> c;

        // Use order() to put a, b and c in increasing order,
        // then print them on one line, separated by single spaces.
    }
    return 0;
}
Run in Compiler

Hint 1

The parameters are references, so swapping them inside order swaps main's variables (lesson 03). Which pairs of neighbours must Maria compare, and in what order, so that the heaviest parcel reaches the right end?

Hint 2

In order, swap a and b only when a > b. In main, order the left pair, then the right pair, then the left pair once more.

Problem 4: best-markEasyFree

Amara marks a class test and writes each student's name and mark as she goes. The best mark wins a book; on a tie, the paper she marked first wins. Keep the winner so far in std::pair<std::string, int> best.

Input. The first line holds n. Each of the next n lines holds a name and a mark.

Output. One line: the winner's name and mark.

Constraints. 1 <= n <= 10000. A name is 1 to 20 lowercase letters; a mark is from 0 to 100.

Sample. Input 4, then alice 82, bob 91, zara 91 and kenji 75, gives bob 91.

#include <iostream>
#include <string>
#include <utility>

int main()
{
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    int n = 0;
    std::cin >> n;

    std::pair<std::string, int> best;

    // Read n lines, each a name and a mark. Keep the best one in best:
    // the highest mark, and on a tie the one that came first.
    // Then print best's name and mark, separated by one space.

    return 0;
}
Run in Compiler

Hint 1

The starter's best begins as an empty name and a mark of 0. What does your program print for a class where every mark is 0?

Hint 2

Read the first student straight into best.first and best.second. For each later student, read into a second pair and copy it over best only when its mark is strictly greater.

Solution

The pair keeps the name and the mark together, so replacing the winner is one assignment, best = next;, and both parts move at once. Comparing only .second is right here: the marks decide, and on a tie the earlier student stays because the comparison is strictly greater.

Comparing whole pairs with < would be wrong, because a pair compares its name first (lesson 06). Leaving best at its starting value fails the all-zero class: no mark is greater than 0, so the program prints an empty name.

Problem 5: words-per-lineMediumPro

David is building an index for his notes: every word with the number of the line it is on. Some lines are empty, and some have extra spaces. A word is a run of characters that are not spaces.

Input. The first line holds n. Then n lines of text follow, possibly empty, possibly with leading, trailing or repeated spaces.

Output. One line per word, in order: the text line's number (from 1), one space, the word. Nothing for a line with no words.

Constraints. 1 <= n <= 1000. Each text line has at most 1000 characters, with no tabs.

Sample. Input 3, then the cat sat, an empty line and on the mat, gives 1 the, 1 cat, 1 sat, 3 on, 3 the and 3 mat.

#include <iostream>
#include <string>

int main()
{
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    int n = 0;
    std::cin >> n;

    // Read the n lines of text that follow with std::getline.
    // For every word, print the number of its line (1 to n),
    // one space and the word, one word per output line.

    return 0;
}
Run in Compiler

Hint 1

Run the bracket program of "When nobody says how many" on the sample. Then think about what std::cin >> word would do to the empty second line: does it know where lines end?

Hint 2

After reading n, call std::getline once and ignore the result. Then read n lines. Walk each line's characters, building a word; at a space, print the word if it is not empty and clear it. After the last character, print what is left.

Problem 6: sort-pairsEasyPro

Alice runs a book swap. Every book has a shelf number and a slot number. She wants the list in walking order: shelf by shelf, and slot by slot on a shelf. The starter reads the pairs into a std::vector<std::pair<int, int>>.

Input. The first line holds n. Each of the next n lines holds a shelf and a slot.

Output. n lines, sorted by shelf and then by slot; equal pairs as often as they appear.

Constraints. 1 <= n <= 40000. Each integer is between -1000000000 and 1000000000.

Sample. Input 4, then 3 1, 1 5, 3 0 and 1 2, gives 1 2, 1 5, 3 0 and 3 1.

#include <algorithm>
#include <iostream>
#include <utility>
#include <vector>

int main()
{
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    int n = 0;
    std::cin >> n;

    // A vector is an array that knows its own size (Module 2 teaches it).
    std::vector<std::pair<int, int>> v(n);
    for (auto& p : v) {
        std::cin >> p.first >> p.second;
    }

    // Sort v by first, and by second when the firsts are equal.
    // Then print one pair per line: first, one space, second.

    return 0;
}
Run in Compiler

Hint 1

Compare the order the statement asks for with the order two pairs compare in (lesson 06). Do you need to write any comparing yourself?

Hint 2

Call std::sort on the whole vector, from v.begin() to v.end(), then print every pair with a range-for and a structured binding.

Problem 7: min-max-pairMediumPro

David checks a cold store's temperature log several times a day. Each check is a short list, and the report needs its coldest and warmest reading. The starter declares std::pair<int, int> minMax(const int a[], int k).

Input. The first line holds t. Each of the next t lines holds k, then k integers.

Output. t lines, each the smallest and the largest of its list.

Constraints. 1 <= t <= 1000 and 1 <= k <= 1000, at most 80000 integers in all, each between -1000000000 and 1000000000.

Sample. Input 3, then 3 4 -2 7, 1 5 and 4 2 2 2 2, gives -2 7, 5 5 and 2 2.

#include <iostream>
#include <utility>

const int MAX_K = 1000;

// Return the smallest and the largest of a[0] to a[k - 1], in that order.
std::pair<int, int> minMax(const int a[], int k)
{
    return {0, 0}; // replace this line
}

int main()
{
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    int t = 0;
    std::cin >> t;

    int a[MAX_K];
    for (int i = 0; i < t; i++) {
        int k = 0;
        std::cin >> k;
        for (int j = 0; j < k; j++) {
            std::cin >> a[j];
        }

        // Call minMax and print the smallest and the largest,
        // separated by one space.
    }
    return 0;
}
Run in Compiler

Hint 1

The function has two answers and returns one value. What can that one value hold? And for a list of only negative readings, what must the largest start as?

Hint 2

Start both lo and hi at a[0], walk the rest, then return {lo, hi};. In main, unpack the result with auto [lo, hi] = minMax(a, k); and print both.

Problem 8: doubledEasyPro

A shop doubles every price for one silly day, and Bob must update the list where it stands. The starter reads the prices into std::vector<long long> values. Double every value in place with a range-for, then print the list.

Input. The first line holds n. The second holds n integers.

Output. One line: the n values, each doubled, in order, separated by single spaces.

Constraints. 1 <= n <= 80000. Each integer is between -2000000000 and 2000000000.

Sample. Input 4 and 3 -1 0 2000000000 gives 6 -2 0 4000000000.

#include <iostream>
#include <vector>

int main()
{
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    int n = 0;
    std::cin >> n;

    // A vector is an array that knows its own size (Module 2 teaches it),
    // so a range-for over it walks exactly the n values.
    std::vector<long long> values(n);
    for (long long& x : values) {
        std::cin >> x;
    }

    // Double every value in place with a range-for. Then print the
    // values on one line, separated by single spaces.

    return 0;
}
Run in Compiler

Hint 1

Of the three forms of the range-for in lesson 04, which one can change the elements? Look at how the starter's reading loop gets its values into the vector.

Hint 2

Loop with for (long long& x : values) and write x *= 2;. Then print in a second loop, with a space before every value but the first.

Problem 9: max-of-each-lineMediumPro

Kenji's sensor station sends batches of three kinds: whole-number counts, decimal temperatures and station names. The dashboard shows the largest value of each batch; for a word, the one a dictionary lists last.

Input. The first line holds t. Each of the next t lines starts with int, double or string, then k, then k values of that type.

Output. t lines, each the largest value of its batch, printed with plain std::cout <<: a double 2.50 prints as 2.5.

Constraints. 1 <= t <= 800 and 1 <= k <= 100. Ints are within ±109, doubles within ±1000 with at most two decimals, strings 1 to 10 lowercase letters.

Sample. Input 3, then int 3 4 -2 7, double 2 2.5 1.25 and string 3 pear apple zebra, gives 7, 2.5 and zebra.

#include <algorithm>
#include <iostream>
#include <string>

int main()
{
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    int t = 0;
    std::cin >> t;
    for (int i = 0; i < t; i++) {
        std::string type;
        int k = 0;
        std::cin >> type >> k;

        // type is "int", "double" or "string". Read the k values into
        // variables of that type, keep the largest with std::max,
        // and print it on its own line.
    }
    return 0;
}
Run in Compiler

Hint 1

A value has to be read into a variable of the right type, and the type word decides which. What happens if you read 2.5 into an int? And which one function finds the larger of two values of any type?

Hint 2

Branch on the type word with three ifs. In each branch, read the first value into a best of that type. Then read the other k - 1 into a variable of the same type and keep best = std::max(best, x).

Problem 10: line-totalsHardPro

Every evening, each branch of Amara's bakery sends one line of sales, refunds as negative numbers; a branch that sold nothing sends an empty line. Nobody says how many branches there are or how many sales are on a line. This is the biggest input in the module.

Input. One or more lines, until the end of the input, each holding zero or more integers separated by spaces. Every line ends with a newline.

Output. One line per input line with its total (0 for an empty line), then a last line: total, one space, and the total of everything.

Constraints. 1 to 20000 lines, at most 80000 integers in all, each between -1000000000 and 1000000000.

Sample. Input 120 80 -20, 45, an empty line and 7 7 7 gives 180, 45, 0, 21 and total 246.

#include <iostream>
#include <sstream>
#include <string>

int main()
{
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    // Read the input line by line until it ends. Print the total of each
    // line on its own line, then one last line: the word total, one
    // space, and the total of every number in the input.

    return 0;
}
Run in Compiler

Hint 1

while (std::cin >> x) reads every number, but it cannot tell you where a line ended, so the per-line totals are lost. Which loop of lesson 02 reads a line at a time, and which tool from its last section reads numbers back out of that line? Speed is not the problem here: the measured times above are all under 40 ms.

Hint 2

Loop on while (std::getline(std::cin, line)). Inside, make std::istringstream in(line); and add up while (in >> x) into a long long line total. Print it, add it to a grand total, and print total with the grand total after the loop.

Common doubts

  • My program passes the sample. Why does a hidden test fail?

    The sample is one small case, chosen to explain the statement. The hidden tests add the empty input where allowed, n = 1, all-equal and all-negative values, and values at both ends of their range. Zara runs those before she submits, in the Playground, with her own inputs.

  • Must I keep the two fast-input lines if no test here is slow?

    The judge cannot see them, so no rule forces you. Keep them anyway: they cost nothing. The day a test is a million numbers, as in Module 16, a program without them can miss the limit. Never mix printf or scanf into a program that has them (lesson 02).

  • Can I use using namespace std; or <bits/stdc++.h> in a judged problem?

    The judge accepts both, since it compiles with GCC. This module writes std:: and exact headers, and lesson 07 explains the trade. Whichever you choose, the output is all the judge reads.

  • Does 1 second cover only my loops, or the whole program?

    The whole program, from start to exit, reading the input included. That is why the reading habits of lesson 02 matter at large sizes, even though at this set's 1 MiB tests they are cheap.

Key takeaways

  • Every problem takes one shape: the two fast-input lines, read, compute, print exactly the Output format with '\n'.
  • With no count, loop until a read fails: while (std::cin >> x) for values, while (std::getline(...)) for lines.
  • After std::cin >> n, throw away the rest of the line before the first std::getline.
  • Multiply the largest value by the largest count: past 2147483647, the total is a long long.
  • Start a best or a smallest from the first real value, never from 0.
  • Test the empty input, n = 1, all equal and all negative before the sample.

Next comes the module test, ten questions on everything in this module. After it, Module 2 opens the first container: std::vector.

Module test

Ten questions on this module. Pass at 70%, and you can take it as many times as you like.

Take the module test

End of lesson 8

Get every problem accepted, and the lesson is done.

0 of 3 free problems accepted

Next: Module Test: Just-Enough C++