Problem:


シャッフル  

問題

1 から n までの番号が書かれた n 枚のカードがある．まず，一番上が番号 1 のカード，上から2枚目が番号 2 のカード，…，一番下が番号 n のカードとなるように順番に重ねて，カードの山を作る．

カードの山に対して，「シャッフル(x,y)」と呼ばれる次のような操作を行うことで，カードを並び替える（x, y は 1 ≤ x < y < n をみたす整数）．

シャッフル(x,y)

    n 枚のカードを，一番上から x 枚目までのカードからなる山A， x+1 枚目から y 枚目のカードからなる山B， y+1 枚目から n 枚目のカードからなる山C の3つの山に分ける．そして，山Aの上に山Bを重ね，さらにその上に山Cを重ねる． 

例えば，順番に並んでいる9枚のカードに対して「シャッフル(3,5)」を行うと， 9 枚のカードに書かれた番号は, 上から順番に 6, 7, 8, 9, 4, 5, 1, 2, 3 となる． 

最初の山の状態から m 回のシャッフル「シャッフル(x1, y1)」「シャッフル(x2, y2)」 … 「シャッフル(xm, ym)」を順番に行った後のカードの山において，上から数えて p 枚目から q 枚目のカードの中に番号が r 以下のカードが何枚含まれているかを求めるプログラムを作成せよ．

入力

入力は複数のデータセットからなる．各データセットは以下の形式で与えられる．

入力は m+3 行からなる． 1 行目にはカードの枚数 n が書かれている（3 ≤ n ≤ 1000000000 = 109）． 2 行目にはシャッフルの回数を表す整数 m が書かれている（1 ≤ m ≤ 5000）． 3 行目には整数 p, q, r が書かれている（1 ≤ p ≤ q ≤ n, 1 ≤ r ≤ n）． i + 3 行目（1 ≤ i ≤ m）には2つの整数 xi, yi (1 ≤ xi < yi < n) が空白を区切りとして書かれている．

n が 0 のとき入力の終了を示す. データセットの数は 5 を超えない．

出力

データセットごとに, m 回のシャッフル後のカードの山において，上から数えて p 枚目から q 枚目のカードの中に含まれている番号が r 以下のカードの枚数を１行に出力せよ．

入出力例

入力例

9
1
3 7 4
3 5
12
3
3 8 5
3 8
2 5
6 10
0

出力例

2
3

1つ目の入力例の山に対して, 「シャッフル(3,5)」を行うと，カードは上から順番に 6, 7, 8, 9, 4, 5, 1, 2, 3 となる．上から数えて 3 枚目から 7 枚目に含まれる番号が 4 以下のカードは，番号 4 と番号 1 の 2 枚である．

また，2つ目の入力例の山に対して, 「シャッフル(3,8)」「シャッフル(2,5)」「シャッフル(6,10)」を順番に行うと，カードは上から順番に 9, 10, 3, 11, 12, 4, 5, 6, 7, 8, 1, 2 となる．上から数えて 3 枚目から 8 枚目に含まれる番号が 5 以下のカードは 3 枚である．

上記問題文と自動審判に使われるデータは、情報オリンピック日本委員会が作成し公開している問題文と採点用テストデータです。



Sample input:
9
1
3 7 4
3 5
12
3
3 8 5
3 8
2 5
6 10
0


Sample output:
2
3

Submission status: Time Limit Exceeded

Solution code:
def shuffle(deck,x,y):
    cnter = 0
    i = 0
    sectiona = []
    while (cnter < x):
        nextsize = deck[i][1] - deck[i][0] + 1
        if(x-cnter >= nextsize):
            sectiona.append(deck[i])
            cnter += nextsize
            i += 1
        else:
            sectiona.append([deck[i][0],deck[i][0] + x-cnter - 1])
            deck[i][0] = deck[i][0] + x-cnter
            cnter = x

    sectionb = []
    while (cnter < y):
        nextsize = deck[i][1] - deck[i][0] + 1
        if(y-cnter >= nextsize):
            sectionb.append(deck[i])
            cnter += nextsize
            i += 1
        else:
            sectionb.append([deck[i][0],deck[i][0] + y-cnter - 1])
            deck[i][0] = deck[i][0] + y-cnter
            cnter = y

    newdeck = deck[i:] + sectionb + sectiona
    return newdeck

