AtCoderのABC
次のABCの問題へ
前のABCの問題へ
ABC447-C Insert and Erase A
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");
WillReturn.Add("BACA");
//3
}
else if (InputPattern == "Input2") {
WillReturn.Add("ABC");
WillReturn.Add("ARC");
//-1
}
else if (InputPattern == "Input3") {
WillReturn.Add("ABC");
WillReturn.Add("ABC");
//0
}
else if (InputPattern == "Input4") {
WillReturn.Add("AAAWAZAAAABAAAU");
WillReturn.Add("AWAAZABAAAAAUA");
//9
}
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()
{
List<string> InputList = GetInputList();
string S = InputList[0];
string T = InputList[1];
// 必要条件のチェック
if (S.Replace("A", "") != T.Replace("A", "")) {
Console.WriteLine(-1);
return;
}
var QueS = new Queue<char>(S);
var QueT = new Queue<char>(T);
long Answer = 0;
while (true) {
if (QueS.Count == 0) {
Answer += QueT.Count;
break;
}
if (QueT.Count == 0) {
Answer += QueS.Count;
break;
}
char PeekS = QueS.Peek();
char PeekT = QueT.Peek();
if (PeekS == PeekT) {
QueS.Dequeue();
QueT.Dequeue();
continue;
}
if (PeekS == 'A') {
QueS.Dequeue();
Answer++;
continue;
}
if (PeekT == 'A') {
QueT.Dequeue();
Answer++;
continue;
}
}
Console.WriteLine(Answer);
}
}
解説
まず、必要条件として、
SからAを消した文字列と
TからAを消した文字列が
完全一致という条件があります。
必要条件を満たしていたら、
SとTのキューを用意して、シュミレーションしてます。
●一致する場合
●一致しない場合でSがA
●一致しない場合でTがA
と場合に分けて考えてます。