모의 투자 대회에 참가자 n명이 있고, 1번부터 n번까지 번호가 붙어 있다. 대회는 1일에 시작했고, 참가자는 1일부터 하루도 빠짐없이 날마다 그날의 손익을 정수 하나로 적었다. 참가자는 저마다 원하는 날에 그만둘 수 있고, 그만둔 뒤로는 아무것도 적지 않는다. 그래서 참가자마다 적은 손익의 개수가 다르고, 하나도 적지 않은 참가자도 있다. i번 참가자의 기록은 입력의 i+1번째 줄에 있고, 1일의 손익부터 날짜 차례로 적혀 있다. 하나도 적지 않은 참가자의 줄은 아무 글자도 없는 빈 줄이다. 가장 오래 기록한 참가자가 적은 손익의 개수를 L이라고 하자. 첫 줄에 L을 출력하라. 이어서 1일부터 L일까지 하루에 한 줄씩, 그날 손익을 적은 참가자 수, 그 참가자들이 그날 적은 손익의 합, 그날 손익이 가장 큰 참가자의 번호를 빈칸 하나씩 띄워 출력하라. 그날 손익이 가장 큰 참가자가 여럿이면 그중 번호가 가장 작은 참가자를 출력한다. L이 0이면 첫 줄의 0 하나만 출력한다.
입력
첫 줄에 참가자 수 n이 주어진다. 이어서 n줄에 걸쳐 1번 참가자부터 차례로 한 줄에 한 참가자의 기록이 주어진다. 한 줄에는 정수가 0개 이상 100개 이하 있고, 정수가 둘 이상이면 빈칸 하나씩으로 나뉜다. 줄의 맨 앞과 맨 뒤에는 빈칸이 없다. 마지막 줄을 포함한 모든 줄은 줄 바꿈으로 끝나므로, 마지막 참가자가 하나도 적지 않았으면 입력은 빈 줄로 끝난다. 1 ≤ n ≤ 1,000, −1,000,000 ≤ 손익 ≤ 1,000,000
출력
첫 줄에 L, 이어서 L줄에 날마다 "참가자 수 합 번호". 음수는 앞에 -를 붙인다
예시 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
예시 2 · stdin
2
stdout
0
main.py
오류 목록00F8 ↓ · ⇧F8 ↑
입력(stdin)
실행하면 이 줄들이 차례로 input()·표준 입력으로 들어가요(실행 중에 묻지 않아요).
$ 준비됐어요
코드를 입력해 풀려면 PC에서 열어 주세요. 모바일에서는 문제와 풀이를 볼 수 있어요.
다른 언어로는?언어별 풀이 보기 · 8개 언어 풀이
줄 하나가 참가자 한 명이라, 수를 읽을 때 줄의 끝을 지켜야 하는 문제예요. 그래서 모든 풀이가 한 줄씩 읽어요(Python·JS·TS는 입력 전체를 split("\n"), Java readLine(), C# Console.ReadLine(), C fgets, C++ std::getline, 크레이콘 콘솔.줄읽기()). 빈 줄은 입력의 끝이 아니라 빈 문자열 ""로 읽혀요(Java·C#은 null이 아니고, 크레이콘도 빈값이 아니에요). 날마다 모을 칸은 그날을 처음 적은 참가자가 나올 때 늘리거나(Python·JS·TS·C++·크레이콘), 100칸을 미리 만들어 두고 가장 긴 기록 길이를 따로 세요(Java·C#·C). 함정 하나: C scanf("%d"), C++ std::cin >> x, Java Scanner.nextInt()는 빈칸과 줄 바꿈을 똑같이 건너뛰어요. 수 뒤의 글자를 scanf("%d%c")로 읽어 '\n'이면 줄이 끝났다고 보는 방법도 빈 줄에서 깨져요. 빈 줄을 건너뛰고 다음 참가자의 수를 읽어서 그 뒤 참가자의 번호가 하나씩 당겨지고, 예시 1의 4일이 1 4 3이 아니라 1 4 2가 돼요. 함정 둘: 빈 줄을 빈칸 하나로 나누면 빈 조각이 하나 생겨요. "".split(" ")는 Python·JS·TS·Java에서 [""], C# "".Split(' ')도 [""], 크레이콘 "".나누기(" ")도 [""]예요. 그 뒤가 언어마다 달라요. JS·TS Number("")는 오류 없이 0이라, 하나도 적지 않은 참가자가 1일에 0을 적은 것으로 세어져 예시 1의 1일이 5 5 1이 돼요. Python int("")는 ValueError, Java Integer.parseInt("")는 NumberFormatException, C# int.Parse("")는 FormatException, 크레이콘 수로변환()은 오류로 멈춰요. Python split()과 크레이콘 나누기()는 인자 없이 부르면 빈 줄에서 빈 목록을 주고, C#은 StringSplitOptions.RemoveEmptyEntries를 붙이면 돼요. Java와 JS·TS 풀이는 빈 줄인지 먼저 보고 따로 다뤄요. C strtok과 C++ std::istringstream의 >>는 빈 줄에서 수를 하나도 내놓지 않아요. 함정 셋: 입력 전체를 읽는 JS·TS 풀이에서 습관처럼 trim()을 먼저 하면 맨 뒤의 빈 줄, 곧 마지막에 하나도 적지 않은 참가자의 줄이 사라져요. 예시 1처럼 마지막 참가자가 빈 줄이면 lines[n]이 undefined가 되어 .split에서 TypeError로 멈춰요. 참가자 수 n을 알고 있으니 줄은 n개만 읽고, trim()은 하지 않아요. 함정 넷: 가장 큰 손익을 0에서 출발해 찾으면, 그날 손익이 모두 음수일 때 아무도 0보다 크지 않아서 번호 대신 0이 나와요. 예시 1의 2일(-2, -7)이 2 -9 1이 아니라 2 -9 0이 돼요. 그날을 처음 적은 참가자의 값으로 시작해요. 함정 다섯: 비교에 >=를 쓰면 같은 값일 때 뒤 번호로 바뀌어요. 예시 1의 1일(3과 3)과 3일(5와 5)이 1번 대신 4번과 3번이 돼요. >로 비교해요. 합은 많아야 1,000 × 1,000,000 = 10억이라 모든 언어의 32비트 정수에 들어가요.
Pythonmain.py · 31 줄
import sysdef 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 줄
// 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 줄
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 줄
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 줄
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 줄
#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 줄
#include <stdio.h>#include <stdlib.h>#include <string.h>#define MAX_DAYS 100int 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 줄
n = 콘솔.줄읽기().수로변환();count = [];total = [];bestValue = [];bestWho = [];반복 (who = 1; who <= n; who++){ 줄 = 콘솔.줄읽기(); // 빈 줄은 빈값이 아니라 "" // 인자 없는 나누기()는 빈 줄에서 빈 목록을 준다(나누기(" ")는 [""]를 준다) values = 줄.나누기(); 반복 (d = 0; d < values.개수; d++) { v = values[d].수로변환(); 만약 (d == count.개수) { count.넣기(0); total.넣기(0); bestValue.넣기(v); bestWho.넣기(who); } count[d] += 1; total[d] += v; 만약 (v > bestValue[d]) { bestValue[d] = v; bestWho[d] = who; } }}콘솔.쓰기(count.개수);반복 (d = 0; d < count.개수; d++){ 콘솔.쓰기(count[d] + " " + total[d] + " " + bestWho[d]);}