def hitnum(a,r):
    if a[1] <= r:
        return a[1]-a[0]+1
    elif a[0] <= r:
        return r-a[0]+1
    else:
        return 0

while True:
    n = int(input())
    if n==0: break
    deck = [[1,n]]
    m = int(input())

    p,q,r = map(int,input().split())

    for i in range(m):
        x,y = map(int,input().split())
        deck = shuffle(deck, x, y)
    deck = shuffle(deck,0,p-1)

    answer = 0
    cnter = 0
    i = 0
    while (cnter < q-p+1):
        nextsize = deck[i][1] - deck[i][0] + 1
        if(q-p+1-cnter >= nextsize):
            answer += hitnum(deck[i],r)
            cnter += nextsize
            i += 1
        else:
            answer += hitnum([deck[i][0],deck[i][0] + q-p+1-cnter - 1],r)
            deck[i][0] = deck[i][0] + q-p+1-cnter
            cnter = q-p+1

    print(answer)

Submission status: Time Limit Exceeded

Solution code:
def shuffle(deck,x,y):
    cnter = 0
    i = 0
    sectiona = sectionb = []
    while (cnter < x):
        nextsize = deck[i][1] - deck[i][0] + 1
        if(x-cnter >= nextsize):
            cnter += nextsize
            i += 1
        else:
            sectiona = [[deck[i][0],deck[i][0] + x-cnter - 1]]
            deck[i][0] = deck[i][0] + x-cnter
            cnter = x
    memoa = i
    while (cnter < y):
        nextsize = deck[i][1] - deck[i][0] + 1
        if(y-cnter >= nextsize):
            cnter += nextsize
            i += 1
        else:
            sectionb = [[deck[i][0],deck[i][0] + y-cnter - 1]]
            deck[i][0] = deck[i][0] + y-cnter
            cnter = y

    newdeck = deck[i:] + deck[memoa:i] + sectionb + deck[0:memoa] + sectiona
    return newdeck

def hitnum(a,r):
    if a[1] <= r:
        return a[1]-a[0]+1
    elif a[0] <= r:
        return r-a[0]+1
    else:
        return 0

while True:
    n = int(input())
    if n==0: break
    deck = [[1,n]]
    m = int(input())

    p,q,r = map(int,input().split())

    for i in range(m):
        x,y = map(int,input().split())
        deck = shuffle(deck, x, y)

    deck = shuffle(deck,0,p-1)

    answer = 0
    cnter = 0
    i = 0
    while (cnter < q-p+1):
        nextsize = deck[i][1] - deck[i][0] + 1
        if(q-p+1-cnter >= nextsize):
            answer += hitnum(deck[i],r)
            cnter += nextsize
            i += 1
        else:
            answer += hitnum([deck[i][0],deck[i][0] + q-p+1-cnter - 1],r)
            deck[i][0] = deck[i][0] + q-p+1-cnter
            cnter = q-p+1

    print(answer)

Submission status: Time Limit Exceeded

Solution code:


