AtCoderのABC
次のABCの問題へ
前のABCの問題へ
ABC486-D Monsters
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("1 1000");
WillReturn.Add("9 100");
WillReturn.Add("2 10");
WillReturn.Add("1 1");
WillReturn.Add("3 10000");
//11001
}
else if (InputPattern == "Input2") {
WillReturn.Add("3");
WillReturn.Add("10 1");
WillReturn.Add("10 1");
WillReturn.Add("2 1");
//-1
}
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();
}
struct MonstrDef
{
internal long ID;
internal long Level;
internal long Cost;
}
static List<MonstrDef> mMonstrList = new List<MonstrDef>();
static void Main()
{
List<string> InputList = GetInputList();
long N = long.Parse(InputList[0]);
long UB = N + 1;
long[] wkArr = { };
Action<string> SplitAct = (pStr) => wkArr = GetSplitArr(pStr);
long CurrID = 0;
foreach (string EachStr in InputList.Skip(1)) {
SplitAct(EachStr);
MonstrDef WillAdd;
WillAdd.ID = CurrID++;
WillAdd.Level = wkArr[0];
WillAdd.Cost = wkArr[1];
mMonstrList.Add(WillAdd);
}
long LastID = mMonstrList.Max(pX => pX.ID);
// 最小コスト[レベル]なインラインDP表
long?[] DPArr = new long?[UB + 1];
DPArr[1] = 0;
long Answer = long.MaxValue;
bool HasAnswer = false;
foreach (MonstrDef EachMonstr in mMonstrList) {
for (long I = UB; EachMonstr.Level <= I; I--) {
if (DPArr[I].HasValue == false) continue;
// モンスターと戦う遷移
long NewI = I + 1;
long NewVal = DPArr[I].Value + EachMonstr.Cost;
if (EachMonstr.ID == LastID) {
// 解の緩和
Answer = Math.Min(Answer, NewVal);
HasAnswer = true;
}
if (DPArr[NewI].HasValue) {
if (DPArr[NewI] <= NewVal) {
continue;
}
}
DPArr[NewI] = NewVal;
}
}
if (HasAnswer) {
Console.WriteLine(Answer);
}
else {
Console.WriteLine(-1);
}
}
}
解説
最小コスト[レベル]を更新するインラインDPで解いてます。
モンスターは最大で6000匹なため、
レベルの最大値も、6001であり
計算量は6000*6000 = 36000000 なため間に合います、
また、特殊処理として、最終モンスターを倒した時には、解を緩和します。
コンテストでRunTimeErrorを出しましたが、
モンスターがN匹いたら、
レベルは、最大で(N+1)になるので、
DP配列の添字は注意する必要があります。