AtCoderのABC
次のABCの問題へ
前のABCの問題へ
ABC188-E Peddler
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("4 3");
WillReturn.Add("2 3 1 5");
WillReturn.Add("2 4");
WillReturn.Add("1 2");
WillReturn.Add("1 3");
//3
}
else if (InputPattern == "Input2") {
WillReturn.Add("5 5");
WillReturn.Add("13 8 3 15 18");
WillReturn.Add("2 4");
WillReturn.Add("1 2");
WillReturn.Add("4 5");
WillReturn.Add("2 3");
WillReturn.Add("1 3");
//10
}
else if (InputPattern == "Input3") {
WillReturn.Add("3 1");
WillReturn.Add("1 100 1");
WillReturn.Add("2 3");
//-99
}
else {
string wkStr;
while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
}
return WillReturn;
}
static Dictionary<int, int> mADict = new Dictionary<int, int>();
// 隣接リストで枝を管理
static Dictionary<int, List<int>> mToNodeListDict = new Dictionary<int, List<int>>();
static void Main()
{
List<string> InputList = GetInputList();
int[] wkArr = { };
Action<string> SplitAct = pStr =>
wkArr = pStr.Split(' ').Select(pX => int.Parse(pX)).ToArray();
SplitAct(InputList[1]);
for (int I = 0; I <= wkArr.GetUpperBound(0); I++) {
mADict[I + 1] = wkArr[I];
}
foreach (string EachStr in InputList.Skip(2)) {
SplitAct(EachStr);
int FromNode = wkArr[0];
int ToNode = wkArr[1];
if (mToNodeListDict.ContainsKey(FromNode) == false) {
mToNodeListDict[FromNode] = new List<int>();
}
mToNodeListDict[FromNode].Add(ToNode);
}
Solve();
}
struct JyoutaiDef
{
internal int Level;
internal int CurrNode;
}
// 貪欲法で、金が一番安いノードからDFSを繰り返す(再訪防止で枝切りする)
static void Solve()
{
var VisitedSet = new HashSet<int>();
int Answer = int.MinValue;
foreach (var EachPair in mADict.OrderBy(pX => pX.Value)) {
JyoutaiDef WillPush;
WillPush.Level = 0;
WillPush.CurrNode = EachPair.Key;
var Stk = new Stack<JyoutaiDef>();
Stk.Push(WillPush);
while (Stk.Count > 0) {
JyoutaiDef Popped = Stk.Pop();
if (Popped.Level >= 1) {
Answer = Math.Max(Answer, mADict[Popped.CurrNode] - EachPair.Value);
}
if (mToNodeListDict.ContainsKey(Popped.CurrNode) == false) {
continue;
}
foreach (int EachInt in mToNodeListDict[Popped.CurrNode]) {
// 再訪防止で枝切り
if (VisitedSet.Add(EachInt) == false) continue;
WillPush.Level = Popped.Level + 1;
WillPush.CurrNode = EachInt;
Stk.Push(WillPush);
}
}
}
Console.WriteLine(Answer);
}
}
解説
貪欲法で、金が一番安いノードからDFSを繰り返してます。
再訪防止で枝切りもしてます。