{ }codelper
reading numbersreading n linesP0427

Paper-trading logs that stop on different days

A paper-trading contest has n participants, numbered 1 to n.
The contest started on day 1, and from day 1 on, without skipping a day, each participant wrote that day's profit or loss as one integer.
Each participant may quit on any day they like, and after quitting they write nothing more.
So participants wrote different numbers of values, and some participants wrote nothing at all.
The record of participant i is on line i+1 of the input, starting with the value of day 1 and following the order of days.
The line of a participant who wrote nothing is an empty line with no characters.
Let L be the number of values written by the participant who kept records the longest.
Print L on the first line.
Then, one line per day from day 1 to day L, print the number of participants who wrote a value that day, the sum of the values they wrote that day, and the number of the participant whose value that day is the largest, separated by single spaces.
If several participants share the largest value that day, print the smallest number among them.
If L is 0, print only the 0 on the first line.

Input
The first line holds the number of participants n.
The next n lines hold one participant's record each, starting with participant 1.
A line holds between 0 and 100 integers, and two or more integers are separated by single spaces.
There is no space at the very start or end of a line.
Every line, including the last one, ends with a line break, so if the last participant wrote nothing the input ends with an empty line.
1 ≤ n ≤ 1,000, −1,000,000 ≤ value ≤ 1,000,000
Output
L on the first line, then L lines "participants sum number", one per day.
Negative numbers start with -
Example 1 · stdin
5
3 -2 5

-1 -7 5 4
3

stdout
4
3 5 1
2 -9 1
2 10 1
1 4 3
Example 2 · stdin
2


stdout
0
main.py
Input (stdin)

When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).

$ Ready

Open this on a computer to write and run code. On mobile you can read the problem and the solutions.

In other languagesShow solutions by language · 8 languages

