80-th Level Archeology (Codeforces 731D)
Tags: Greedy, sortings

Archeologists have found a secret pass in the dungeon of one of the pyramids of Cycleland. To enter the treasury they have to open an unusual lock on the door. The lock consists of n words, each consisting of some hieroglyphs. The wall near the lock has a round switch. Each rotation of this switch changes the hieroglyphs according to some rules. The instruction nearby says that the door will open only if words written on the lock would be sorted in lexicographical order (the definition of lexicographical comparison in given in notes section).The rule that changes hieroglyphs is the following. One clockwise rotation of the round switch replaces each hieroglyph with the next hieroglyph in alphabet, i.e. hieroglyph x (1 ≤ x ≤ c - 1) is replaced with hieroglyph (x + 1), and hieroglyph c is replaced with hieroglyph 1.Help archeologist determine, how many clockwise rotations they should perform in order to open the door, or determine that this is impossible, i.e. no cyclic shift of the alphabet will make the sequence of words sorted lexicographically.

Input: The first line of the input contains two integers n and c (2 ≤ n ≤ 500 000, 1 ≤ c ≤ 106) — the number of words, written on the lock, and the number of different hieroglyphs.Each of the following n lines contains the description of one word. The i-th of these lines starts with integer li (1 ≤ li ≤ 500 000), that denotes the length of the i-th word, followed by li integers wi, 1, wi, 2, ..., wi, li (1 ≤ wi, j ≤ c) — the indices of hieroglyphs that make up the i-th word. Hieroglyph with index 1 is the smallest in the alphabet and with index c — the biggest.It's guaranteed, that the total length of all words doesn't exceed 106.

Output: If it is possible to open the door by rotating the round switch, print integer x (0 ≤ x ≤ c - 1) that defines the required number of clockwise rotations. If there are several valid x, print any of them.If it is impossible to open the door by this method, print  - 1.

Note: Word a1, a2, ..., am of length m is lexicographically not greater than word b1, b2, ..., bk of length k, if one of two conditions hold:   at first position i, such that ai ≠ bi, the character ai goes earlier in the alphabet than character bi, i.e. a has smaller character in the first position where they differ;  if there is no such position i and m ≤ k, i.e. the first word is a prefix of the second or two words are equal. The sequence of words is said to be sorted in lexicographical order if each word (except the last one) is lexicographically not greater than the next word.In the first sample, after the round switch is rotated 1 position clockwise the words look as follows:1 323 1 23 1 2 3In the second sample, words are already sorted in lexicographical order.In the last sample, one can check that no shift of the alphabet will work.

Sample Inputs:
4 3
2 3 2
1 1
3 2 3 1
4 2 3 1 2

2 5
2 4 2
2 4 2

4 4
1 2
1 3
1 4
1 2

Sample Outputs:
1

0

-1

Solution (Python):
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
(n, c) = map(int, input().split())
w1 = list(map(int, input().split()))[1:]
ng = [0] * (c + 1)
ok = 1
for _ in range(n - 1):
    w2 = list(map(int, input().split()))[1:]
    f = 0
    for (i, j) in zip(w1, w2):
        if i < j:
            l = c - j + 1
            r = l + (j - i) % c
            ng[l] += 1
            ng[r] -= 1
            f = 1
            break
        elif i > j:
            l = c - i + 1
            r = l + (i - j) % c
            ng[0] += 1
            ng[l] -= 1
            ng[r] += 1
            f = 1
            break
    if not f and len(w1) > len(w2):
        ok = 0
    w1 = w2
ans = -1
if ok:
    for i in range(1, c + 1):
        ng[i] += ng[i - 1]
        if not ng[i]:
            ans = i
            break
    if not ng[0]:
        ans = 0
print(ans)

Solution (Python):
import sys
readline = sys.stdin.readline
(N, C) = map(int, readline().split())
imos = [0] * (C + 1)
W = [None] * N
for i in range(N):
    (L, *W[i]) = map(int, readline().split())
    for j in range(L):
        W[i][j] -= 1
cnt = 0
for i in range(N - 1):
    for (a, b) in zip(W[i], W[i + 1]):
        if a < b:
            imos[0] += 1
            imos[C - b] -= 1
            imos[C - a] += 1
            imos[C] -= 1
            cnt += 1
            break
        elif a > b:
            imos[C - a] += 1
            imos[C - b] -= 1
            cnt += 1
            break
    else:
        if len(W[i]) > len(W[i + 1]):
            print(-1)
            exit()
for i in range(1, C + 1):
    imos[i] += imos[i - 1]
ans = -1
for i in range(C):
    if imos[i] == cnt:
        ans = i
print(ans)

Solution (Python):
import sys
readline = sys.stdin.readline
(N, C) = map(int, readline().split())
imos = [0] * (C + 1)
W = [None] * N
for i in range(N):
    (L, *W[i]) = map(int, readline().split())
    for j in range(L):
        W[i][j] -= 1
cnt = 0
for i in range(N - 1):
    for (a, b) in zip(W[i], W[i + 1]):
        if a < b:
            imos[0] += 1
            imos[C - b] -= 1
            imos[C - a] += 1
            imos[C] -= 1
            cnt += 1
            break
        elif a > b:
            imos[C - a] += 1
            imos[C - b] -= 1
            cnt += 1
            break
    else:
        if len(W[i]) > len(W[i + 1]):
            print(-1)
            exit()
for i in range(1, C + 1):
    imos[i] += imos[i - 1]
ans = -1
for i in range(C):
    if imos[i] == cnt:
        ans = i
print(ans)