def shuffle(deck,x,y):
    cnter = 0
    i = 0
    sectiona = [0,0]
    sectionb = [0,0]
    while (cnter < x):
        nextsize = deck[i][1] - deck[i][0] + 1
        if(x-cnter >= nextsize):
            cnter += nextsize
            i += 1
        else:
            sectiona[0] = deck[i][0]
            sectiona[1] = deck[i][0] + x-cnter - 1
            deck[i][0] = deck[i][0] + x-cnter
            cnter = x
    memoa = i
    while (cnter < y):
        nextsize = deck[i][1] - deck[i][0] + 1
        if(y-cnter >= nextsize):
            cnter += nextsize
            i += 1
        else:
            sectionb[0] = deck[i][0]
            sectionb[1] = deck[i][0] + y-cnter - 1
            deck[i][0] = deck[i][0] + y-cnter
            cnter = y

    # + is too slow
    newdeck =deck[i:]
    newdeck.extend(deck[memoa:i])
    if sectionb[1]:
        newdeck.append(sectionb)
    newdeck.extend(deck[0:memoa])
    if sectiona[1]:
        newdeck.append(sectiona)
    return newdeck

def hitnum(a,r):
    if a[1] <= r:
        return a[1]-a[0]+1
    elif a[0] <= r:
        return r-a[0]+1
    else:
        return 0

while True:
    n = int(input())
    if n==0: break
    deck = [[1,n]]
    m = int(input())

    p,q,r = map(int,input().split())

    for i in range(m):
        x,y = map(int,input().split())
        deck = shuffle(deck, x, y)

    deck = shuffle(deck,0,p-1)

    answer = 0
    cnter = 0
    i = 0
    while (cnter < q-p+1):
        nextsize = deck[i][1] - deck[i][0] + 1
        if(q-p+1-cnter >= nextsize):
            answer += hitnum(deck[i],r)
            cnter += nextsize
            i += 1
        else:
            answer += hitnum([deck[i][0],deck[i][0] + q-p+1-cnter - 1],r)
            deck[i][0] = deck[i][0] + q-p+1-cnter
            cnter = q-p+1

    print(answer)

Submission status: Time Limit Exceeded

Solution code:
while True:
  n = int(input())
  if not n: break
  m = int(input())
  p, q, r = map(int,input().split())
  S = [[1,n]] #init,last

  for i in range(m):
    x,y = map(int,input().split())
    ix = iy = 0
    dx = dy = 0
    c = 0
    for j in range(len(S)):
      temp = c + (S[j][1] - S[j][0]) + 1 
      if not dx and temp >= x:
        ix = j
        dx = x - c
      if temp > y:
        iy = j
        dy = y - c
        break
      c = temp

    X = S[ix][0]
    Y = S[iy][0]
    if ix == iy:
      S = [[Y + dy, S[iy][1]]] + S[iy + 1:] + [[X + dx , Y + dy - 1]] + S[:ix] + [[X, X + dx - 1]]
    else:
      S = [[Y + dy, S[iy][1]]] + S[iy + 1:] + [[X + dx, S[ix][1]]] + S[ix + 1 : iy] + [[Y, Y + dy - 1]] + S[:ix] +  [[X, X + dx - 1]]
  
  count = 0
  ans = 0
  for section in S:
    l = section[1] - section[0] + 1
    if p <= count + l and count + l <= q:
      if r < section[0]: pass
      elif section[0] <= r and r < section[1]:
        ans += (r - section[0] + 1)
      elif section[1] <= r:
        ans += l
    elif p <= count + l and q < count + l:
      if r < section[0]: pass
      elif section[0] <= r and r < section[1]:
        ans += min(r - section[0] + 1, q - count)
      elif section[1] <= r:
        ans += (q - count)
      break
    count += l
  print(ans)

Submission status: Time Limit Exceeded

