結果

問題 No.271 next_permutation (2)
ユーザー Min_25Min_25
提出日時 2017-05-05 10:42:20
言語 PyPy2
(7.3.13)
結果
AC  
実行時間 156 ms / 2,000 ms
コード長 1,563 bytes
コンパイル時間 1,668 ms
コンパイル使用メモリ 77,488 KB
実行使用メモリ 88,964 KB
最終ジャッジ日時 2023-08-17 11:28:42
合計ジャッジ時間 4,688 ms
ジャッジサーバーID
(参考情報)
judge11 / judge13
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 102 ms
80,780 KB
testcase_01 AC 106 ms
81,968 KB
testcase_02 AC 129 ms
87,360 KB
testcase_03 AC 92 ms
80,680 KB
testcase_04 AC 71 ms
77,828 KB
testcase_05 AC 73 ms
77,932 KB
testcase_06 AC 72 ms
77,876 KB
testcase_07 AC 71 ms
78,224 KB
testcase_08 AC 72 ms
77,920 KB
testcase_09 AC 72 ms
77,828 KB
testcase_10 AC 71 ms
78,120 KB
testcase_11 AC 74 ms
77,968 KB
testcase_12 AC 88 ms
80,008 KB
testcase_13 AC 156 ms
88,964 KB
testcase_14 AC 73 ms
77,956 KB
testcase_15 AC 73 ms
78,124 KB
testcase_16 AC 73 ms
77,912 KB
testcase_17 AC 72 ms
77,888 KB
testcase_18 AC 151 ms
88,924 KB
testcase_19 AC 135 ms
88,224 KB
testcase_20 AC 137 ms
87,472 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
from itertools import permutations

def solve():
  def factoradic(n, seq):
    def add(idx, v):
      while idx <= n:
        fenwick[idx] += v
        idx += idx & -idx
      return
    def read(idx):
      ret = 0
      while idx > 0:
        ret += fenwick[idx]
        idx &= idx - 1
      return ret
    fenwick = [0] * (n + 1)
    for i in range(2, n + 1):
      add(i, 1)
    ret = [1] * n
    for i, c in enumerate(seq):
      ret[i] = read(c + 1)
      add(c + 1, -1)
    return ret

  def sum_inv_all(n):
    return (n * (n - 1) // 2) % mod * ((mod + 1) // 2) % mod * facts[n] % mod

  def sum_inv(A):
    n = len(A)
    block = 0
    ret = 0
    isum = 0
    for i in range(n - 1, 0, -1):
      d = A[i]
      s = i * (i + 1) // 2 % mod
      t = d * (d - 1) // 2 % mod
      u = s * block + t + d * isum
      ret = (ret + u % mod * facts[i]) % mod
      isum += d
      block = (block * (i + 1) + d) % mod
    return ret

  def update(vals, K):
    n = len(vals)
    for i in range(1, n):
      K, vals[i] = divmod(vals[i] + K, i + 1)
    ret = 0
    if K > 0:
      ret = K % mod * sum_inv_all(n) % mod
    return ret

  F = 100010
  mod = 10 ** 9 + 7
  facts = [1] * F
  for i in range(1, F):
    facts[i] = facts[i - 1] * i % mod

  input = sys.stdin.readline
  while 1:
    try:
      N, K = map(int, input().split())
    except:
      break
    A = [c - 1 for c in map(int, input().split())]
    vals = factoradic(N, A)[::-1]
    ans  = -sum_inv(vals)
    ans += update(vals, K)
    ans += sum_inv(vals)
    print(ans % mod)

solve()
0