yukicoder    前のyukicoderの問題へ

yukicoder 3489 あみだくじ作り


問題へのリンク


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("2");
            WillReturn.Add("1 2");
        }
        else if (InputPattern == "Input2") {
            WillReturn.Add("2");
            WillReturn.Add("2 1");
        }
        else if (InputPattern == "Input3") {
            WillReturn.Add("3");
            WillReturn.Add("3 1 2");
        }
        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();
        long N = long.Parse(InputList[0]);
        long[] PArr = GetSplitArr(InputList[1]);

        var GoalDict = new Dictionary<long, long>();
        for (long I = 0; I <= PArr.GetUpperBound(0); I++) {
            GoalDict[PArr[I]] = I + 1;
        }

        var CurrDict = new Dictionary<long, long>();
        for (long I = 1; I <= N; I++) {
            CurrDict[I] = I;
        }

        var AnswerList = new List<long>();
        for (long I = 1; I <= N; I++) {
            long SearchVal = GoalDict[I];
            long StaInd = 0;
            for (long J = I + 1; J <= N; J++) {
                if (CurrDict[J] == SearchVal) {
                    StaInd = J;
                    break;
                }
            }
            // 既にゴールにいる場合
            if (I == StaInd) continue;

            for (long J = StaInd; I + 1 <= J; J--) {
                // 三角交換
                long tmp = CurrDict[J];
                CurrDict[J] = CurrDict[J - 1];
                CurrDict[J - 1] = tmp;

                AnswerList.Add(J - 1);
            }
        }
        Console.WriteLine("Yes");
        Console.WriteLine(AnswerList.Count);
        AnswerList.ForEach(pX => Console.WriteLine(pX));
    }
}


解説

バブルソートをシュミれば最小の交換回数になるので
解くことができます。
N * N は、バブルソートの最大交換回数より大きいので
必ず解ありとなります。