Write a function score(difficulty, drop, judge scores) that gives the score of a gymnastics routine.
The difficulty d and the drop count k are always given, and after them it takes any number of judge scores.
The function drops the k lowest and the k highest of the judge scores it received, and returns the sum of the remaining scores multiplied by d.
Even when several scores are equal, only k are dropped from the low side and k from the high side.
If no scores remain, the sum is 0.
The function is called twice for each routine.
The official score passes the scores of all judges: score(d, k, s1, s2, …, sm).
The head score passes only the scores of the first two judges on the line (the head judges) and drops nothing: score(d, 0, s1, s2).
The first line gives the number of routines q.
Each of the next q lines gives, for one routine, d, k and then the judge scores s1, s2, …, sm separated by single spaces. The number of judges m may differ from line to line and is not given separately.
For each routine print the official score and the head score in this order on one line, separated by a single space.
Only the output is judged, so how the function is written is not checked. Still, try to solve it by writing one function with a parameter that takes any number of values (in languages without that syntax, one list or array) and calling it twice.
Input
1 ≤ q ≤ 1,000. 1 ≤ d ≤ 10. 2 ≤ m ≤ 100. 0 ≤ k and 2 × k ≤ m. 0 ≤ judge score ≤ 100 (all integers)
Output
q lines, each with the official score and the head score
Example 1 · stdin
3
3 1 9 7 8 10
2 0 5 6 7
1 1 4 100
stdout
51 48
36 22
0 104
main.py
Error List00F8 ↓ · ⇧F8 ↑
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
How you write a parameter that takes any number of values differs by language: Python def score(d, k, *scores), JS function score(d, k, ...scores), TS ...scores: number[], Java static long score(int d, int k, int... scores), C# static long Score(int d, int k, params int[] scores); a function can have only one such parameter. In JS, TS, Java and C# it must be the last parameter, while Python lets you write more parameters after *scores, but those can only be given by name (trap 3). C's ... (stdarg.h) cannot tell how many values it received and cannot take an array spread into it, so C takes an array and a count as in (const int *scores, int m); C++ takes a std::vector<int> and is called with braces, score(d, 0, {s[0], s[1]}). Craykon has no such syntax, so the function takes one list and is called as score(d, 0, [s[0], s[1]]). The calling side differs too. Python score(*nums) and JS score(...nums) spread a list so that the first two go to d and k and the rest to scores. TS rejects score(...nums) (TS2556: it cannot know how many spread values land on d and k). So spread only into the rest parameter: score(d, k, ...nums.slice(2)). Java and C# simply pass the array. Trap 1: whether the function gets a copy depends on the language. Python's *scores is a new tuple and JS/TS ...scores is a new array, so sorting inside the function leaves the caller's data alone. But when you pass an array to Java int... or C# params, nothing is copied and the function gets that very array. A Craykon list behaves the same way. Sorting it directly inside the function reorders the caller's array, so the head score read afterward from s[0] and s[1] uses the two lowest scores (the 48 on the first example line becomes 45). Sort a copy: scores.clone(), (int[])scores.Clone(), Craykon scores.GetRange(0, scores.Count). In C++ a vector taken by value is a copy. Trap 2: Python's *scores is a tuple, which has no scores.sort() (AttributeError). Use sorted(scores). Trap 3: in Python, a parameter written after *scores, as in def score(d, *scores, k=0), can only be given by name. A k passed by position ends up among the judge scores. Trap 4: writing the kept range as Python ordered[k:-k] gives [0:0], an empty list, when k is 0. Write ordered[k:len(ordered) - k]. Trap 5: JS/TS sort() without a compare function sorts even numbers in string order, so 10 comes before 9 and 100 before 20. Write sort((a, b) => a - b).
Pythonmain.py · 20 lines
import sysdef score(d, k, *scores): """난도 d와 버림 k는 꼭 받고, 심사 점수는 몇 개든 받는다(scores는 튜플).""" ordered = sorted(scores) # 튜플은 고칠 수 없으니 정렬한 새 목록을 만든다 kept = ordered[k:len(ordered) - k] # [k:-k]는 k가 0일 때 빈 목록이 된다 return d * sum(kept)lines = sys.stdin.read().split("\n")q = int(lines[0])out = []for i in range(1, q + 1): nums = list(map(int, lines[i].split())) d, k = nums[0], nums[1] official = score(*nums) # 목록을 펼쳐 넘긴다: 앞의 둘은 d와 k로, 나머지는 scores로 head = score(d, 0, nums[2], nums[3]) # 주심 두 명만 따로 넘긴다 out.append(f"{official} {head}")print("\n".join(out))
JavaScriptmain.js · 19 lines
// 난도 d와 버림 k는 꼭 받고, 심사 점수는 몇 개든 받는다(...scores는 새 배열)function score(d, k, ...scores) { scores.sort((a, b) => a - b); // 비교 함수가 없으면 문자열 순서로 정렬된다 let sum = 0; for (let i = k; i < scores.length - k; i++) sum += scores[i]; return d * sum;}const lines = require("fs").readFileSync(0, "utf8").split("\n");const q = Number(lines[0]);const out = [];for (let i = 1; i <= q; i++) { const nums = lines[i].trim().split(/\s+/).map(Number); const [d, k] = nums; const official = score(...nums); // 배열을 펼쳐 넘긴다: 값이 복사되므로 nums는 그대로다 const head = score(d, 0, nums[2], nums[3]); // 주심 두 명만 따로 넘긴다 out.push(official + " " + head);}console.log(out.join("\n"));
TypeScriptmain.ts · 22 lines
import { readFileSync } from "node:fs";// 난도 d와 버림 k는 꼭 받고, 심사 점수는 몇 개든 받는다(...scores는 새 배열)function score(d: number, k: number, ...scores: number[]): number { scores.sort((a, b) => a - b); // 비교 함수가 없으면 문자열 순서로 정렬된다 let sum = 0; for (let i = k; i < scores.length - k; i++) sum += scores[i]; return d * sum;}const lines: string[] = readFileSync(0, "utf8").split("\n");const q: number = Number(lines[0]);const out: string[] = [];for (let i = 1; i <= q; i++) { const nums: number[] = lines[i].trim().split(/\s+/).map(Number); const [d, k] = nums; // score(...nums)는 d와 k 자리에 몇 개가 들어갈지 몰라 TS가 막는다: 나머지 매개변수 자리만 펼친다 const official: number = score(d, k, ...nums.slice(2)); const head: number = score(d, 0, nums[2], nums[3]); // 주심 두 명만 따로 넘긴다 out.push(official + " " + head);}console.log(out.join("\n"));
JavaMain.java · 32 lines
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.Arrays;public class Main { // 난도 d와 버림 k는 꼭 받고, 심사 점수는 몇 개든 받는다(int...은 맨 뒤에만 쓸 수 있다) static long score(int d, int k, int... scores) { // 배열을 그대로 넘겨받으면 부른 쪽 배열과 같은 것이다: 복사본을 정렬한다 int[] ordered = scores.clone(); Arrays.sort(ordered); long sum = 0; for (int i = k; i < ordered.length - k; i++) sum += ordered[i]; return d * sum; } public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int q = Integer.parseInt(in.readLine().trim()); StringBuilder out = new StringBuilder(); for (int line = 0; line < q; line++) { String[] parts = in.readLine().trim().split("\\s+"); int d = Integer.parseInt(parts[0]), k = Integer.parseInt(parts[1]); int[] s = new int[parts.length - 2]; for (int i = 0; i < s.length; i++) s[i] = Integer.parseInt(parts[i + 2]); long official = score(d, k, s); // 배열을 통째로 넘긴다 long head = score(d, 0, s[0], s[1]); // 주심 두 명만 따로 넘긴다 out.append(official).append(' ').append(head).append('\n'); } System.out.print(out); }}
C#Main.cs · 33 lines
using System;using System.Text;class Program{ // 난도 d와 버림 k는 꼭 받고, 심사 점수는 몇 개든 받는다(params는 맨 뒤에만 쓸 수 있다) static long Score(int d, int k, params int[] scores) { // 배열을 그대로 넘겨받으면 부른 쪽 배열과 같은 것이다: 복사본을 정렬한다 int[] ordered = (int[])scores.Clone(); Array.Sort(ordered); long sum = 0; for (int i = k; i < ordered.Length - k; i++) sum += ordered[i]; return d * sum; } static void Main() { int q = int.Parse(Console.ReadLine()); var sb = new StringBuilder(); for (int line = 0; line < q; line++) { string[] parts = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries); int d = int.Parse(parts[0]), k = int.Parse(parts[1]); int[] s = new int[parts.Length - 2]; for (int i = 0; i < s.Length; i++) s[i] = int.Parse(parts[i + 2]); long official = Score(d, k, s); // 배열을 통째로 넘긴다 long head = Score(d, 0, s[0], s[1]); // 주심 두 명만 따로 넘긴다 sb.Append(official).Append(' ').Append(head).Append('\n'); } Console.Write(sb); }}
C++main.cpp · 30 lines
#include <algorithm>#include <iostream>#include <sstream>#include <string>#include <vector>// 심사 점수는 vector로 받는다. 값으로 받으면 복사본이라 마음대로 정렬해도 된다static long long score(int d, int k, std::vector<int> scores) { std::sort(scores.begin(), scores.end()); long long sum = 0; for (int i = k; i < static_cast<int>(scores.size()) - k; i++) sum += scores[i]; return d * sum;}int main() { std::string line; std::getline(std::cin, line); int q = std::stoi(line); for (int t = 0; t < q; t++) { std::getline(std::cin, line); std::istringstream in(line); int d, k, x; in >> d >> k; std::vector<int> s; while (in >> x) s.push_back(x); long long official = score(d, k, s); long long head = score(d, 0, {s[0], s[1]}); // 주심 두 명만 중괄호로 묶어 넘긴다 std::cout << official << ' ' << head << '\n'; }}
Cmain.c · 41 lines
#include <stdio.h>#include <stdlib.h>#include <string.h>#define MAXM 100static int by_value(const void *a, const void *b) { return *(const int *)a - *(const int *)b;}/* C의 ...(stdarg.h)는 개수를 알 수 없고 배열을 펼쳐 넘길 수도 없다: 배열과 개수를 함께 받는다 */static long long score(int d, int k, const int *scores, int m) { int ordered[MAXM]; memcpy(ordered, scores, (size_t)m * sizeof(int)); /* 부른 쪽 배열은 그대로 둔다 */ qsort(ordered, (size_t)m, sizeof(int), by_value); long long sum = 0; for (int i = k; i < m - k; i++) sum += ordered[i]; return d * sum;}int main(void) { int q; static char line[1024]; scanf("%d ", &q); for (int t = 0; t < q; t++) { if (!fgets(line, sizeof line, stdin)) break; int d, k, used = 0, m = 0, s[MAXM]; char *p = line; sscanf(p, "%d %d%n", &d, &k, &used); p += used; while (m < MAXM && sscanf(p, "%d%n", &s[m], &used) == 1) { p += used; m++; } long long official = score(d, k, s, m); int heads[2] = {s[0], s[1]}; /* 주심 두 명만 따로 넘긴다 */ long long head = score(d, 0, heads, 2); printf("%lld %lld\n", official, head); } return 0;}
Craykonmain.cray · 26 lines
// 크레이콘에는 '몇 개든 받는 매개변수'가 없다 — 심사 점수를 목록 하나로 받는다점수(d, k, scores){ // 받은 목록은 부른 쪽 목록과 같은 것이다: 복사본을 정렬한다 ordered = scores.GetRange(0, scores.Count); ordered.Sort(); sum = 0; for (i = k; i < ordered.Count - k; i++) { sum += ordered[i]; } return d * sum;}q = Console.ReadLine().ToNumber();for (t = 0; t < q; t++){ nums = Console.ReadNumbers(); d = nums[0]; k = nums[1]; s = nums.GetRange(2, nums.Count - 2); official = 점수(d, k, s); // 주심 두 명만 새 목록으로 묶어 넘긴다 head = 점수(d, 0, [s[0], s[1]]); Console.WriteLine(official + " " + head);}