Solution code:
while True:
  n = int(input())
  if not n: break
  m = int(input())
  p, q, r = map(int,input().split())
  S = [(1,n)]

  for i in range(m):
    x,y = map(int,input().split())
    ix = iy = 0
    dx = dy = 0
    c = 0
    for j in range(len(S)):
      temp = c + (S[j][1] - S[j][0]) + 1 
      if not dx and temp >= x:
        ix = j
        dx = x - c
      if temp > y:
        iy = j
        dy = y - c
        break
      c = temp

    X = S[ix][0]
    Y = S[iy][0]
    if ix == iy:
      S1 =  [(Y + dy, S[iy][1])]
      extend = S1.extend
      append = S1.append
      extend(S[iy + 1:])
      append((X + dx , Y + dy - 1))
      extend(S[:ix])
      append((X, X + dx - 1))
      S = S1
    else:
      S1 = [(Y + dy, S[iy][1])] 
      extend = S1.extend
      append = S1.append
      extend(S[iy + 1:])
      append((X + dx, S[ix][1]))
      extend(S[ix + 1 : iy])
      append((Y, Y + dy - 1))
      extend(S[:ix])
      append((X, X + dx - 1))
      S = S1
  
  count = 0
  ans = 0
  for section in S:
    l = section[1] - section[0] + 1
    if p <= count + l and count + l <= q:
      if r < section[0]: pass
      elif section[0] <= r and r < section[1]:
        ans += (r - section[0] + 1)
      elif section[1] <= r:
        ans += l
    elif p <= count + l and q < count + l:
      if r < section[0]: pass
      elif section[0] <= r and r < section[1]:
        ans += min(r - section[0] + 1, q - count)
      elif section[1] <= r:
        ans += (q - count)
      break
    count += l
  print(ans)

Submission status: Time Limit Exceeded

Solution code:
for e in iter(input, '0'):
    n = int(e)
    Cards = [(n, 1, n)]
    m = int(input())
    p, q, r = map(int, input().split())
    for _ in [0] * m:
        x, y = map(int, input().split())
        total = 0
        A, B, C = [], [], []
        for k, s, t in Cards:
            if y < total + k:
                if total < y:
                    C += [(total + k - y, s + y - total, t)]
                    if total < x:
                        B += [(y - x, s + x - total, s + y - total - 1)]
                        A += [(x - total, s, s + x - total - 1)]
                    else:
                        B += [(y - total, s, s + y - total - 1)]
                else:
                    C += [(k, s, t)]
            elif x < total + k:
                if total < x:
                    B += [(total + k - x, s + x - total, t)]
                    A += [(x - total, s, s + x - total - 1)]
                else:
                    B += [(k, s, t)]
            else:
                A += [(k, s, t)]
            total += k
        Cards = C + B + A
    total = 0
    D = []
    p = p - 1
    for k, s, t in Cards:
        if q < total + k:
            if total < q:
                if total < p:
                    D += [(s + x - total, s + q - total - 1)]
                else:
                    D += [(s, s + q - total - 1)]
        elif p < total + k:
            if total < p:
                D += [(s + p - total, t)]
            else:
                D += [(s, t)]
        total += k
    ans = 0
    for s, t in D:
        if t < r:
            ans += t - s + 1
        elif s <= r <= t:
            ans += r - s + 1
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
def solve():
    for e in iter(input, '0'):
        n = int(e)
        Cards = [(n, 1, n)]
        m = int(input())
        p, q, r = map(int, input().split())
        for _ in [0] * m:
            x, y = map(int, input().split())
            total = 0
            A, B, C = [], [], []
            for k, s, t in Cards:
                if y < total + k:
                    if total < y:
                        C += [(total + k - y, s + y - total, t)]
                        if total < x:
                            B += [(y - x, s + x - total, s + y - total - 1)]
                            A += [(x - total, s, s + x - total - 1)]
                        else:
                            B += [(y - total, s, s + y - total - 1)]
                    else:
                        C += [(k, s, t)]
                elif x < total + k:
                    if total < x:
                        B += [(total + k - x, s + x - total, t)]
                        A += [(x - total, s, s + x - total - 1)]
                    else:
                        B += [(k, s, t)]
                else:
                    A += [(k, s, t)]
                total += k
            Cards = C + B + A
        total = 0
        D = []
        p = p - 1
        for k, s, t in Cards:
            if q < total + k:
                if total < q:
                    if total < p:
                        D += [(s + x - total, s + q - total - 1)]
                    else:
                        D += [(s, s + q - total - 1)]
            elif p < total + k:
                if total < p:
                    D += [(s + p - total, t)]
                else:
                    D += [(s, t)]
            total += k
        ans = 0
        for s, t in D:
            if t < r:
                ans += t - s + 1
            elif s <= r <= t:
                ans += r - s + 1
        print(ans)


