{ }codelper
reading numbers64-bit integersP0231

Scale log that wraps anywhere

A warehouse scale printed the weights of the items in each box on a paper tape. The tape is narrow, so after any number it may continue on the next line. There may be one or more spaces between numbers, spaces at the start or end of a line, and blank lines in between. A single number is never split across two lines. Read from the start of the whole input, the integers mean the following. The very first number is the number of boxes k. Then, for box 1, box 2 and so on in order, each box gives its item count m followed by the m weights of its items. If m is 0 the box is empty and no weights follow for it. For each box print the sum of its weights on its own line (0 for an empty box). On the last line print the number of the box with the largest sum. If several boxes share the largest sum, print the smallest of their numbers.

Input
1 ≤ k ≤ 1,000, 0 ≤ m ≤ 10,000, the m of all boxes add up to at most 20,000, 1 ≤ weight ≤ 1,000,000,000 (all integers), at most 100 numbers per line
Output
k lines: the weight sum of each box / last line: the number of the box with the largest sum
Example 1 · stdin
3 2 500
 700
0

4 100 200
   300 400
stdout
1200
0
1000
1
Example 2 · stdin
2
1
800
2 300
500
stdout
800
800
1
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

The heart of this problem is reading the input as a stream of numbers, not as lines.
C scanf("%d"), C++ std::cin >> and Java Scanner.nextInt() skip every space and newline before a number and read the next one, so it doesn't matter where the lines break.
By contrast, Python input(), C# Console.ReadLine(), Java BufferedReader.readLine() and Craykon Console.ReadLine()/Console.ReadNumbers() read one line at a time.
If you assume each box sits on one line and handle one box per line, you get it wrong.
So Python uses sys.stdin.read().split(), JS/TS readFileSync(0, "utf8").trim().split(/\s+/) and C# Console.In.ReadToEnd().Split(..., StringSplitOptions.RemoveEmptyEntries) to split the whole input at once.
For fast reading in Java, keep a small function that reads the next line when the StringTokenizer is empty.
Craykon takes the pieces of each line with line.Split() and keeps in a variable whether it is waiting for the box count, an item count or a weight.
The separator is a trap too.
JS split(" ") treats only a single space as a separator, so pieces such as "3\n2" or "" appear and Number turns them into NaN or 0.
In C#, leaving out RemoveEmptyEntries produces "" where spaces repeat and on blank lines, and int.Parse throws FormatException.
Python split() and Craykon Split() without a separator treat any run of spaces as one and drop empty pieces (writing split(" ") in Python does produce empty pieces).
The weight sum reaches 10^13, beyond a 32-bit int, so Java and C# need long and C and C++ long long.
Numbers in JS, TS and Craykon are exact integers up to 2^53, and Python integers have no size limit.
Update the heaviest box with >, not >=, so the earlier number stays on a tie.

