AtCoderのABC
次のABCの問題へ
前のABCの問題へ
ABC197-C ORXOR
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("1 5 7");
//2
}
else if (InputPattern == "Input2") {
WillReturn.Add("3");
WillReturn.Add("10 10 10");
//0
}
else if (InputPattern == "Input3") {
WillReturn.Add("4");
WillReturn.Add("1 3 3 1");
//0
}
else {
string wkStr;
while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
}
return WillReturn;
}
struct JyoutaiDef
{
internal int CurrInd;
internal List<long> ORList;
}
static void Main()
{
List<string> InputList = GetInputList();
long[] AArr = InputList[1].Split(' ').Select(pX => long.Parse(pX)).ToArray();
int UB = AArr.GetUpperBound(0);
JyoutaiDef WillPush;
WillPush.CurrInd = 0;
WillPush.ORList = new List<long>();
var Stk = new Stack<JyoutaiDef>();
Stk.Push(WillPush);
long Answer = long.MaxValue;
while (Stk.Count > 0) {
JyoutaiDef Popped = Stk.Pop();
if (Popped.CurrInd > UB) {
long AnswerKouho = Popped.ORList[0];
for (int I = 1; I <= Popped.ORList.Count - 1; I++) {
AnswerKouho ^= Popped.ORList[I];
}
Answer = Math.Min(Answer, AnswerKouho);
continue;
}
// 分割しない場合
if (Popped.ORList.Count > 0) {
WillPush.CurrInd = Popped.CurrInd + 1;
WillPush.ORList = new List<long>(Popped.ORList);
int LastInd = WillPush.ORList.Count - 1;
long LastVal = WillPush.ORList[LastInd];
LastVal |= AArr[Popped.CurrInd];
WillPush.ORList.RemoveAt(LastInd);
WillPush.ORList.Add(LastVal);
Stk.Push(WillPush);
}
// 分割する場合
WillPush.CurrInd = Popped.CurrInd + 1;
WillPush.ORList = new List<long>(Popped.ORList);
WillPush.ORList.Add(AArr[Popped.CurrInd]);
Stk.Push(WillPush);
}
Console.WriteLine(Answer);
}
}
解説
制約が緩いので、深さ優先探索で、全ての分割を試してます。
C#での
ビットの論理積(BitAnd)は &
ビットの論理和(BitOr)は |
ビットの排他的論理和は ^
を使います。