if __name__ == '__main__':
    solve()

Submission status: Time Limit Exceeded

Solution code:
def solve():
    import sys
    read = sys.stdin.readline
    for e in iter(read, '0\n'):
        n = int(e)
        Cards = [(n, 1, n)]
        m = int(read())
        p, q, r = map(int, read().split())
        for _ in [0] * m:
            x, y = map(int, read().split())
            total = 0
            A, B, C = [], [], []
            for k, s, t in Cards:
                if y < total + k:
                    if total < y:
                        C += [(total + k - y, s + y - total, t)]
                        if total < x:
                            B += [(y - x, s + x - total, s + y - total - 1)]
                            A += [(x - total, s, s + x - total - 1)]
                        else:
                            B += [(y - total, s, s + y - total - 1)]
                    else:
                        C += [(k, s, t)]
                elif x < total + k:
                    if total < x:
                        B += [(total + k - x, s + x - total, t)]
                        A += [(x - total, s, s + x - total - 1)]
                    else:
                        B += [(k, s, t)]
                else:
                    A += [(k, s, t)]
                total += k
            Cards = C + B + A
        total = 0
        D = []
        p = p - 1
        for k, s, t in Cards:
            if q < total + k:
                if total < q:
                    if total < p:
                        D += [(s + x - total, s + q - total - 1)]
                    else:
                        D += [(s, s + q - total - 1)]
            elif p < total + k:
                if total < p:
                    D += [(s + p - total, t)]
                else:
                    D += [(s, t)]
            total += k
        ans = 0
        for s, t in D:
            if t < r:
                ans += t - s + 1
            elif s <= r <= t:
                ans += r - s + 1
        print(ans)


if __name__ == '__main__':
    solve()

Submission status: Time Limit Exceeded

Solution code:
def solve():
    import sys
    line = sys.stdin.readline
    for e in iter(line, '0\n'):
        n = int(e)
        Cards = [(n, 1, n)]
        m = int(line())
        p, q, r = map(int, line().split())
        for _ in range(m):
            x, y = map(int, line().split())
            total = 0
            A, B, C = [], [], []
            for k, s, t in Cards:
                if y < total + k:
                    if total < y:
                        C += [(total + k - y, s + y - total, t)]
                        if total < x:
                            B += [(y - x, s + x - total, s + y - total - 1)]
                            A += [(x - total, s, s + x - total - 1)]
                        else:
                            B += [(y - total, s, s + y - total - 1)]
                    else:
                        C += [(k, s, t)]
                elif x < total + k:
                    if total < x:
                        B += [(total + k - x, s + x - total, t)]
                        A += [(x - total, s, s + x - total - 1)]
                    else:
                        B += [(k, s, t)]
                else:
                    A += [(k, s, t)]
                total += k
            Cards = C + B + A
        total = 0
        D = []
        p = p - 1
        for k, s, t in Cards:
            if q < total + k:
                if total < q:
                    if total < p:
                        D += [(s + x - total, s + q - total - 1)]
                    else:
                        D += [(s, s + q - total - 1)]
            elif p < total + k:
                if total < p:
                    D += [(s + p - total, t)]
                else:
                    D += [(s, t)]
            total += k
        ans = 0
        for s, t in D:
            if t < r:
                ans += t - s + 1
            elif s <= r <= t:
                ans += r - s + 1
        print(ans)


if __name__ == '__main__':
    solve()

Submission status: Time Limit Exceeded

