PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#CC0000024. Tổng vị trí sau khi ghép hai tập (Merge Sets)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

2 lộ trình

Tổng vị trí sau khi ghép hai tập (Merge Sets)

Merge Sets

Source: AtCoder

Version: Phuoc Hung OJ Extended

Problem Statement

There are nn integer sets S1,…,SnS_1,\ldots,S_n, each with exactly mm elements. All elements across all sets are distinct. For two sets A,BA,B, merge their elements and sort them increasingly into sequence CC. Define f(A,B)f(A,B) as the sum of 1-based positions of elements from AA in CC. Find ∑1≤i<j≤nf(Si,Sj)\sum_{1\le i<j\le n} f(S_i,S_j).

Input

The first line contains integers n,mn,m. Each of the following nn lines contains the mm elements ai,1,…,ai,ma_{i,1},\ldots,a_{i,m} of set SiS_i. Elements within a line need not be sorted.

Output

Print one 64-bit integer: the total ∑1≤i<j≤nf(Si,Sj)\sum_{1\le i<j\le n} f(S_i,S_j).

Subtasks

  • Subtask 1 (20 points): 1≤n≤41\le n\le 4; 1≤m≤51\le m\le 5; 1≤ai,j≤1091\le a_{i,j}\le 10^9 for all i,ji,j; all ai,ja_{i,j} across all nn sets are pairwise distinct.
  • Subtask 2 (30 points): 1≤n≤801\le n\le 80; 1≤m≤251\le m\le 25; 1≤ai,j≤1091\le a_{i,j}\le 10^9 for all i,ji,j; all ai,ja_{i,j} across all nn sets are pairwise distinct.
  • Subtask 3 (50 points): 1≤n≤100001\le n\le 10000; 1≤m≤1001\le m\le 100; 1≤ai,j≤1091\le a_{i,j}\le 10^9 for all i,ji,j; all ai,ja_{i,j} across all nn sets are pairwise distinct.

Examples

Input

3 2
1 3
2 8
4 6

Output

12

Explanation

For (S1,S2)(S_1,S_2), the merged sorted values are (1,2,3,8)(1,2,3,8); the first set occupies positions 11 and 33, contributing 44. For (S1,S3)(S_1,S_3), the sorted values are (1,3,4,6)(1,3,4,6) and the contribution is 1+2=31+2=3. For (S2,S3)(S_2,S_3), positions 11 and 44 contribute 55. The total is 4+3+5=124+3+5=12.