For n days, someone wrote down how much their bank balance changed each day. The first line gives n. The second line gives the n changes from day 1 to day n in order, separated by single spaces. The changes are integers, and a day on which the balance went down has a negative change. The average is the sum of all the changes divided by n, used as it is, without dropping or rounding the fractional part. Find the day for which the absolute value of (change minus average) is the smallest. If several days tie, choose among them the day with the smallest change. If several of those days also have the same change, choose the earliest of them. Print which day the chosen day is and its change, separated by a single space, on one line.
One line with the number of the chosen day (counting from day 1) and its change, separated by a single space
Example 1 · stdin
3
1 2 2
stdout
2 2
Example 2 · stdin
6
5 3 7 1 3 5
stdout
2 3
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
This problem accepts all 8 languages. Languages differ in the division used to compare with the average. The / of Python, JS, TS and Craykon is real division, so the average 1.666… of example 1 comes out as it is. In C, C++, Java and C#, dividing integers with total / n drops the fractional part. So the C, C++, Java, C# and Python solutions multiply |x − total ÷ n| by n and compare |x × n − total|, with no division at all. The JS, TS and Craykon solutions use the real average and check whether two distances are equal with ===/==, and that is also correct. For two different changes to be exactly as far from the average, the average must lie exactly between them, so it is an integer or ends in .5, and a double represents such numbers exactly. The way the choosing rules are written also differs. In Python, giving a tuple as the key, as in min(range(n), key=lambda i: (abs(a[i] * n - total), a[i], i)), compares from the first slot, so all three rules fit on one line. C++ can also compare tuples made with std::make_tuple using <. The C, Java, C#, JS, TS and Craykon solutions write the condition out, as in d < bestD || (d == bestD && a[i] < a[best]). Craykon gets the distance with Mathf.Abs. Trap one: dividing the average as integers. The average in example 1 is 1.666…, but C total / n gives 1, so day 1, at distance 0 from 1, is chosen and 1 1 is printed. Python // also gives 1 and prints the same 1 1. With negative numbers the two divisions differ. For the changes -1 -2 -2 the average is -1.666… and the answer is 2 -2. C / drops toward 0 and gives -1, so it prints the wrong 1 -1, while Python // goes down to -2 and is right by luck. For the changes -2 -1 -1 the average is -1.333… and the answer is 2 -1; this time C is right by luck, and Python // gives -2 and prints the wrong 1 -2. Trap two: in C, computing the average as a double and then writing abs(a[i] - avg). C abs takes an int, so the double is converted to int and its fractional part is dropped. In example 1 all three distances become 0, and day 1, with the smallest change, gives 1 1. For doubles use fabs from <math.h>. The judge's gcc 11 gives no warning with -Wall; only with -Wextra does it warn with -Wabsolute-value. C++ std::abs, Java Math.abs and C# Math.Abs have separate versions that take a double, so this does not happen there. Trap three: the rule for days that are equally close. The average in example 2 is 4, and the 5 on day 1 and the 3 on day 2 are both 1 away. Comparing only the distance with < keeps day 1, which came first, and prints 1 5. The smaller change, 3, must be chosen. 3 appears twice, on day 2 and day 5, and comparing the changes with <= switches to the later day 5 and prints 5 3. Comparing with < keeps the earlier day 2.
Pythonmain.py · 7 lines
n = int(input())a = list(map(int, input().split()))total = sum(a)# |x - total / n| 대신 양쪽에 n을 곱한 |x * n - total|로 견주면 정수만으로 끝난다# 튜플은 앞 칸부터 견주므로 (거리, 변화량, 날) 순서가 곧 고르는 규칙이다best = min(range(n), key=lambda i: (abs(a[i] * n - total), a[i], i))print(best + 1, a[best])
JavaScriptmain.js · 11 lines
const [n, ...a] = require("fs").readFileSync(0, "utf8").trim().split(/\s+/).map(Number);// JS의 /는 늘 실수 나눗셈이라 평균이 1.666…처럼 그대로 나온다const avg = a.reduce((s, x) => s + x, 0) / n;let best = 0;for (let i = 1; i < n; i++) { const d = Math.abs(a[i] - avg); const bestD = Math.abs(a[best] - avg); // 더 가깝거나, 똑같이 가까우면서 변화량이 더 작을 때만 바꾼다(같은 변화량이면 앞선 날이 남는다) if (d < bestD || (d === bestD && a[i] < a[best])) best = i;}console.log(`${best + 1} ${a[best]}`);
TypeScriptmain.ts · 12 lines
import { readFileSync } from "node:fs";const [n, ...a]: number[] = readFileSync(0, "utf8").trim().split(/\s+/).map(Number);// TS의 /는 늘 실수 나눗셈이라 평균이 1.666…처럼 그대로 나온다const avg: number = a.reduce((s, x) => s + x, 0) / n;let best: number = 0;for (let i = 1; i < n; i++) { const d: number = Math.abs(a[i] - avg); const bestD: number = Math.abs(a[best] - avg); // 더 가깝거나, 똑같이 가까우면서 변화량이 더 작을 때만 바꾼다(같은 변화량이면 앞선 날이 남는다) if (d < bestD || (d === bestD && a[i] < a[best])) best = i;}console.log(`${best + 1} ${a[best]}`);
JavaMain.java · 22 lines
import java.util.Scanner;public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] a = new int[n]; int total = 0; for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); total += a[i]; } // int끼리 나누면 소수점 아래가 버려지므로, 평균과의 거리에 n을 곱한 |a[i] * n - total|로 견준다 int best = 0; for (int i = 1; i < n; i++) { int d = Math.abs(a[i] * n - total); int bestD = Math.abs(a[best] * n - total); if (d < bestD || (d == bestD && a[i] < a[best])) best = i; } System.out.println((best + 1) + " " + a[best]); }}
C#Main.cs · 21 lines
using System;using System.Linq;class Program{ static void Main() { int n = int.Parse(Console.ReadLine()); int[] a = Array.ConvertAll(Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries), int.Parse); int total = a.Sum(); // int끼리 나누면 소수점 아래가 버려지므로, 평균과의 거리에 n을 곱한 |a[i] * n - total|로 견준다 int best = 0; for (int i = 1; i < n; i++) { int d = Math.Abs(a[i] * n - total); int bestD = Math.Abs(a[best] * n - total); if (d < bestD || (d == bestD && a[i] < a[best])) best = i; } Console.WriteLine($"{best + 1} {a[best]}"); }}
C++main.cpp · 21 lines
#include <cstdlib>#include <iostream>#include <numeric>#include <tuple>#include <vector>int main() { int n; std::cin >> n; std::vector<int> a(n); for (int& x : a) std::cin >> x; int total = std::accumulate(a.begin(), a.end(), 0); // int끼리 나누면 소수점 아래가 버려지므로, 평균과의 거리에 n을 곱한 |x * n - total|로 견준다 // std::tuple은 앞 칸부터 견주므로 (거리, 변화량, 날) 순서가 곧 고르는 규칙이다 auto key = [&](int i) { return std::make_tuple(std::abs(a[i] * n - total), a[i], i); }; int best = 0; for (int i = 1; i < n; i++) { if (key(i) < key(best)) best = i; } std::cout << best + 1 << " " << a[best] << "\n";}
Cmain.c · 20 lines
#include <stdio.h>#include <stdlib.h>int main(void) { int n, a[1000], total = 0; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &a[i]); total += a[i]; } /* total / n은 소수점 아래를 버리므로, 평균과의 거리에 n을 곱한 |a[i] * n - total|로 견준다 */ int best = 0; for (int i = 1; i < n; i++) { int d = abs(a[i] * n - total); int bestD = abs(a[best] * n - total); if (d < bestD || (d == bestD && a[i] < a[best])) best = i; } printf("%d %d\n", best + 1, a[best]); return 0;}
Craykonmain.cray · 21 lines
n = Console.ReadLine().ToNumber();a = Console.ReadNumbers();합 = 0;foreach (x in a){ 합 += x;}// 크레이콘의 /는 실수 나눗셈이라 평균이 1.666…처럼 그대로 나온다평균 = 합 / n;고른날 = 0;for (i = 1; i < n; i += 1){ 거리 = Mathf.Abs(a[i] - 평균); 가장가까운거리 = Mathf.Abs(a[고른날] - 평균); // 똑같이 가까우면 변화량이 더 작을 때만 바꾸고, 같은 변화량이면 앞선 날이 남는다 if (거리 < 가장가까운거리 || 거리 == 가장가까운거리 && a[i] < a[고른날]) { 고른날 = i; }}Console.WriteLine(고른날 + 1 + " " + a[고른날]);