結果

問題 No.2382 Amidakuji M
ユーザー kakel-san
提出日時 2023-07-14 23:42:54
言語 C#(csc)
(csc 3.9.0)
結果
AC  
実行時間 127 ms / 2,000 ms
コード長 2,184 bytes
コンパイル時間 2,623 ms
コンパイル使用メモリ 107,136 KB
実行使用メモリ 37,760 KB
最終ジャッジ日時 2024-09-16 08:51:28
合計ジャッジ時間 3,288 ms
ジャッジサーバーID
(参考情報)
judge3 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 19
権限があれば一括ダウンロードができます
コンパイルメッセージ
Microsoft (R) Visual C# Compiler version 3.9.0-6.21124.20 (db94f4cc)
Copyright (C) Microsoft Corporation. All rights reserved.

ソースコード

diff #

using System;
using static System.Console;
using System.Linq;
using System.Collections.Generic;
class Program
{
    static int[] NList => ReadLine().Split().Select(int.Parse).ToArray();
    static long[] LList => ReadLine().Split().Select(long.Parse).ToArray();
    public static void Main()
    {
        Solve();
    }
    static void Solve()
    {
        var c = LList;
        var (n, m) = ((int)c[0], c[1]);
        var p = NList;

        var ft = new FenwickTree(n + 2);
        var rev = 0L;
        for (var i = 0; i < n; ++i)
        {
            rev += ft.Sum(n + 1) - ft.Sum(p[i]);
            ft.Add(p[i], 1);
        }
        var d = 0L;
        if (rev != 0) d = (m + rev - 1) / m;

        if (m * d % 2 == rev % 2) WriteLine(m * d);
        else if (m % 2 == 1) WriteLine(m * (d + 1));
        else WriteLine(-1);
    }
    class FenwickTree
    {
        int size;
        long[] tree;
        public FenwickTree(int size)
        {
            this.size = size;
            tree = new long[size + 2];
        }
        public void Add(int index, int value)
        {
            ++index;
            for (var x = index; x <= size; x += (x & -x)) tree[x] += value;
        }
        /// <summary>先頭からindexまでの和(include index)</summary>
        public long Sum(int index)
        {
            ++index;
            var sum = 0L;
            for (var x = index; x > 0; x -= (x & -x)) sum += tree[x];
            return sum;
        }
        /// <summary>Sum(x) >= value となる最小のxを求める</summary>
        // 各要素は非負であること
        // sizeが2べきでない場合に正しく動く?
        public int LowerBound(long value)
        {
            if (value < 0) return -1;
            var x = 0;
            var b = 1;
            while (b * 2 <= size) b <<= 1;
            for (var k = b; k > 0; k >>= 1)
            {
                if (x + k <= size && tree[x + k] < value)
                {
                    value -= tree[x + k];
                    x += k;
                }
            }
            return x;
        }
    }
}
0