AtCoderのABC
次のABCの問題へ
前のABCの問題へ
ABC345-C One Time Swap
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("abc");
//3
}
else if (InputPattern == "Input2") {
WillReturn.Add("aaaaa");
//1
}
else {
string wkStr;
while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
}
return WillReturn;
}
static void Main()
{
List<string> InputList = GetInputList();
string S = InputList[0];
char[] CharArr = S.ToCharArray();
long UB = CharArr.GetUpperBound(0);
// 同じ文字の有無
bool HasSameChar = true;
if (CharArr.Length == CharArr.Distinct().Count()) {
HasSameChar = false;
}
Dictionary<char, long> CntDict =
CharArr.GroupBy(pX => pX).ToDictionary(pX => pX.Key, pX => pX.LongCount());
long Answer = 0;
for (long I = 0; I <= UB; I++) {
char CurrChar = CharArr[I];
foreach (var EachPair in CntDict) {
if (EachPair.Key == CurrChar) continue;
Answer += EachPair.Value;
}
CntDict[CurrChar]--;
}
if (HasSameChar) Answer++;
Console.WriteLine(Answer);
}
}
解説
最初に、GroupByとToDictionaryで文字ごとの件数を集計し、
左端を全探索してます。