AtCoderのABC
次のABCの問題へ
前のABCの問題へ
ABC350-C Sort
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("5");
WillReturn.Add("3 4 1 2 5");
//2
//1 3
//2 4
}
else if (InputPattern == "Input2") {
WillReturn.Add("4");
WillReturn.Add("1 2 3 4");
//0
}
else if (InputPattern == "Input3") {
WillReturn.Add("3");
WillReturn.Add("3 1 2");
//2
//1 2
//2 3
}
else {
string wkStr;
while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
}
return WillReturn;
}
static void Main()
{
List<string> InputList = GetInputList();
int[] AArr = InputList[1].Split(' ').Select(pX => int.Parse(pX)).ToArray();
// Ind[値]なDict
var IndDict = new Dictionary<int, int>();
for (int I = 0; I <= AArr.GetUpperBound(0); I++) {
IndDict[AArr[I]] = I;
}
int MinVal = AArr.Min();
int MaxVal = AArr.Max();
var SwapStrList = new List<string>();
for (int I = MinVal; I <= MaxVal; I++) {
if (AArr[I - 1] == I) continue;
int FromInd = I - 1;
int ToInd = IndDict[I];
SwapStrList.Add(string.Format("{0} {1}", FromInd + 1, ToInd + 1));
// 値のSwap
int wkVal = AArr[FromInd];
AArr[FromInd] = AArr[ToInd];
AArr[ToInd] = wkVal;
IndDict[wkVal] = ToInd;
IndDict[FromInd] = I;
}
Console.WriteLine(SwapStrList.Count);
SwapStrList.ForEach(pX => Console.WriteLine(pX));
}
}
解説
最小値選択法をシュミレーションしてます。
Ind[値]なDictでの高速化もしてます。