Solution code:
def solve():
    import sys
    line = sys.stdin.readline
    for e in iter(line, '0\n'):
        n = int(e)
        Cards = [(n, 1)]
        m = int(line())
        p, q, r = map(int, line().split())
        for _ in range(m):
            x, y = map(int, line().split())
            total = 0
            A, B, C = [], [], []
            for k, s in Cards:
                if y < total + k:
                    if total < y:
                        C += [(total + k - y, s + y - total)]
                        if total < x:
                            B += [(y - x, s + x - total)]
                            A += [(x - total, s)]
                        else:
                            B += [(y - total, s)]
                    else:
                        C += [(k, s)]
                elif x < total + k:
                    if total < x:
                        B += [(total + k - x, s + x - total)]
                        A += [(x - total, s)]
                    else:
                        B += [(k, s)]
                else:
                    A += [(k, s)]
                total += k
            Cards = C + B + A
        total = 0
        D = []
        p = p - 1
        for k, s in Cards:
            if q < total + k:
                if total < q:
                    if total < p:
                        D += [(s + x - total, s + q - total - 1)]
                    else:
                        D += [(s, s + q - total - 1)]
            elif p < total + k:
                if total < p:
                    D += [(s + p - total, s + k - 1)]
                else:
                    D += [(s, s + k - 1)]
            total += k
        ans = 0
        for s, t in D:
            if t < r:
                ans += t - s + 1
            elif s <= r <= t:
                ans += r - s + 1
        print(ans)


if __name__ == '__main__':
    solve()

Submission status: Time Limit Exceeded

Solution code:
def solve():
    import sys
    line = sys.stdin.readline
    for e in iter(line, '0\n'):
        n = int(e)
        Cards = [(n, 1)]
        m = int(line())
        p, q, r = map(int, line().split())
        for _ in range(m):
            x, y = map(int, line().split())
            total = 0
            A, B, C = [], [], []
            for k, s in Cards:
                if y < total + k:
                    if total < y:
                        C += [(total + k - y, s + y - total)]
                        if total < x:
                            B += [(y - x, s + x - total)]
                            A += [(x - total, s)]
                        else:
                            B += [(y - total, s)]
                    else:
                        C += [(k, s)]
                elif x < total + k:
                    if total < x:
                        B += [(total + k - x, s + x - total)]
                        A += [(x - total, s)]
                    else:
                        B += [(k, s)]
                else:
                    A += [(k, s)]
                total += k
            Cards = C + B + A
        total = 0
        ans = 0
        D = []
        p = p - 1
        for k, s in Cards:
            if q < total + k:
                if total < q:
                    v, w = s + (x - total) * (total < p), s + q - total - 1
                    if w < r:
                        ans += w - v + 1
                    elif v <= r <= w:
                        ans += r - v + 1
            elif p < total + k:
                v, w = s + (p - total) * (total < p), s + k - 1
                if w < r:
                    ans += w - v + 1
                elif v <= r <= w:
                    ans += r - v + 1
            total += k
        print(ans)


if __name__ == '__main__':
    solve()

Submission status: Time Limit Exceeded

Solution code:
def solve():
    import sys
    line = sys.stdin.readline
    for e in iter(line, '0\n'):
        n = int(e)
        Cards = [(n, 1)]
        m = int(line())
        p, q, r = map(int, line().split())
        for _ in range(m):
            x, y = map(int, line().split())
            total = 0
            A, B, C = [], [], []
            for k, s in Cards:
                if y < total + k:
                    if total < y:
                        C += [(total + k - y, s + y - total)]
                        if total < x:
                            B += [(y - x, s + x - total)]
                            A += [(x - total, s)]
                        else:
                            B += [(y - total, s)]
                    else:
                        C += [(k, s)]
                elif x < total + k:
                    if total < x:
                        B += [(total + k - x, s + x - total)]
                        A += [(x - total, s)]
                    else:
                        B += [(k, s)]
                else:
                    A += [(k, s)]
                total += k
            Cards = C + B + A
        total = 0
        ans = 0
        D = []
        p = p - 1
        for k, s in Cards:
            if 0 < q - total < k:
                v = (x - total) * (total < p)
                if v <= r - s:
                    ans += min(q - total - 1, r - s) - v + 1
            elif p < total + k:
                v = (p - total) * (total < p)
                if v <= r - s:
                    ans += min(k - 1, r - s) - v + 1
            total += k
        print(ans)


