Problem:


Score : 300 points

Problem Statement

We have a sequence of N integers A~=~A_0,~A_1,~...,~A_{N - 1}.

Let B be a sequence of K \times N integers obtained by concatenating K copies of A. For example, if A~=~1,~3,~2 and K~=~2, B~=~1,~3,~2,~1,~3,~2.

Find the inversion number of B, modulo 10^9 + 7.

Here the inversion number of B is defined as the number of ordered pairs of integers (i,~j)~(0 \leq i < j \leq K \times N - 1) such that  B_i > B_j.

Constraints

All values in input are integers.

1 \leq N \leq 2000

1 \leq K \leq 10^9

1 \leq A_i \leq 2000

Input

Input is given from Standard Input in the following format:

N K
A_0 A_1 ... A_{N - 1}

Output

Print the inversion number of B, modulo 10^9 + 7.

Sample Input 1

2 2
2 1

Sample Output 1

3

In this case, B~=~2,~1,~2,~1. We have:

B_0 > B_1

B_0 > B_3

B_2 > B_3

Thus, the inversion number of B is 3.

Sample Input 2

3 5
1 1 1

Sample Output 2

0

A may contain multiple occurrences of the same number.

Sample Input 3

10 998244353
10 9 8 7 5 6 3 4 2 1

Sample Output 3

185297239

Be sure to print the output modulo 10^9 + 7.



Sample input:
2 2
2 1


Sample output:
3

Submission status: Accepted

