#BS0000465. Đoạn hành trình chung dài nhất (Longest Common Subpath)
Bài tập thuộc lộ trình
Mục lục đề ⌄
Đ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 cities numbered from to , with a road between every pair of distinct cities. There are friends traveling through the country. Friend () visits the ordered sequence of 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 paths. The starting positions may differ between paths.
Input
The first line contains integers , the numbers of cities and friends.
Each of the next lines contains followed by exactly integers describing path .
Output
Print the maximum length of a common subpath, or if no nonempty common subpath exists.
Subtasks
- Subtask 1 (20 points): ; ; ; ; ; for all , with for city bounds and for the adjacent-city condition.
- Subtask 2 (30 points): ; ; ; ; ; for all , with for city bounds and for the adjacent-city condition.
- Subtask 3 (50 points): ; ; ; ; ; for all , with for city bounds and 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 occurs in all three paths. A common block of length would have to be the entire second path , which is absent from the third path. Thus is optimal.
Input
3 3
1 0
1 1
1 2
Output
0
Explanation
The three friends visit only cities , , , respectively. No city is common to all three paths, so the answer is .
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 , while those in the second decrease by . No length-two common block exists, so the answer is .