AtCoderのABC
次のABCの問題へ
前のABCの問題へ
ABC426-D Pop and Insert
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("5");
WillReturn.Add("01001");
WillReturn.Add("3");
WillReturn.Add("000");
WillReturn.Add("15");
WillReturn.Add("110010111100101");
//4
//0
//16
}
else {
string wkStr;
while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
}
return WillReturn;
}
static long[] GetSplitArr(string pStr)
{
return (pStr == "" ? new string[0] : pStr.Split(' ')).Select(pX => long.Parse(pX)).ToArray();
}
static void Main()
{
var sb = new System.Text.StringBuilder();
List<string> InputList = GetInputList();
for (int I = 2; I <= InputList.Count - 1; I += 2) {
string S = InputList[I];
long Answer = Solve(S);
sb.Append(Answer);
sb.AppendLine();
}
Console.Write(sb.ToString());
}
static long Solve(string pStr)
{
List<RunLen.RunLenInfo> RunLenList = RunLen.DeriveRunLenInfoList(pStr);
if (RunLenList.Count == 1) {
return 0;
}
long Cnt0 = RunLenList.Where(pX => pX.AppearChar == '0').Sum(pX => pX.RunLen);
long Cnt1 = RunLenList.Where(pX => pX.AppearChar == '1').Sum(pX => pX.RunLen);
var AnswerList = new List<long>();
foreach (RunLen.RunLenInfo EachRunLenInfo in RunLenList) {
long NeedMove0 = Cnt0;
long NeedMove1 = Cnt1;
if (EachRunLenInfo.AppearChar == '0') {
long AnswerKouho = (NeedMove0 - EachRunLenInfo.RunLen) * 2 + NeedMove1;
AnswerList.Add(AnswerKouho);
}
if (EachRunLenInfo.AppearChar == '1') {
long AnswerKouho = (NeedMove1 - EachRunLenInfo.RunLen) * 2 + NeedMove0;
AnswerList.Add(AnswerKouho);
}
}
return AnswerList.Min();
}
}
#region RunLen
// ランレングス圧縮(文字列)
internal class RunLen
{
// ランレングス圧縮情報
internal class RunLenInfo
{
internal char AppearChar;
internal int RunLen;
}
// ランレングス圧縮結果を返す
internal static List<RunLenInfo> DeriveRunLenInfoList(string pBaseStr)
{
var WillReturn = new List<RunLenInfo>();
int StrUB = pBaseStr.Length - 1;
char PrevChar = pBaseStr[0];
int StrLen = 0;
for (int I = 0; I <= StrUB; I++) {
if (pBaseStr[I] != PrevChar) {
RunLenInfo WillAdd = new RunLenInfo();
WillAdd.AppearChar = PrevChar;
WillAdd.RunLen = StrLen;
WillReturn.Add(WillAdd);
StrLen = 0;
PrevChar = pBaseStr[I];
}
StrLen++;
if (I == StrUB) {
RunLenInfo WillAdd = new RunLenInfo();
WillAdd.AppearChar = pBaseStr[I];
WillAdd.RunLen = StrLen;
WillReturn.Add(WillAdd);
}
}
return WillReturn;
}
}
#endregion
解説
ダイソーの500円のオセロセットで
110010111100101で考察すると、
まずRLEします。
○●○●○●○●○
○● ○●
○
○
すると、移動させない塊を全て試せば良いと分かります。
移動させない塊を決めると、
(移動させない塊以外での同じ色の個数) * 2 + 違う色の個数
が移動の総コストとなります。