if __name__ == '__main__':
    solve()

Submission status: Time Limit Exceeded

Solution code:
def solve():
    import sys
    line = sys.stdin.readline
    for e in iter(line, '0\n'):
        n = int(e)
        Cards = [(n, 1, n)]
        m = int(line())
        p, q, r = map(int, line().split())
        for _ in range(m):
            x, y = map(int, line().split())
            total = 0
            A, B, C = [], [], []
            for k, s, t in Cards:
                if y < total + k:
                    if total < y:
                        C += [(total + k - y, s + y - total, t)]
                        if total < x:
                            B += [(y - x, s + x - total, s + y - total - 1)]
                            A += [(x - total, s, s + x - total - 1)]
                        else:
                            B += [(y - total, s, s + y - total - 1)]
                    else:
                        C += [(k, s, t)]
                elif x < total + k:
                    if total < x:
                        B += [(total + k - x, s + x - total, t)]
                        A += [(x - total, s, s + x - total - 1)]
                    else:
                        B += [(k, s, t)]
                else:
                    A += [(k, s, t)]
                total += k
            Cards = C + B + A
        total = 0
        D = []
        p = p - 1
        for k, s, t in Cards:
            if q < total + k:
                if total < q:
                    if total < p:
                        D += [(s + x - total, s + q - total - 1)]
                    else:
                        D += [(s, s + q - total - 1)]
            elif p < total + k:
                if total < p:
                    D += [(s + p - total, t)]
                else:
                    D += [(s, t)]
            total += k
        ans = 0
        for s, t in D:
            if t < r:
                ans += t - s + 1
            elif s <= r:
                ans += r - s + 1
        print(ans)


if __name__ == '__main__':
    solve()

Submission status: Time Limit Exceeded

Solution code:
def solve():
    import sys
    line = sys.stdin.readline
    for n in iter(line, '0\n'):
        Cards = [(int(n), 1)]
        m = int(line())
        p, q, r = map(int, line().split())
        for _ in range(m):
            x, y = map(int, line().split())
            total = 0
            A, B, C = [], [], []
            for k, s in Cards:
                t = total + k
                if y < t:
                    if total < y:
                        C += [(t - y, s + y - total)]
                        if total < x:
                            B += [(y - x, s + x - total)]
                            A += [(x - total, s)]
                        else:
                            B += [(y - total, s)]
                    else:
                        C += [(k, s)]
                elif x < t:
                    if total < x:
                        B += [(t - x, s + x - total)]
                        A += [(x - total, s)]
                    else:
                        B += [(k, s)]
                else:
                    A += [(k, s)]
                total = t
            Cards = C + B + A
        ans = total = 0
        p = p - 1
        for k, s in Cards:
            if q < total + k:
                if total < q:
                    v = s + (x - total) * (total < p)
                    if v <= r:
                        ans += min(s + q - total - 1, r) - v + 1
            elif p < total + k:
                v = s + (p - total) * (total < p)
                if v <= r:
                    ans += min(s + k - 1, r) - v + 1
            total += k
        print(ans)


if __name__ == '__main__':
    solve()

Submission status: Time Limit Exceeded

