AtCoderの企業コンテスト    次の企業コンテストの問題へ    前の企業コンテストの問題へ

Tenka1 Programmer Beginner Contest2018 C Align


問題へのリンク


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("6");
            WillReturn.Add("8");
            WillReturn.Add("1");
            WillReturn.Add("2");
            WillReturn.Add("3");
            //21
        }
        else if (InputPattern == "Input2") {
            WillReturn.Add("6");
            WillReturn.Add("3");
            WillReturn.Add("1");
            WillReturn.Add("4");
            WillReturn.Add("1");
            WillReturn.Add("5");
            WillReturn.Add("9");
            //25
        }
        else if (InputPattern == "Input3") {
            WillReturn.Add("3");
            WillReturn.Add("5");
            WillReturn.Add("5");
            WillReturn.Add("1");
            //8
        }
        else {
            string wkStr;
            while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
        }
        return WillReturn;
    }

    static long[] mAArr;
    static long UB;

    static void Main()
    {
        List<string> InputList = GetInputList();
        mAArr = InputList.Skip(1).Select(pX => long.Parse(pX)).ToArray();
        UB = mAArr.GetUpperBound(0);

        // 昇順にソートしておく
        Array.Sort(mAArr);

        var StaIndList = new List<long>();
        if (UB % 2 == 0) {
            StaIndList.Add(UB / 2);
        }
        else {
            StaIndList.Add(UB / 2);
            StaIndList.Add(UB / 2 + 1);
        }

        var ResultList = new List<long>();
        foreach (long EachStaInd in StaIndList) {
            ResultList.Add(ExecTSP(EachStaInd, false));
            ResultList.Add(ExecTSP(EachStaInd, true));
        }
        Console.WriteLine(ResultList.Max());
    }

    // 開始Indと、最初に左に移動するかを引数として、TSPでの移動距離を返す
    static long ExecTSP(long pStaInd, bool pFirstToLeft)
    {
        long LeftInd = 0;
        long RightInd = UB;

        bool ToLeft = pFirstToLeft;

        long SumDistance = 0;
        long CurrInd = pStaInd;
        while (true) {
            long ToInd;
            if (ToLeft) {
                ToInd = LeftInd++;
            }
            else {
                ToInd = RightInd--;
            }
            if (ToInd == pStaInd) break;

            SumDistance += Math.Abs(mAArr[CurrInd] - mAArr[ToInd]);
            CurrInd = ToInd;
            ToLeft = !(ToLeft);
        }
        return SumDistance;
    }
}


解説

数直線上を左右に移動可能なTSP問題で
移動距離を最長にすると考えて

中央値から最初に左に移動する場合と、
中央値から最初に右に移動する場合で、
最長の移動距離をチェックしてます。