AtCoderのABC
次のABCの問題へ
前のABCの問題へ
ABC194-C Squared Error
C#のソース
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static string InputPattern = "InputX";
static List<string> GetInputList()
{
var WillReturn = new List<string>();
if (InputPattern == "Input1") {
WillReturn.Add("3");
WillReturn.Add("2 8 4");
//56
}
else if (InputPattern == "Input2") {
WillReturn.Add("5");
WillReturn.Add("-5 8 9 -4 -3");
//950
}
else {
string wkStr;
while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
}
return WillReturn;
}
static void Main()
{
List<string> InputList = GetInputList();
long[] AArr = InputList[1].Split(' ').Select(pX => long.Parse(pX)).ToArray();
int N = AArr.Length;
long SumVal = AArr.Sum();
long Answer = 0;
foreach (long EachLong in AArr) {
Answer += EachLong * EachLong * (N - 1);
SumVal -= EachLong;
Answer += -2 * EachLong * SumVal;
}
Console.WriteLine(Answer);
}
}
解説
例えば、数列が
A B C D
の場合
(A-B)^2 + (A-C)^2 + (A-D)^2 + (B-C)^2 + (B-D)-2 + (C-D)^2
= A^2 -2AB + B^2 +
A^2 -2AC + C^2 +
A^2 -2AD + D^2 +
B^2 -2BC + C^2 +
B^2 -2BD + D^2 +
C^2 -2CD + D^2
= 3 * (A^2 + B^2 + C^2 + D^2)
-2A(B+C+D)
-2B(C+D)
-2CD
になることをふまえてます。