Solution code:
def solve():
    import sys
    line = sys.stdin.readline
    for n in iter(line, '0\n'):
        Cards = [(int(n), 1)]
        m = int(line())
        p, q, r = map(int, line().split())
        for _ in range(m):
            x, y = map(int, line().split())
            total = 0
            A, B, C = [], [], []
            for k, s in Cards:
                t = total + k
                if total < x:
                    A += [(x - total, s)]
                if t <= x:
                    A += [(k, s)]
                if total < y < t:
                    B += [(y - max(x, total), s + (x - total) * (total < x))]
                if x < t <= y:
                    B += [([k, t - x][total < x], s + (x - total) * (total < x))]
                if y < t:
                    C += [([k, t - y][total < y], s + (y - total) * (total < y))]
                total = t
            Cards = C + B + A
        ans = total = 0
        p = p - 1
        for k, s in Cards:
            if 0 < q - total < k:
                v = s + (x - total) * (total < p)
                if v <= r:
                    ans += min(s + q - total - 1, r) - v + 1
            if p < total + k <= q:
                v = s + (p - total) * (total < p)
                if v <= r:
                    ans += min(s + k - 1, r) - v + 1
            total += k
        print(ans)


if __name__ == '__main__':
    solve()

Submission status: Memory Limit Exceeded

Solution code:
while True:
    n = int(input())
    if n == 0: break
    m = int(input())
    p, q, r = map(int, input().split())
    card = [i+1 for i in range(n)]
    for _ in range(m):
        x, y = map(int, input().split())
        A, B = card[:x], card[x:y]
        card = card[y:] + B + A
    print(sum([1 for v in card[p-1:q] if v <= r]))

Submission status: Memory Limit Exceeded

Solution code:
while True:
    n = int(input())
    if n == 0:
        break
    card = [v+1 for v in range(n)]
    m = int(input())
    p, q, r = map(int, input().split())
    for _ in range(m):
        x, y = map(int, input().split())
        A, B, C = card[:x], card[x:y], card[y:]
        card = C + B + A
    print(sum([1 for i in range(p-1, q) if card[i] <= r]))

Submission status: Memory Limit Exceeded

Solution code:
while True:
    n=input()
    if n==0:break
    m=input()
    p,q,r=map(int,raw_input().split())
    L="0"*r+"1"*(n-r)
    for i in range(m):
        x,y=map(int,raw_input().split())
        L=L[:x]+L[x:y]+L[y:]
    print sum(1 for i in L[p-1:q] if i=="0")

Submission status: Runtime Error

Solution code:
for e in iter(input,'0'):
 n=int(e)
 C=[*range(1,n+1)]
 m=int(input())
 p,q,r=map(int,input().split())
 for _ in[0]*m:
  x,y=map(int,input().split())
  C=C[y:]+C[x:y]+C[:x]
 print(sum(x<=r for x in C[p-1:q]))

Submission status: Runtime Error

Solution code:
def solve():
    import sys
    r = sys.stdin.readline
    for e in iter(r, '0'):
        n = int(e)
        Cards = [(n, 1, n)]
        m = int(r())
        p, q, r = map(int, r().split())
        for _ in [0] * m:
            x, y = map(int, r().split())
            total = 0
            A, B, C = [], [], []
            for k, s, t in Cards:
                if y < total + k:
                    if total < y:
                        C += [(total + k - y, s + y - total, t)]
                        if total < x:
                            B += [(y - x, s + x - total, s + y - total - 1)]
                            A += [(x - total, s, s + x - total - 1)]
                        else:
                            B += [(y - total, s, s + y - total - 1)]
                    else:
                        C += [(k, s, t)]
                elif x < total + k:
                    if total < x:
                        B += [(total + k - x, s + x - total, t)]
                        A += [(x - total, s, s + x - total - 1)]
                    else:
                        B += [(k, s, t)]
                else:
                    A += [(k, s, t)]
                total += k
            Cards = C + B + A
        total = 0
        D = []
        p = p - 1
        for k, s, t in Cards:
            if q < total + k:
                if total < q:
                    if total < p:
                        D += [(s + x - total, s + q - total - 1)]
                    else:
                        D += [(s, s + q - total - 1)]
            elif p < total + k:
                if total < p:
                    D += [(s + p - total, t)]
                else:
                    D += [(s, t)]
            total += k
        ans = 0
        for s, t in D:
            if t < r:
                ans += t - s + 1
            elif s <= r <= t:
                ans += r - s + 1
        print(ans)


if __name__ == '__main__':
    solve()