Pythonmain.py · 13 lines
import sys # 줄과 상관없이 입력 전체를 빈칸·줄바꿈으로 나눈 수의 흐름으로 읽는다nums = iter(map(int, sys.stdin.read().split()))k = next(nums)best, best_total = 1, -1for box in range(1, k + 1):    m = next(nums)    total = sum(next(nums) for _ in range(m))    print(total)    if total > best_total:  # 같으면 앞의 상자를 그대로 둔다        best, best_total = box, totalprint(best)
JavaScriptmain.js · 19 lines
// 앞뒤 빈칸을 없앤 뒤 /\s+/로 나누면 여러 빈칸·줄바꿈·빈 줄이 모두 하나의 구분이 된다const nums = require("fs").readFileSync(0, "utf8").trim().split(/\s+/).map(Number);let at = 0;const k = nums[at++];const out = [];let best = 1;let bestTotal = -1;for (let box = 1; box <= k; box++) {  const m = nums[at++];  let total = 0; // 최대 10^13: 2^53 안이라 정확하다  for (let i = 0; i < m; i++) total += nums[at++];  out.push(total);  if (total > bestTotal) {    best = box;    bestTotal = total;  }}out.push(best);console.log(out.join("\n"));
TypeScriptmain.ts · 21 lines
import { readFileSync } from "node:fs";// 앞뒤 빈칸을 없앤 뒤 /\s+/로 나누면 여러 빈칸·줄바꿈·빈 줄이 모두 하나의 구분이 된다const nums: number[] = readFileSync(0, "utf8").trim().split(/\s+/).map(Number);let at = 0;const next = (): number => nums[at++];const k = next();const out: number[] = [];let best = 1;let bestTotal = -1;for (let box = 1; box <= k; box++) {  const m = next();  let total = 0; // 최대 10^13: 2^53 안이라 정확하다  for (let i = 0; i < m; i++) total += next();  out.push(total);  if (total > bestTotal) {    best = box;    bestTotal = total;  }}out.push(best);console.log(out.join("\n"));
JavaMain.java · 34 lines
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.StringTokenizer; public class Main {    static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));    static StringTokenizer tok = new StringTokenizer("");     // 지금 줄의 수를 다 쓰면 다음 줄을 읽는다: 줄이 어디서 바뀌든 수만 차례로 나온다    static long next() throws IOException {        while (!tok.hasMoreTokens()) tok = new StringTokenizer(in.readLine());        return Long.parseLong(tok.nextToken());    }     public static void main(String[] args) throws IOException {        int k = (int) next();        StringBuilder out = new StringBuilder();        int best = 1;        long bestTotal = -1;        for (int box = 1; box <= k; box++) {            long m = next();            long total = 0; // 최대 10^13: int로는 넘친다            for (long i = 0; i < m; i++) total += next();            out.append(total).append('\n');            if (total > bestTotal) {                best = box;                bestTotal = total;            }        }        out.append(best).append('\n');        System.out.print(out);    }}
C#Main.cs · 30 lines
using System;using System.Text; class Program{    static void Main()    {        // 입력 전체를 읽고 빈칸·줄바꿈으로 나눈다. 빈 조각(빈칸이 겹친 곳, 빈 줄)은 버린다        string[] nums = Console.In.ReadToEnd().Split(new[] { ' ', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);        int at = 0;        int k = int.Parse(nums[at++]);        var out_ = new StringBuilder();        int best = 1;        long bestTotal = -1;        for (int box = 1; box <= k; box++)        {            int m = int.Parse(nums[at++]);            long total = 0; // 최대 10^13: int로는 넘친다            for (int i = 0; i < m; i++) total += long.Parse(nums[at++]);            out_.Append(total).Append('\n');            if (total > bestTotal)            {                best = box;                bestTotal = total;            }        }        out_.Append(best).Append('\n');        Console.Write(out_);    }}
C++main.cpp · 27 lines
#include <iostream> int main() {    std::ios::sync_with_stdio(false);    std::cin.tie(nullptr);    // >>는 빈칸·줄바꿈을 모두 건너뛰고 다음 수를 읽는다    int k;    std::cin >> k;    int best = 1;    long long bestTotal = -1;    for (int box = 1; box <= k; box++) {        int m;        std::cin >> m;        long long total = 0; // 최대 10^13: int로는 넘친다        for (int i = 0; i < m; i++) {            long long w;            std::cin >> w;            total += w;        }        std::cout << total << '\n';        if (total > bestTotal) {            best = box;            bestTotal = total;        }    }    std::cout << best << '\n';}
Cmain.c · 26 lines
#include <stdio.h> int main(void) {    /* scanf("%d")는 수 앞의 빈칸·줄바꿈을 모두 건너뛴다: 줄이 어디서 바뀌든 상관없다 */    int k;    scanf("%d", &k);    int best = 1;    long long best_total = -1;    for (int box = 1; box <= k; box++) {        int m;        scanf("%d", &m);        long long total = 0; /* 최대 10^13: int로는 넘친다 */        for (int i = 0; i < m; i++) {            long long w;            scanf("%lld", &w);            total += w;        }        printf("%lld\n", total);        if (total > best_total) {            best = box;            best_total = total;        }    }    printf("%d\n", best);    return 0;}
Craykonmain.cray · 44 lines
// 줄마다 수의 개수가 제각각이다. 줄을 읽어 수를 하나씩 꺼내며// "지금 무엇을 기다리는지"(상자 수 → 물건 수 → 무게)를 따라간다k = -1; // 아직 상자 수를 읽지 않았다box = 0; // 지금 상자 번호left = -1; // 이 상자에 남은 무게 수(-1이면 물건 수를 기다린다)total = 0;best = 1;bestTotal = -1;줄 = Console.ReadLine();while (줄 != null){    foreach (조각 in 줄.Split())    {        x = 조각.ToNumber();        if (k == -1)        {            k = x;        }        else if (left == -1)        {            box++;            left = x;            total = 0;        }        else        {            total += x;            left--;        }        // 무게를 다 읽었으면(빈 상자는 바로) 상자 하나가 끝난다        if (left == 0)        {            Console.WriteLine(total);            if (total > bestTotal)            {                best = box;                bestTotal = total;            }            left = -1;        }    }    줄 = Console.ReadLine();}Console.WriteLine(best);