Solution code:
def main(sample_file = ''):

    """ convenient functions
    # for i, a in enumerate(iterable)
    # q, mod = divmod(a, b)
    # divmod(x, y) returns the tuple (x//y, x%y)
    # Higher-order function: reduce(operator.mul, xyz_count, 1)
    # manage median(s) using two heapq https://atcoder.jp/contests/abc127/tasks/abc127_f
    """

    """convenient decorator
    # @functools.lru_cache():
    # to facilitate use of recursive function
        # ex:
        # from functools import lru_cache
        # import sys
        # sys.setrecursionlimit(10**9)
        # @lru_cache(maxsize=None)
        # def fib(n):
        #     if n < 2:
        #         return n
        #     return fib(n-1) + fib(n-2)
        # print(fib(1000))
    """
    
    # import numpy as np
    import sys
    sys.setrecursionlimit(10**7)
    from itertools import accumulate, combinations, permutations, product # https://docs.python.org/ja/3/library/itertools.html
    # accumulate() returns iterator! to get list: list(accumulate())
    from math import factorial, ceil, floor, sqrt
    def factorize(n):
        """return the factors of the Arg and count of each factor
        
        Args:
            n (long): number to be resolved into factors
        
        Returns:
            list of tuples: factorize(220) returns [(2, 2), (5, 1), (11, 1)]
        """
        fct = []  # prime factor
        b, e = 2, 0  # base, exponent
        while b * b <= n:
            while n % b == 0:
                n = n // b
                e = e + 1
            if e > 0:
                fct.append((b, e))
            b, e = b + 1, 0
        if n > 1:
            fct.append((n, 1))
        return fct
    def combinations_count(n, r):
        """Return the number of selecting r pieces of items from n kinds of items.
        
        Args:
            n (long): number
            r (long): number
        
        Raises:
            Exception: not defined when n or r is negative
        
        Returns:
            long: number
        """
        # TODO: How should I do when n - r is negative?
        if n < 0 or r < 0:
            raise Exception('combinations_count(n, r) not defined when n or r is negative')
        if n - r < r: r = n - r
        if r < 0: return 0
        if r == 0: return 1
        if r == 1: return n
        numerator = [n - r + k + 1 for k in range(r)]
        denominator = [k + 1 for k in range(r)]
        for p in range(2,r+1):
            pivot = denominator[p - 1]
            if pivot > 1:
                offset = (n - r) % p
                for k in range(p-1,r,p):
                    numerator[k - offset] /= pivot
                    denominator[k] /= pivot
        result = 1
        for k in range(r):
            if numerator[k] > 1:
                result *= int(numerator[k])
        return result
    def combinations_with_replacement_count(n, r):
        """Return the number of selecting r pieces of items from n kinds of items allowing individual elements to be repeated more than once.
        
        Args:
            n (long): number
            r (long): number
        
        Raises:
            Exception: not defined when n or r is negative
        
        Returns:
            long: number
        """
        if n < 0 or r < 0:
            raise Exception('combinations_with_replacement_count(n, r) not defined when n or r is negative')
        elif n == 0:
            return 1
        else:
            return combinations_count(n + r - 1, r)
    from bisect import bisect_left, bisect_right
    from collections import deque, Counter, defaultdict # https://docs.python.org/ja/3/library/collections.html#collections.deque
    from heapq import heapify, heappop, heappush, heappushpop, heapreplace,nlargest,nsmallest # https://docs.python.org/ja/3/library/heapq.html
    from copy import deepcopy, copy # https://docs.python.org/ja/3/library/copy.html
    import operator
    from operator import itemgetter #sort 
    # ex1: List.sort(key=itemgetter(1))
    # ex2: sorted(tuples, key=itemgetter(1,2))
    from functools import reduce, lru_cache
    def chmin(x, y):
        """change minimum
        if x > y, x = y and return (x, True).
        convenient when solving problems of dp[i]
        
        Args:
            x (long): current minimum value
            y (long): potential minimum value
        
        Returns:
            (x, bool): (x, True) when updated, else (x, False)
        """
        if x > y:
            x = y
            return (x, True)
        else:
            return (x, False)
    def chmax(x, y):
        """change maximum
        if x < y, x = y and return (x, True).
        convenient when solving problems of dp[i]
        
        Args:
            x (long): current maximum value
            y (long): potential maximum value
        
        Returns:
            (x, bool): (x, True) when updated, else (x, False)
        """
        if x < y:
            x = y
            return (x, True)
        else:
            return (x, False)

    from fractions import gcd # Deprecated since version 3.5: Use math.gcd() instead.
    def gcds(numbers):
        return reduce(gcd, numbers)
    def lcm(x, y):
        return (x * y) // gcd(x, y)
    def lcms(numbers):
        return reduce(lcm, numbers, 1)
    def make_divisors(n, reversed=False):
        """create list of divisors
        
        Args:
            number (int): number from which list of divisors is created
            reversed (bool, optional): ascending order if False. Defaults to False.
        
        Returns:
            list: list of divisors
        """
        divisors = set()
        for i in range(1, int(n**0.5)+1):
            if n % i == 0:
                divisors.add(i)
                divisors.add(n//i)
        return sorted(list(divisors),reverse=reversed)
    
    # first create factorial_list
    # fac_list = mod_factorial_list(n)
    INF = 10 ** 18
    MOD = 10 ** 9 + 7
    modpow = lambda a, n, p = MOD: pow(a, n, p) # Recursive function in python is slow!
    def modinv(a, p = MOD):
        # evaluate reciprocal using Fermat's little theorem:
        # a**(p-1) is identical to 1 (mod p) when a and p is coprime
        return modpow(a, p-2, p)
    def modinv_list(n, p = MOD):
        if n <= 1:
            return [0,1][:n+1]
        else:
            inv_t = [0,1]
            for i in range(2, n+1):
                inv_t += [inv_t[p % i] * (p - int(p / i)) % p]
            return inv_t
    def modfactorial_list(n, p = MOD):
        if n == 0:
            return [1]
        else:
            l = [0] * (n+1)
            tmp = 1
            for i in range(1, n+1):
                tmp = tmp * i % p
                l[i] = tmp
            return l
    def modcomb(n, k, fac_list = [], p = MOD):
        # fac_list = modfactorial_list(100)
        # print(modcomb(100, 5, modfactorial_list(100)))
        from math import factorial
        if n < 0 or k < 0 or n < k: return 0
        if n == 0 or k == 0: return 1
        if len(fac_list) <= n:
            a = factorial(n) % p
            b = factorial(k) % p
            c = factorial(n-k) % p
        else:
            a = fac_list[n]
            b = fac_list[k]
            c = fac_list[n-k]
        return (a * modpow(b, p-2, p) * modpow(c, p-2, p)) % p
    def modadd(a, b, p = MOD):
        return (a + b) % MOD
    def modsub(a, b, p = MOD):
        return (a - b) % p
    def modmul(a, b, p = MOD):
        return ((a % p) * (b % p)) % p
    def moddiv(a, b, p = MOD):
        return modmul(a, modpow(b, p-2, p))

    class UnionFindTree:
        """union find tree class
        TODO: fix this description...
        how to use (example):
        >>  uf = UnionFindTree(N) 
        >>  if uf.find_root(a) == uf.find_root(b):
        >>      do something
        >>  else:
        >>      do something
        >>      uf.unite(a, b)
        """
        def __init__(self, N):
            self.root = [-1] * (N+1)
            self.rank   = [0]  * (N+1)
            self.connected_num = [1] * (N+1)
    
        def find_root(self,x):
            root = self.root
            while root[x] != -1:
                x = root[x]
            return x
    
        def unite(self,x,y):
            root = self.root
            rank = self.rank
            connected_num = self.connected_num
            find_root = self.find_root
    
            rx = find_root(x)
            ry = find_root(y)
            if rx != ry:
                if rank[rx] < rank[ry]:
                    root[rx] = ry
                    rx,ry = ry,rx
                else:
                    if rank[rx] == rank[ry]:
                        rank[rx] += 1
                    root[ry] = rx       
                connected_num[rx] += connected_num[ry]

    # Graph: https://en.wikipedia.org/wiki/Directed_graph
    # Bellman-Ford: O(|V||E|). Use this if there exists an edge with negative length in the graph
    # After N steps, the shortest path has converded if there doesn't exist an cycle of edges with negative
    # Watch out: d[N] == d[2*N] doesn't necessarily mean the graph doesn't have negative cycle
    # ref: https://www.youtube.com/watch?v=1Z6ofKN03_Y

    def BellmanFord(N, M, ABC, vertex_start, vertex_end, value_if_inf = -1, find_shortest = False):
        """to calculate furthest or shortest length between vertex_start and vertex_end using BellmanFord algorithm
        
        Args:
            N (int): number of vertices
            M (int): number of edges
            ABC (list): [(ai, bi, ci) for _ in range(N)] where i-th edge is directed from vertex ai to vertex bi and the length is ci 
            vertex_start (int): start vertex. usually use 0.
            vertex_end (int): end vertex. usually use N-1.
            value_if_inf (int or string as you like, optional): value you want when the furthest (or shortest) distance is infinite (or -infinite). Defaults to -1.
            find_shortest (bool, optional): choose False to find furthest path. Defaults to False.
        
        Returns:
            int or string: normally int (but can be str if you set value_if_inf to str)
            
        Example:
                N, M, P = R()
                ABC = [R() for _ in range(M)]
                ABC = [(a-1, b-1, c-P) for a, b, c in ABC]
                print(BellmanFord(N, M, ABC, 0, N-1, value_if_inf = 'inf'))

        """

        def make_reachable_list(N, M, ABC, vertex_start, vertex_end):
            reachable_to_direct = defaultdict(list)
            reachable_from_direct = defaultdict(list)
            reachable_from_start = [False] * N
            reachable_to_end = [False] * N
            reachable_from_start[vertex_start] = True
            reachable_to_end[vertex_end] = True
            reachable_from_both_sides = [False] * N
            dfs_from_start = []
            dfs_to_end = []
            for a, b, c in ABC:
                reachable_to_direct[a].append(b)
                reachable_from_direct[b].append(a)
                if a == vertex_start:
                    dfs_from_start.append(b)
                    reachable_from_start[b] = True
                if b == vertex_end:
                    dfs_to_end.append(a)
                    reachable_to_end[a] = True
            while dfs_from_start:
                v = dfs_from_start.pop()
                for i in reachable_to_direct[v]:
                    if not reachable_from_start[i]:
                        reachable_from_start[i] = True
                        dfs_from_start.append(i)
            while dfs_to_end:
                v = dfs_to_end.pop()
                for i in reachable_from_direct[v]:
                    if not reachable_to_end[i]:
                        reachable_to_end[i] = True
                        dfs_to_end.append(i)
            for i in range(N):
                reachable_from_both_sides[i] = reachable_from_start[i] and reachable_to_end[i]
            return reachable_from_both_sides
        
        reachable_from_both_sides = make_reachable_list(N, M, ABC, vertex_start, vertex_end)
        
        if find_shortest:
            dist = [INF for i in range(N)]
        else:
            dist = [-INF for i in range(N)]
        
        dist[vertex_start] = 0
        for i in range(N):
            updated = False
            for a, b, c in ABC:
                if not reachable_from_both_sides[a]:
                    continue
                elif find_shortest:
                    update_condition = dist[a] + c < dist[b]
                else:
                    update_condition = dist[a] + c > dist[b]
                if dist[a] != INF and update_condition:
                    dist[b] = dist[a] + c
                    updated = True
                    if i == N-1:
                        return value_if_inf
            if not updated:
                break
        return dist[vertex_end]

    """ initialize variables and set inputs
    # initialize variables
        # to initialize list, use [0] * n
        # to initialize two dimentional array, use [[0] * N for _ in range(N)]
    # set inputs
        # put inputs between specific values (almost as quickly)
        # ex) S = [-INF] + [int(r()) for _ in range(A)] + [INF]
        # open(0).read() is sometimes useful:
        # ex) n, m, *x = map(int, open(0).read().split())
        #     min(x[::2]) - max(x[1::2])
        # ex2) *x, = map(int, open(0).read().split())
        #     don't forget to add comma after *x if only one variable is used
    # preprocessing
        # transpose = [x for x in zip(*data)]
        # ex) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] => [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
        # flat = [flatten for inner in data for flatten in inner]
        # ex) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] => [1, 2, 3, 4, 5, 6, 7, 8, 9]
    # calculate and output
        # output pattern
        # ex1) print(*l) => when l = [2, 5, 6], printed 2 5 6
    """

    # functions to read input
    r = lambda: sys.stdin.readline().strip()
    r_int = lambda: int(r())
    R = lambda: list(map(int, r().split()))
    Rmap = lambda: map(int, r().split())
    Rfloat = lambda: list(map(float, r().split()))
    Rtuple = lambda: tuple(map(int, r().split()))

    """ how to treat input
    # single int: int(r())
    # single string: r()
    # single float: float(r())
    # line int: R()
    # line string: r().split()
    # line (str, int, int): [j if i == 0 else int(j) for i, j in enumerate(r().split())]
    # lines int: [R() for _ in range(n)]
    """

    # for test
    if sample_file:
        sys.stdin = open(sample_file)
        
    # ----------------------------------
    # main

    N, K = R()
    A = R()
    revA = reversed(A)
    sotA = sorted(A)
    ans = [0] * N
    l = []
    for i, a in enumerate(revA):
        l.append(a)
        l.sort()
        ans[N-1-i] = bisect_left(l, a)
    tmp = (sum(ans)*K)%(10**9+7)
    for i, a in enumerate(sotA):
        ans[N-1-i] = bisect_left(sotA, a)
    print((sum(ans)*K*(K-1)//2 + tmp)%(10**9+7))
            

    # to finish code, use return instead of exit()
    # end of main
    # ----------------------------------

    """memo: how to use defaultdict of list
    # initialize
    Dic = defaultdict(list)
    # append / extend
    Dic[x].append(y)
    # three methods for loop: keys(), values(), items()
    for k, v in Dic.items():
    """
    
    """memo: how to solve binary problems
    # to make binary digits text
    >>> a = 5
    >>> bin_str_a = format(a, '#06b')
    >>> print(bin_str_a)
    0b0101 # first 2 strings (='0b') indicates it is binary
    """
    
    """memo: how to solve the problem
    creating simple test/answer
    greed
    simple dp
    graph
    """

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
A = list(map(int, input().split()))
mod = 10 ** 9 + 7
table = [0 for _ in range(N)]
ftable = [0 for _ in range(N)]
for i in range(N):
  for j in range(N):
    if A[i] > A[j]:
      table[i] += 1
      if i < j:
        ftable[i] += 1
print((sum(table) * (K * (K - 1)) // 2 + sum(ftable) * K) % mod)

Submission status: Accepted

Solution code:
def li():
    return list(map(int, input().split()))


if __name__ == "__main__":
    [n, k] = li()
    a_list = li()
    mod = 10 ** 9 + 7

    tentou = 0
    b = k * (k + 1) // 2 % mod
    c = k * (k - 1) // 2 % mod
    for index in range(n):
        num1 = len([0 for a in a_list[index + 1:] if a_list[index] > a])
        num2 = len([0 for a in a_list[:index] if a_list[index] > a])
        tentou = tentou + num1 * b + num2 * c
        tentou = tentou % mod
    print(tentou)

# i=0系に対する転倒数
# a1, ..., an-1の中でa0より小さい数の個数 * (k + k-1 + ... + 1)
# i=1
# a2, ..., an-1の中でa1より小さい数の個数 * (k + k-1 + ... + 1) + a0の中でa1より小さい数の個数 * (k-1 + ... + 1)
# i=m
# am+1, ..., an-1の中でamより小さい数の個数 * (k + k-1 + ... + 1) + a0, ..., am-1の中でa1より小さい数の個数 * (k-1 + ... + 1)

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
li = list(map(int,input().split()))

cnt_a = 0
cnt_b = 0
mod = 10**9 + 7

for i in range(n):
    for j in range(n):
        if i >= j:
            if li[i] > li[j]:
                cnt_b += 1
        else:
            if li[i] > li[j]:
                cnt_a += 1
            
ans = cnt_a * (k*(k+1))//2 +  cnt_b * ((k-1)*k) // 2

print(ans%mod)

Submission status: Accepted

Solution code:
#import numpy as np
from numpy import*
#from scipy.sparse.csgraph import shortest_path #shortest_path(csgraph=graph) # dijkstra# floyd_warshall
#from scipy.sparse import csr_matrix
 
from collections import* #defaultdict Counter deque appendleft
from fractions import gcd
from functools import* #reduce
from itertools import* #permutations("AB",repeat=2) combinations("AB",2) product("AB",2) groupby accumulate
from operator import mul,itemgetter
from bisect import* #bisect_left bisect_right
from heapq import* #heapify heappop heappushpop
from math import factorial,pi
from copy import deepcopy
import sys
sys.setrecursionlimit(10**8)
#input=sys.stdin.readline  #危険！基本オフにしろ！
 
def main():
    n,k,*a=map(int,open(0).read().split())
    a=array(a)
    b=0
    c=0
    for i in range(1,n):
        ac=array(a[i:])
        b+=len(ac[ac<a[i-1]])
    for i in range(n):
        c+=len(a[a<a[i]])
    print( (b*k+c*k*(k-1)//2) % (10**9+7) )
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
A=list(map(int,input().split()))
x=0
y=0
for i in range(n):
  for j in A[i+1:]:
    if A[i]>j:
      x+=1
for i in range(n):
  for j in A:
    if A[i]>j:
      y+=1
print((x*k+y*k*(k-1)//2)%1000000007)

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
A = list(map(int, input().split()))
t=0
for i in range(N-1):
    for j in range(i+1,N):
        if A[i]>A[j]:
            t+=1
A.sort()
T=0
s=A[0]
n=0
for i in range(1,N):
    if A[i]!=s:
        n=i
        s=A[i]
    T+=n
print((t*K+K*(K-1)//2*T)%(10**9+7))

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
A = list(map(int, input().split()))
MOD = 10 ** 9 + 7

a = 0
b = 0
for i in range(N - 1):
  for j in range(i + 1, N):
    if A[i] > A[j]:
      a += 1
    if A[i] < A[j]:
      b += 1
ans = a * K * (K + 1) // 2
ans += b * K * (K - 1) // 2
print(ans % MOD)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
a = list(map(int, input().split()))

first_count = 0
second_count = 0
for i in range(N):
  for j in range(i, N):
    if a[i] > a[j]:
      first_count += 1
    if a[N-i-1] > a[N-j-1]:
      second_count += 1
      
      
print((first_count * K * (K + 1) // 2 + second_count * K * (K -1) // 2) % (10 ** 9 + 7))

Submission status: Accepted

Solution code:
M = 10**9+7
n, k = map(int, input().split())
*a, = map(int, input().split())
a = a[::-1]
b = [0]*2001
c = [0]*n
d = [0]*n
for i in range(n):
    b[a[i]] += 1
    if i > 0:
        c[i] += sum(b[:a[i]])
for i in range(n):
    f = b[:a[i]]
    if f: d[i] += sum(f)
g, h = sum(c)%M, sum(d)%M
print((k*g+k*(k-1)//2*h)%M)

Submission status: Accepted

Solution code:
N,K = map(int,input().split())
A = list(map(int,input().split()))
INF = 10**9+7

cnt = [0]*N

for i in range(N):
    c = 0
    x = A[i]
    for j in range(i+1,N):
        y = A[j]
        if x > y:
            c += 1
    cnt[i] = c*K
for i in range(N):
    x = A[i]
    c = 0
    for j in range(N):
        y = A[j]
        if x > y:
            c += 1
    cnt[i] += (c*K*(K-1)//2)%INF
print(sum(cnt)%INF)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
a = [int(x) for x in input().split()]
mod = 1000000007

ans = 0
for i in range(n):
    cnt,tmp = 0,0
    for j in range(i+1, n):
        if a[i] > a[j] : cnt+=1
    for j in range(0, n):
        if a[i] > a[j] : tmp+=1
    ans += (2*cnt + (k-1)*tmp)*k//2
    ans %= mod

print(ans)

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
a=list(map(int,input().split()))
mod=10**9+7

ans=0

for i in range(n):
    before=0
    whole=0
    ai=a[i]
    for j in range(n):
        if ai>a[j]:
            whole+=1
            before+=1
            if i>j:
                before-=1
    
    ans+=whole*(k*(k-1))//2 + before*k
    ans%=mod

print(ans)

Submission status: Accepted

Solution code:
N,K=[int(i) for i in input().split(" ")]
A=[int(i) for i in input().split(" ")]


inside=0
for i in range(N):
    for j in range(i,N):
        if A[i]>A[j]:
            inside+=1

outside=0
for i in range(N):
    for j in range(N):
        if A[i]>A[j]:
            outside+=1

s=inside*K+outside*((K*(K-1))//2)

print(s%(10**9+7))

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
a=list(map(int,input().split()))
ato=[]
zen=[]
for i in range(n):
    now=a[i]
    temp=0
    if(i!=n-1):
        for j in range(i+1,n):
            if(now>a[j]):
                temp+=1
    ato.append(temp)
    temp=0
    for j in range(n):
        if(a[j]>a[i]):
            temp+=1
    zen.append(temp)

#print(ato)
#print(zen)

ans=0
p=10**9+7
for i in range(n):
    ans+=(ato[i]*2+(k-1)*zen[i])*k//2
    ans=ans%p
print(ans%p)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
A = [int(a) for a in input().split()]

ca_inner = 0
ca_outer = 0
for i in range(N):
    for j in range(N):
        if A[i] > A[j]:
            ca_outer += 1
            if i < j:
                ca_inner += 1

ca_inner *= K
ca_outer *= (K - 1) * K // 2

print((ca_inner + ca_outer) % (10**9 + 7))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
def solve():
    N,K = map(int, input().split())
    *A, = map(int, input().split())
    L = [0 for i in range(2001)]
    invertion = 0
    for a in A:
        invertion += sum(L[a+1:])
        L[a]+=1
    res = (K*invertion + sum(sum(L[a+1:])*(K*(K-1)//2) for a in A))%(10**9+7)

    return str(res)

if __name__ == '__main__':
    print(solve())

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
a=list(map(int,input().split()))
mod=10**9+7
No=2**12
tree=[0]*(2*No)
ans=0
def add(k,x):
    k+=No-1
    while k>=0:
        tree[k]+=x
        k=(k-1)//2
def query(l,r):
    L=l+No-1
    R=r+No-1
    s=0
    while L<=R:
        if R&1:
            s+=tree[R]
            R-=2
        else:
            R-=1
        if L&1:
            L-=1
        else:
            s+=tree[L]
        L>>=1;R>>=1
    return s
for i in a:
    ans+=query(i+1,2001)
    ans%=mod
    add(i,1)
import collections
c=collections.Counter(a)
l=sorted(c.items())
t=l[0][1]
ans*=k
ans%=mod
for i,j in l[1:]:
    ans+=j*t*k*(k-1)//2
    ans%=mod
    t+=j
print(ans)

Submission status: Accepted

Solution code:
from sys import stdout
printn = lambda x: stdout.write(x)
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split())
DBG = True # and False
BIG = 999999999
R = 10**9 + 7

def ddprint(x):
  if DBG:
    print(x)

n,k = inm()
a = inl()
x = 0
for i in range(n-1):
    for j in range(i+1,n):
        if a[i]>a[j]:
            x += 1
y = 0
for i in range(n):
    for j in range(n):
        if a[i]>a[j]:
            y += 1
print((k*x+k*(k-1)*y//2)%R)

Submission status: Accepted

Solution code:
import bisect

n, k = map(int,input().split())
a = list(map(int,input().split()))

z = [0 for i in range(n)]
r = [0 for i in range(n)]

s = []
for i in range(len(a)):
    idx = bisect.bisect_left(s,a[len(a)-1-i])
    r[len(a)-1-i] = idx
    s.insert(idx,a[len(a)-1-i])
for i in range(n):
    z[i] = bisect.bisect_left(s,a[i])

l = [0 for i in range(n)]
ans = 0
for i in range(n):
    ans += r[i] * k * (k+1) // 2
    l[i] = z[i] - r[i]
    ans += l[i] * k * (k-1) // 2
print(ans%(10**9+7))

Submission status: Accepted

Solution code:
N,K = map(int,input().split())
*A, = map(int,input().split())

mod = 10**9+7

ans = 0
for i in range(N):
    for j in range(i+1,N):
        if A[i]>A[j]:
            ans += 1
            ans %= mod
ans = ans*K%mod
C = {}
for a in A:
    C[a] = C.get(a,0)+1
C2 = [N-C[a] for a in A]
ans2 = K*(K-1)*sum(C2)//4%mod
ans = (ans+ans2)%mod
print(ans)

Submission status: Accepted

Solution code:
MOD = 10**9 + 7

n,k = (int(num) for num in input().split())
a = [int(num) for num in input().split()]
cnt_in = 0
for i in range(n):
    for j in range(i+1,n):
        if a[i] > a[j]:
            cnt_in += 1
dic = {}
for num in a:
    if num not in dic.keys():
        dic[num] = 1
    else:
        dic[num] += 1

        
dic = sorted(dic.items(), key = lambda x:x[0])
#print(dic)
cnt_out = 0
v = [item[1] for item in dic]

lv = len(v)
for i in range(lv):
    for j in range(i+1,lv):
        cnt_out += v[i] * v[j]
        
ans = int(cnt_in*k + k*(k-1)//2*cnt_out) % MOD
print(ans)

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
a=list(map(int,input().split()))
me=0 # Aの中の転倒数
right=0 # 自分より右に並んだAの中にある転倒数
for i in range(len(a)):
  for j in range(len(a)):
    if i==j:#自分同士は比較しない
      continue
    elif a[i]>a[j]:#a[i]のほうが大きい時
      right=right+1
      if i<j:
        me=me+1

total=me*k+right*(((k-1)*k)//2)
print(total%(10**9+7))

Submission status: Accepted

Solution code:

N,K = map(int,input().split())

A = list(map(int,input().split()))

ans = 0
oneloop = 0
base = [0] * 2001

num = [0] * 2001


for i in range(N):

    na = A[i]

    oneloop += num[na]

    for j in range(na):

        num[j] += 1


ans += oneloop * K

#print (oneloop)


for i in range(N):

    na = A[i]
    ans = ( ans + num[na] * K * (K-1) // 2 ) % (10 ** 9 + 7)

print (ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
D = 10**9+7

N, K = map(int, input().split())
A = list(map(int, input().split()))

afters = [0]*N
alls = [0]*N

for i, key in enumerate(A):
    for j, a in enumerate(A):
        if a < key:
            alls[i] += 1
            if j > i:
                afters[i] += 1

ans = sum(afters)*K + sum(alls)*K*(K-1)//2
print(ans % D)

Submission status: Accepted

Solution code:
import itertools

MOD = 10 ** 9 + 7

N, K = map(int, input().split())
a_list = list(map(int, input().split()))

ans = 0
for i in range(N - 1):
    for j in range(i + 1, N):
        if a_list[i] > a_list[j]:
            ans += K

counts = [0] * 2000
for a in a_list:
    a -= 1
    counts[a] += 1

accum = list(itertools.accumulate(counts))
for a in a_list:
    a -= 1
    if a == 0:
        continue
    ans += accum[a - 1] * K * (K - 1) // 2
    ans %= MOD
print(ans)

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
A=list(map(int,input().split()))
v=[[0]*N for i in range(2)]
for i,a in enumerate(A):
    for j,aa in enumerate(A):
        if a>aa:
            if i<j:
                v[0][i]+=1
            elif i>j:
                v[1][i]+=1
r=0
m=10**9+7
for i in range(N):
    r+=((v[0][i]*K*(K+1)//2)%m+(v[1][i]*K*(K-1)//2)%m)%m
print(r%m)

Submission status: Accepted

Solution code:
words = lambda t : list(map(t, input().split()))
n,k = words(int)
a = words(int)

accum = [0] * n
adding = [0] * n

for i in range(n-1):
    for j in range(i,n):
        if a[i] > a[j]:
            adding[i] += 1

for i in range(n):
    for j in range(n):
        if a[i] > a[j]:
            accum[i] += 1

MOD = 10**9 + 7
sum_accum = sum(accum)
sum_adding = sum(adding)
ans = 0

ans = (((k-1) * k) // 2) * sum_accum + k * sum_adding
ans %= MOD
'''
for i in range(k):
    ans += sum_accum * i + sum_adding
    ans %= MOD
'''
print(ans)

Submission status: Accepted

Solution code:
MOD = 10 ** 9 + 7

n,k = map(int,input().split())
a = list(map(int,input().split()))

incount = 0
for i in range(n-1):
    for j in range(i+1,n):
        if a[i] > a[j]:
            incount += 1

#print(incount)

out = 0

for p in range(n):
    for q in range(n):
        if a[p] < a[q]:
            out += 1

#print(out)

outcount = out * (k * (k-1)) //2

print((incount * k + outcount) % MOD)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
ModNum = (10**9)+7

def main():
    N,K = map(int,input().split())
    A = [int(a) for a in input().split()]
    inversion_in_L = [0]*N
    inversion_in_R = [0]*N
    for i in range(N):
        for j in range(N):
            if j<i and A[j]>A[i]:
                inversion_in_L[i] += 1
            elif i<j and A[j]>A[i]:
                inversion_in_R[i] += 1
    ans = 0
    for i in range(N):
        ans += (K-1)*K*inversion_in_R[i]//2
        ans %= ModNum
        ans += (K+1)*K*inversion_in_L[i]//2
        ans %= ModNum

    print(ans)



if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
N,K = map(int,input().split(' '))
A = list(map(int,input().split(' ')))
MOD = 10**9 + 7

inv2 = pow(2,MOD-2,MOD)

right = 0
left = 0
for i in range(N):
	for j in range(i+1,N):
		if A[i] < A[j]:
			right += 1
		elif A[j] < A[i]:
			left += 1

M1 = (((K*(K-1) % MOD)*inv2) % MOD) + K
M2 = ((K*(K-1) % MOD) * inv2) % MOD

ans = (M1*left + M2 * right) % MOD
print(ans)

Submission status: Accepted

Solution code:
import sys

lines = sys.stdin.readlines()
parts = lines[0].split(' ')
n = int(parts[0])
k = int(parts[1])
arr = [int(s) for s in lines[1].strip().split()]

ans = 0
mod = 1000000007

for i in range(n):
    in_arr = 0
    all_arr = 0
    for j in range(n):
        if arr[i] > arr[j]:
            all_arr += 1
            if j > i:
                in_arr += 1

    ans += in_arr * k + all_arr * (k - 1) * (k) // 2
    ans %= mod

print(ans)

Submission status: Accepted

Solution code:
N,K = map(int,input().split())
A = list(map(int,input().split()))
MOD = 10**9+7
ans = 0
for i in range(N):
    for j in range(i,N):
        if A[i]<A[j]:
            ans = (ans + K*(K-1)//2)%MOD
        if A[i]>A[j]:
            ans = (ans + K*(K+1)//2)%MOD
print(ans)