Each line is one participant, so while reading numbers you must keep track of where a line ends.
So every solution reads one line at a time (Python/JS/TS split the whole input with split("\n"), Java readLine(), C# Console.ReadLine(), C fgets, C++ std::getline, Craykon Console.ReadLine()).
An empty line is not the end of input; it is read as the empty string "" (not null in Java and C#, and not null in Craykon either).
The per-day slots are either grown when the first participant reaches that day (Python/JS/TS/C++/Craykon), or 100 slots are made in advance and the longest record length is counted separately (Java/C#/C).
Trap one: C scanf("%d"), C++ std::cin >> x and Java Scanner.nextInt() skip spaces and line breaks alike.
Reading the character after each number with scanf("%d%c") and treating '\n' as the end of the line also breaks on empty lines.
It skips the empty line and reads the next participant's numbers, so every later participant's number shifts up by one, and day 4 of example 1 becomes 1 4 2 instead of 1 4 3.
Trap two: splitting an empty line at single spaces gives one empty piece.
"".split(" ") is [""] in Python, JS/TS and Java, C# "".Split(' ') is [""] too, and so is Craykon "".Split(" ").
What happens next differs.
JS/TS Number("") is 0 without any error, so a participant who wrote nothing is counted as writing 0 on day 1, and day 1 of example 1 becomes 5 5 1.
Python int("") raises ValueError, Java Integer.parseInt("") throws NumberFormatException, C# int.Parse("") throws FormatException, and Craykon ToNumber() stops with an error.
Python split() and Craykon Split() called without an argument give an empty list for an empty line, and in C# adding StringSplitOptions.RemoveEmptyEntries is enough.
The Java and JS/TS solutions check for an empty line first and handle it separately.
C strtok and >> on a C++ std::istringstream produce no numbers from an empty line.
Trap three: in a JS/TS solution that reads the whole input, calling trim() first out of habit removes the empty lines at the very end, that is, the lines of the last participants who wrote nothing.
When the last participant's line is empty, as in example 1, lines[n] is undefined and .split stops with a TypeError.
Since you know n, read exactly n lines and do not trim().
Trap four: if you search for the largest value starting from 0, then on a day where all values are negative nobody beats 0, and 0 is printed instead of a participant number.
Day 2 of example 1 (-2, -7) becomes 2 -9 0 instead of 2 -9 1.
Start from the value of the first participant who wrote that day.
Trap five: comparing with >= switches to the later number on a tie.
Day 1 (3 and 3) and day 3 (5 and 5) of example 1 give 4 and 3 instead of 1.
Compare with >.
A sum is at most 1,000 × 1,000,000 = one billion, which fits a 32-bit integer in every language.

Pythonmain.py · 31 lines
import sys  def main():    lines = sys.stdin.read().split("\n")  # 빈 줄도 한 줄로 남는다    n = int(lines[0])    count = []  # count[d]: d+1일에 손익을 적은 참가자 수    total = []    best_value = []    best_who = []    for who in range(1, n + 1):        # 인자 없는 split()은 빈 줄에서 빈 목록 []을 준다(split(" ")은 [""]를 준다)        values = [int(t) for t in lines[who].split()]        for d, v in enumerate(values):            if d == len(count):  # 이 날을 처음 적은 사람                count.append(0)                total.append(0)                best_value.append(v)                best_who.append(who)            count[d] += 1            total[d] += v            if v > best_value[d]:  # 같으면 앞 번호가 남는다                best_value[d] = v                best_who[d] = who    out = [str(len(count))]    for d in range(len(count)):        out.append(f"{count[d]} {total[d]} {best_who[d]}")    print("\n".join(out))  main()
JavaScriptmain.js · 29 lines
// trim()을 하면 맨 뒤의 빈 줄(하나도 적지 않은 참가자)까지 사라지므로 하지 않는다const lines = require("fs").readFileSync(0, "utf8").split("\n");const n = Number(lines[0]);const count = [];const total = [];const bestValue = [];const bestWho = [];for (let who = 1; who <= n; who++) {  const line = lines[who];  // "".split(" ")은 [""]이고 Number("")은 0이다. 빈 줄은 따로 빈 목록으로 둔다  const values = line === "" ? [] : line.split(" ").map(Number);  values.forEach((v, d) => {    if (d === count.length) {      count.push(0);      total.push(0);      bestValue.push(v);      bestWho.push(who);    }    count[d]++;    total[d] += v;    if (v > bestValue[d]) {      bestValue[d] = v;      bestWho[d] = who;    }  });}const out = [String(count.length)];for (let d = 0; d < count.length; d++) out.push(`${count[d]} ${total[d]} ${bestWho[d]}`);console.log(out.join("\n"));
TypeScriptmain.ts · 30 lines
import { readFileSync } from "node:fs";// trim()을 하면 맨 뒤의 빈 줄(하나도 적지 않은 참가자)까지 사라지므로 하지 않는다const lines: string[] = readFileSync(0, "utf8").split("\n");const n = Number(lines[0]);const count: number[] = [];const total: number[] = [];const bestValue: number[] = [];const bestWho: number[] = [];for (let who = 1; who <= n; who++) {  const line = lines[who];  // "".split(" ")은 [""]이고 Number("")은 0이다. 빈 줄은 따로 빈 목록으로 둔다  const values: number[] = line === "" ? [] : line.split(" ").map(Number);  values.forEach((v, d) => {    if (d === count.length) {      count.push(0);      total.push(0);      bestValue.push(v);      bestWho.push(who);    }    count[d]++;    total[d] += v;    if (v > bestValue[d]) {      bestValue[d] = v;      bestWho[d] = who;    }  });}const out: string[] = [String(count.length)];for (let d = 0; d < count.length; d++) out.push(`${count[d]} ${total[d]} ${bestWho[d]}`);console.log(out.join("\n"));
JavaMain.java · 37 lines
import java.io.BufferedReader;import java.io.InputStreamReader; public class Main {    public static void main(String[] args) throws Exception {        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));        int n = Integer.parseInt(in.readLine().trim());        final int MAX_DAYS = 100;        int[] count = new int[MAX_DAYS];        int[] total = new int[MAX_DAYS]; // 합은 많아야 10억이라 int로 된다        int[] bestValue = new int[MAX_DAYS];        int[] bestWho = new int[MAX_DAYS];        int days = 0;        for (int who = 1; who <= n; who++) {            String line = in.readLine(); // 빈 줄은 null이 아니라 ""            // "".split(" ")은 [""]이라 parseInt("")에서 멈춘다. 빈 줄은 건너뛴다            if (line.isEmpty()) continue;            String[] parts = line.split(" ");            for (int d = 0; d < parts.length; d++) {                int v = Integer.parseInt(parts[d]);                if (count[d] == 0 || v > bestValue[d]) { // 첫 사람이거나 더 클 때만 바꾼다                    bestValue[d] = v;                    bestWho[d] = who;                }                count[d]++;                total[d] += v;            }            days = Math.max(days, parts.length);        }        StringBuilder out = new StringBuilder();        out.append(days).append('\n');        for (int d = 0; d < days; d++) {            out.append(count[d]).append(' ').append(total[d]).append(' ').append(bestWho[d]).append('\n');        }        System.out.print(out);    }}
C#Main.cs · 41 lines
using System;using System.Text; class Program{    static void Main()    {        int n = int.Parse(Console.ReadLine()!);        const int MaxDays = 100;        int[] count = new int[MaxDays];        int[] total = new int[MaxDays]; // 합은 많아야 10억이라 int로 된다        int[] bestValue = new int[MaxDays];        int[] bestWho = new int[MaxDays];        int days = 0;        for (int who = 1; who <= n; who++)        {            string line = Console.ReadLine()!; // 빈 줄은 null이 아니라 ""            // "".Split(' ')은 [""]이라 int.Parse("")에서 멈춘다. 빈 조각을 버리게 한다            string[] parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);            for (int d = 0; d < parts.Length; d++)            {                int v = int.Parse(parts[d]);                if (count[d] == 0 || v > bestValue[d]) // 첫 사람이거나 더 클 때만 바꾼다                {                    bestValue[d] = v;                    bestWho[d] = who;                }                count[d]++;                total[d] += v;            }            days = Math.Max(days, parts.Length);        }        var output = new StringBuilder();        output.Append(days).Append('\n');        for (int d = 0; d < days; d++)        {            output.Append(count[d]).Append(' ').Append(total[d]).Append(' ').Append(bestWho[d]).Append('\n');        }        Console.Write(output);    }}
C++main.cpp · 36 lines
#include <iostream>#include <sstream>#include <string>#include <vector> int main() {    std::ios::sync_with_stdio(false);    std::string line;    std::getline(std::cin, line);    int n = std::stoi(line);    std::vector<int> count, total, bestValue, bestWho;    for (int who = 1; who <= n; who++) {        // std::cin >> x는 줄 바꿈도 건너뛰어 빈 줄(참가자 하나)이 사라진다. 한 줄씩 읽는다        std::getline(std::cin, line);        std::istringstream row(line);        int v;        for (std::size_t d = 0; row >> v; d++) {            if (d == count.size()) { // 이 날을 처음 적은 사람                count.push_back(0);                total.push_back(0);                bestValue.push_back(v);                bestWho.push_back(who);            }            count[d]++;            total[d] += v;            if (v > bestValue[d]) { // 같으면 앞 번호가 남는다                bestValue[d] = v;                bestWho[d] = who;            }        }    }    std::cout << count.size() << '\n';    for (std::size_t d = 0; d < count.size(); d++)        std::cout << count[d] << ' ' << total[d] << ' ' << bestWho[d] << '\n';    return 0;}
Cmain.c · 32 lines
#include <stdio.h>#include <stdlib.h>#include <string.h> #define MAX_DAYS 100 int main(void) {    char line[1100]; /* 한 줄은 1,000글자 이하 */    int count[MAX_DAYS] = {0}, total[MAX_DAYS] = {0};    int best_value[MAX_DAYS] = {0}, best_who[MAX_DAYS] = {0};    int n, days = 0;    if (!fgets(line, sizeof line, stdin)) return 0;    n = atoi(line);    /* scanf("%d")는 줄 바꿈도 건너뛰어 빈 줄(참가자 하나)이 사라진다. 한 줄씩 읽는다 */    for (int who = 1; who <= n; who++) {        if (!fgets(line, sizeof line, stdin)) break;        int d = 0;        for (char *tok = strtok(line, " \r\n"); tok; tok = strtok(NULL, " \r\n"), d++) {            int v = (int)strtol(tok, NULL, 10);            if (count[d] == 0 || v > best_value[d]) { /* 첫 사람이거나 더 클 때만 바꾼다 */                best_value[d] = v;                best_who[d] = who;            }            count[d]++;            total[d] += v;        }        if (d > days) days = d;    }    printf("%d\n", days);    for (int d = 0; d < days; d++) printf("%d %d %d\n", count[d], total[d], best_who[d]);    return 0;}
Craykonmain.cray · 34 lines
n = Console.ReadLine().ToNumber();count = [];total = [];bestValue = [];bestWho = [];for (who = 1; who <= n; who++){    줄 = Console.ReadLine(); // 빈 줄은 빈값이 아니라 ""    // 인자 없는 나누기()는 빈 줄에서 빈 목록을 준다(나누기(" ")는 [""]를 준다)    values = 줄.Split();    for (d = 0; d < values.Count; d++)    {        v = values[d].ToNumber();        if (d == count.Count)        {            count.Add(0);            total.Add(0);            bestValue.Add(v);            bestWho.Add(who);        }        count[d] += 1;        total[d] += v;        if (v > bestValue[d])        {            bestValue[d] = v;            bestWho[d] = who;        }    }}Console.WriteLine(count.Count);for (d = 0; d < count.Count; d++){    Console.WriteLine(count[d] + " " + total[d] + " " + bestWho[d]);}