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

#BS0000465. Đoạn hành trình chung dài nhất (Longest Common Subpath)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Đoạn hành trình chung dài nhất (Longest Common Subpath)

Longest Common Subpath

Source: LeetCode

Version: Phuoc Hung OJ Extended

Problem Statement

A country has nn cities numbered from 00 to n−1n-1, with a road between every pair of distinct cities. There are mm friends traveling through the country. Friend ii (1≤i≤m1\le i\le m) visits the ordered sequence ai,1,…,ai,lia_{i,1},\ldots,a_{i,l_i} of lil_i cities. A city may be visited repeatedly, but two consecutive visits cannot be to the same city.

A subpath is a contiguous block of a path. Two blocks are equal if their lengths and corresponding city numbers match. Find the maximum length of a block occurring in every one of the mm paths. The starting positions may differ between paths.

Input

The first line contains integers n,mn,m, the numbers of cities and friends.

Each of the next mm lines contains lil_i followed by exactly lil_i integers ai,1,…,ai,lia_{i,1},\ldots,a_{i,l_i} describing path ii.

Output

Print the maximum length of a common subpath, or 00 if no nonempty common subpath exists.

Subtasks

  • Subtask 1 (20 points): 1≤n≤1051\le n\le 10^5; 2≤m≤1052\le m\le 10^5; 1≤li≤1051\le l_i\le 10^5; ∑i=1mli≤80\sum_{i=1}^m l_i\le 80; 0≤ai,j<n0\le a_{i,j}<n; ai,j≠ai,j+1a_{i,j}\ne a_{i,j+1} for all 1≤i≤m1\le i\le m, with 1≤j≤li1\le j\le l_i for city bounds and 1≤j<li1\le j<l_i for the adjacent-city condition.
  • Subtask 2 (30 points): 1≤n≤1051\le n\le 10^5; 2≤m≤1052\le m\le 10^5; 1≤li≤1051\le l_i\le 10^5; ∑i=1mli≤2000\sum_{i=1}^m l_i\le 2000; 0≤ai,j<n0\le a_{i,j}<n; ai,j≠ai,j+1a_{i,j}\ne a_{i,j+1} for all 1≤i≤m1\le i\le m, with 1≤j≤li1\le j\le l_i for city bounds and 1≤j<li1\le j<l_i for the adjacent-city condition.
  • Subtask 3 (50 points): 1≤n≤1051\le n\le 10^5; 2≤m≤1052\le m\le 10^5; 1≤li≤1051\le l_i\le 10^5; ∑i=1mli≤100000\sum_{i=1}^m l_i\le 100000; 0≤ai,j<n0\le a_{i,j}<n; ai,j≠ai,j+1a_{i,j}\ne a_{i,j+1} for all 1≤i≤m1\le i\le m, with 1≤j≤li1\le j\le l_i for city bounds and 1≤j<li1\le j<l_i for the adjacent-city condition.

Examples

Input

5 3
5 0 1 2 3 4
3 2 3 4
5 4 0 1 2 3

Output

2

Explanation

The block (2,3)(2,3) occurs in all three paths. A common block of length 33 would have to be the entire second path (2,3,4)(2,3,4), which is absent from the third path. Thus 22 is optimal.

Input

3 3
1 0
1 1
1 2

Output

0

Explanation

The three friends visit only cities 00, 11, 22, respectively. No city is common to all three paths, so the answer is 00.

Input

5 2
5 0 1 2 3 4
5 4 3 2 1 0

Output

1

Explanation

Every city occurs in both paths. All adjacent pairs in the first path increase by 11, while those in the second decrease by 11. No length-two common block exists, so the answer is 11.