This page is still under construction.

Parts of this page are still being built. What you see may change.

Sport Clubs

Time limit1sMemory limit128 MB

Summary
Given k partial rankings of n teams, find the permutation of all n teams minimizing the total L1 distance to all the league point vectors.
Level

Medium7 of 10

Topics
Greedy, Sorting, Math, Implementation
Solved
No attempts yet

Problem

The most popular sport in Byteland is BitBall. Many Bytelandian cities organize BitBall leagues every year. Each BitBall team may take part in any number of leagues, no matter who organizes a league. At the end of the season all results are summarized. Each league publishes its own ranking list, which orders the teams that took part in that league. Based on these ranking lists, the The Best BitBaller magazine determines and publishes the super ranking list of all BitBall teams.

Determining the super ranking list is not easy. It is computed under the following rules. If a team took mm-th place on a ranking list that consists of ll positions, then the number of points this team scored equals l+1−ml + 1 - m. If the team did not take part in a league at all, it receives 00 points there. The distance between two ranking lists is computed as follows: for each team we take the absolute value of the difference between the points the team scored on the two lists, and we sum these values over all teams. The super ranking list to be determined is the one whose total distance from all the league ranking lists is minimal.

The super ranking list orders all nn teams, so it has nn positions; a team placed mm-th on it scores n+1−mn + 1 - m points.

Write a program which:

  • reads the description of the ranking lists of all BitBall leagues from standard input,
  • determines the super ranking list for the The Best BitBaller magazine,
  • writes the total distance of the super ranking list to standard output.

Input

The first line contains two integers nn and kk (2≤n≤5002 \le n \le 500, 1≤k≤5001 \le k \le 500), separated by a single space: the number of teams and the number of leagues.

Each of the next kk lines describes one league. A description starts with an integer mm (2≤m≤n2 \le m \le n), the number of teams in that league, followed by mm integers l1,l2,…,lml_1, l_2, \dots, l_m (1≤li≤n1 \le l_i \le n). The values lil_i are pairwise distinct; lil_i is the team that took ii-th place in that league's ranking list. All numbers on a line are separated by single spaces.

Output

Print a single integer: the minimum possible total distance of the super ranking list, that is, the sum of its distances to all the league ranking lists.

Examples3

  1. Example 1

    Input
    4 2
    3 1 2 3
    2 4 3
    
    Expected output
    11
    
  2. Example 2

    Input
    2 1
    2 1 2
    
    Expected output
    0
    
  3. Example 3

    Input
    3 2
    3 1 2 3
    3 3 2 1
    
    Expected output
    4