We saw the little game Marmot made for Mole's lunch. Now it's Marmot's dinner time and, as we all know, Marmot eats flowers. At every dinner he eats some red and white flowers. Therefore a dinner can be represented as a sequence of several flowers, some of them white and some of them red.But, for a dinner to be tasty, there is a rule: Marmot wants to eat white flowers only in groups of size k.Now Marmot wonders in how many ways he can eat between a and b flowers. As the number of ways could be very large, print it modulo 1000000007 (109 + 7).

Input contains several test cases. The first line contains two integers t and k (1 ≤ t, k ≤ 105), where t represents the number of test cases. The next t lines contain two integers ai and bi (1 ≤ ai ≤ bi ≤ 105), describing the i-th test.

Print t lines to the standard output. The i-th line should contain the number of ways in which Marmot can eat between ai and bi flowers at dinner modulo 1000000007 (109 + 7).

Note  For K = 2 and length 1 Marmot can eat (R).  For K = 2 and length 2 Marmot can eat (RR) and (WW).  For K = 2 and length 3 Marmot can eat (RRR), (RWW) and (WWR).  For K = 2 and length 4 Marmot can eat, for example, (WWWW) or (RWWR), but for example he can't eat (WWWR).

dp=[]
  mod=1000000007
  na=gets.chomp

  t=na[0..na.index(" ")-1].to_i
  i=na.index(" ")
  k=na[i+1..na.length-1].to_i
  i=1
  dp[0]=1
  while i<100001
  dp[i]=0
  if(i-k>=0)
    dp[i]=dp[i-k]
  end
    dp[i]+=dp[i-1]
    dp[i]=(dp[i])% mod
  i+=1
  end
  i=1
  while i<100001
  dp[i]+=dp[i-1]
  dp[i]=(dp[i])% mod
  i+=1
  end

  while t>0
  na=gets.chomp

  a=na[0..na.index(" ")-1].to_i
  i=na.index(" ")
  b=na[i+1..na.length-1].to_i
  temp=(dp[b]-dp[a-1])% mod
  puts temp

  t-=1
  end

# coding: utf-8

# 총 테스트 케이스 t 에 대해, 꽃을 a개부터 b개 사이로 먹는 경우의 수를 계산한다
# 단 흰 꽃은 k개 단위로만 먹을 수 있다.
# 예) k = 2일때, 꽃 4개를 먹을 때는 흰색만 4개를 먹을 수 있지만,
#     k = 3일때는 3개를 먹을 수 없다.
# 이때 빨간 꽃 R과 흰꽃 W를 섞어서 먹을 수 있는 경우의 수를 modulo 10**9 + 7 로 계산
MODULO_BASE = 10**9 + 7
MAX_HEIGHT = 10**5
# 혹시 k-Tree 문제 생각나십니까? 음 도움이 될지 모르겠는데
# 각 자리에 올 수 있는건 R 또는 W입니다. 이것은 이진트리입니다.
# 이진트리의 순회는 DFS와 BFS중 하나로 풀 수 있겠죠.
# growing을 어떻게 할까요, 되는 노드만 계산합시다. 언제 망한 노드도 계산해요
# D0: (root) (K = 3) Z = WWW (unbalanced)
# D1:                         R1                                            Z3
# D2:              RR2                 RZ4                          ZR4                  ZZ6
# D3:       RRR3       RRZ5        RZR5       RZZ7            ZRR5     ZRZ7          ZZR7       ZZZ9
# D4:   RRRR4 RRRZ6 RRZR6 RRZZ8 RZRR6 RZRZ8 RZZR8 RZZZ10   ZRRR6  ZRRZ8 ZRZR8 ZRZZ10  ZZRR8 ZZRZ10  ZZZR10 ZZZZ12
t, k = gets.split.map(&:to_i)
# 아 시발 이런 뜻이라니
# 각 꽃의 개수를 목적치로 설정합니다.
# 모든 경우에 대해 R로 채우는 1가지가 있으므로 dp[x] += 1을 적용합니다.
# dp[x]로부터, k씩 더해 방문 가능한 개수를 1씩 증가시킵니다
# dp[x+1]로 넘어가서 dp[x+1]에 대해 방문하였으므로 += 1을 수행하고, 여기로부터 방문 가능한 x+k배수를 모두 += 1합니다.
# 자연스럽게 x' 가 x + k 와 같아지는 순간이 있습니다. 이때도 += 1을 적용합니다.
#
dp = Array.new(MAX_HEIGHT + k) { 0 } # 0번 인덱스 안써요
# 이렇게 초기화해야하는 이유가 있음
# K = 1일때는 한 자리에 두가지 경우가 바로 발생됨. 그걸 표현하려면 이 방법이 좋다.
dp[1] += 1
dp[k] += 1
acc_dp = Array.new(MAX_HEIGHT + k)
acc_dp[0] = 0
acc_dp[1] = dp[1] # 여기도 초기화를 이렇게 해야함, 왜 항상 처음이 1일거라 생각하는거지? K=1이면 이 자리는 2이다.
acc = dp[1]
for i in 2..MAX_HEIGHT
    if i <= k
        dp[i] += 1 # No more cases...
    else
        dp[i] += (dp[i-1]%MODULO_BASE + dp[i-k]%MODULO_BASE) % MODULO_BASE # Came from prev R(i-1), from prev Z(i-k)
    end
    acc += dp[i]
    acc_dp[i] = acc
end

t.times {
    a, b = gets.split.map(&:to_i)
    # p "#{acc_dp[b]} #{acc_dp[a-1]}"
    puts (acc_dp[b] - acc_dp[a-1])%MODULO_BASE
}

# coding: utf-8

# 총 테스트 케이스 t 에 대해, 꽃을 a개부터 b개 사이로 먹는 경우의 수를 계산한다
# 단 흰 꽃은 k개 단위로만 먹을 수 있다.
# 예) k = 2일때, 꽃 4개를 먹을 때는 흰색만 4개를 먹을 수 있지만,
#     k = 3일때는 3개를 먹을 수 없다.
# 이때 빨간 꽃 R과 흰꽃 W를 섞어서 먹을 수 있는 경우의 수를 modulo 10**9 + 7 로 계산
MODULO_BASE = 10**9 + 7
MAX_HEIGHT = 10**5
# 혹시 k-Tree 문제 생각나십니까? 음 도움이 될지 모르겠는데
# 각 자리에 올 수 있는건 R 또는 W입니다. 이것은 이진트리입니다.
# 이진트리의 순회는 DFS와 BFS중 하나로 풀 수 있겠죠.
# growing을 어떻게 할까요, 되는 노드만 계산합시다. 언제 망한 노드도 계산해요
# D0: (root) (K = 3) Z = WWW (unbalanced)
# D1:                         R1                                            Z3
# D2:              RR2                 RZ4                          ZR4                  ZZ6
# D3:       RRR3       RRZ5        RZR5       RZZ7            ZRR5     ZRZ7          ZZR7       ZZZ9
# D4:   RRRR4 RRRZ6 RRZR6 RRZZ8 RZRR6 RZRZ8 RZZR8 RZZZ10   ZRRR6  ZRRZ8 ZRZR8 ZRZZ10  ZZRR8 ZZRZ10  ZZZR10 ZZZZ12
t, k = gets.split.map(&:to_i)
# 아 시발 이런 뜻이라니
# 각 꽃의 개수를 목적치로 설정합니다.
# 모든 경우에 대해 R로 채우는 1가지가 있으므로 dp[x] += 1을 적용합니다.
# dp[x]로부터, k씩 더해 방문 가능한 개수를 1씩 증가시킵니다
# dp[x+1]로 넘어가서 dp[x+1]에 대해 방문하였으므로 += 1을 수행하고, 여기로부터 방문 가능한 x+k배수를 모두 += 1합니다.
# 자연스럽게 x' 가 x + k 와 같아지는 순간이 있습니다. 이때도 += 1을 적용합니다.
#
dp = Array.new(MAX_HEIGHT + k) { 0 } # 0번 인덱스 안써요
dp[1] = 1
dp[k] = 1
acc_dp = Array.new(MAX_HEIGHT + k)
acc_dp[0] = 0
acc_dp[1] = 1
acc = 1
for i in 2..MAX_HEIGHT
    if i < k
        dp[i] += 1 # No more cases...
    else
        dp[i] += (dp[i-1]%MODULO_BASE + dp[i-k]%MODULO_BASE) % MODULO_BASE # Came from prev R(i-1), from prev Z(i-k)
    end
    acc += dp[i]
    acc_dp[i] = acc
end

t.times {
    a, b = gets.split.map(&:to_i)
    puts (acc_dp[b] - acc_dp[a-1])%MODULO_BASE
}

# coding: utf-8

# 총 테스트 케이스 t 에 대해, 꽃을 a개부터 b개 사이로 먹는 경우의 수를 계산한다
# 단 흰 꽃은 k개 단위로만 먹을 수 있다.
# 예) k = 2일때, 꽃 4개를 먹을 때는 흰색만 4개를 먹을 수 있지만,
#     k = 3일때는 3개를 먹을 수 없다.
# 이때 빨간 꽃 R과 흰꽃 W를 섞어서 먹을 수 있는 경우의 수를 modulo 10**9 + 7 로 계산
MODULO_BASE = 10**9 + 7
MAX_HEIGHT = 10**5
# 혹시 k-Tree 문제 생각나십니까? 음 도움이 될지 모르겠는데
# 각 자리에 올 수 있는건 R 또는 W입니다. 이것은 이진트리입니다.
# 이진트리의 순회는 DFS와 BFS중 하나로 풀 수 있겠죠.
# growing을 어떻게 할까요, 되는 노드만 계산합시다. 언제 망한 노드도 계산해요
# D0: (root) (K = 3) Z = WWW (unbalanced)
# D1:                         R1                                            Z3
# D2:              RR2                 RZ4                          ZR4                  ZZ6
# D3:       RRR3       RRZ5        RZR5       RZZ7            ZRR5     ZRZ7          ZZR7       ZZZ9
# D4:   RRRR4 RRRZ6 RRZR6 RRZZ8 RZRR6 RZRZ8 RZZR8 RZZZ10   ZRRR6  ZRRZ8 ZRZR8 ZRZZ10  ZZRR8 ZZRZ10  ZZZR10 ZZZZ12
t, k = gets.split.map(&:to_i)
# 아 시발 이런 뜻이라니
# 각 꽃의 개수를 목적치로 설정합니다.
# 모든 경우에 대해 R로 채우는 1가지가 있으므로 dp[x] += 1을 적용합니다.
# dp[x]로부터, k씩 더해 방문 가능한 개수를 1씩 증가시킵니다
# dp[x+1]로 넘어가서 dp[x+1]에 대해 방문하였으므로 += 1을 수행하고, 여기로부터 방문 가능한 x+k배수를 모두 += 1합니다.
# 자연스럽게 x' 가 x + k 와 같아지는 순간이 있습니다. 이때도 += 1을 적용합니다.
#
dp = Array.new(MAX_HEIGHT + k) { 0 } # 0번 인덱스 안써요
# 이렇게 초기화해야하는 이유가 있음
# K = 1일때는 한 자리에 두가지 경우가 바로 발생됨. 그걸 표현하려면 이 방법이 좋다.
dp[1] += 1
dp[k] += 1
acc_dp = Array.new(MAX_HEIGHT + k)
acc_dp[0] = 0
acc_dp[1] = dp[1] # 여기도 초기화를 이렇게 해야함, 왜 항상 처음이 1일거라 생각하는거지? K=1이면 이 자리는 2이다.
acc = 1
for i in 2..MAX_HEIGHT
    if i <= k
        dp[i] += 1 # No more cases...
    else
        dp[i] += (dp[i-1]%MODULO_BASE + dp[i-k]%MODULO_BASE) % MODULO_BASE # Came from prev R(i-1), from prev Z(i-k)
    end
    acc += dp[i]
    acc_dp[i] = acc
end

t.times {
    a, b = gets.split.map(&:to_i)
    # p "#{acc_dp[b]} #{acc_dp[a-1]}"
    puts (acc_dp[b] - acc_dp[a-1])%MODULO_BASE
}

# coding: utf-8

# 총 테스트 케이스 t 에 대해, 꽃을 a개부터 b개 사이로 먹는 경우의 수를 계산한다
# 단 흰 꽃은 k개 단위로만 먹을 수 있다.
# 예) k = 2일때, 꽃 4개를 먹을 때는 흰색만 4개를 먹을 수 있지만,
#     k = 3일때는 3개를 먹을 수 없다.
# 이때 빨간 꽃 R과 흰꽃 W를 섞어서 먹을 수 있는 경우의 수를 modulo 10**9 + 7 로 계산
MODULO_BASE = 10**9 + 7
MAX_HEIGHT = 10**5
# 혹시 k-Tree 문제 생각나십니까? 음 도움이 될지 모르겠는데
# 각 자리에 올 수 있는건 R 또는 W입니다. 이것은 이진트리입니다.
# 이진트리의 순회는 DFS와 BFS중 하나로 풀 수 있겠죠.
# growing을 어떻게 할까요, 되는 노드만 계산합시다. 언제 망한 노드도 계산해요
# D0: (root) (K = 3) Z = WWW (unbalanced)
# D1:                         R1                                            Z3
# D2:              RR2                 RZ4                          ZR4                  ZZ6
# D3:       RRR3       RRZ5        RZR5       RZZ7            ZRR5     ZRZ7          ZZR7       ZZZ9
# D4:   RRRR4 RRRZ6 RRZR6 RRZZ8 RZRR6 RZRZ8 RZZR8 RZZZ10   ZRRR6  ZRRZ8 ZRZR8 ZRZZ10  ZZRR8 ZZRZ10  ZZZR10 ZZZZ12
t, k = gets.split.map(&:to_i)
# 아 시발 이런 뜻이라니
# 각 꽃의 개수를 목적치로 설정합니다.
# 모든 경우에 대해 R로 채우는 1가지가 있으므로 dp[x] += 1을 적용합니다.
# dp[x]로부터, k씩 더해 방문 가능한 개수를 1씩 증가시킵니다
# dp[x+1]로 넘어가서 dp[x+1]에 대해 방문하였으므로 += 1을 수행하고, 여기로부터 방문 가능한 x+k배수를 모두 += 1합니다.
# 자연스럽게 x' 가 x + k 와 같아지는 순간이 있습니다. 이때도 += 1을 적용합니다.
#
dp = Array.new(MAX_HEIGHT + k) { 0 } # 0번 인덱스 안써요
dp[1] = 1
dp[k] = 1
acc_dp = Array.new(MAX_HEIGHT + k)
acc_dp[0] = 0
acc_dp[1] = 1
acc = 1
for i in 2..MAX_HEIGHT
    if i < k
        dp[i] += 1 # No more cases...
    else
        dp[i] += (dp[i-1]%MODULO_BASE + dp[i-k]%MODULO_BASE) % MODULO_BASE # Came from prev R(i-1), from prev Z(i-k)
    end
    acc = (acc%MODULO_BASE + dp[i]%MODULO_BASE)%MODULO_BASE
    acc_dp[i] = acc
end

t.times {
    a, b = gets.split.map(&:to_i)
    puts (acc_dp[b] - acc_dp[a-1]).abs
}

# coding: utf-8

# 총 테스트 케이스 t 에 대해, 꽃을 a개부터 b개 사이로 먹는 경우의 수를 계산한다
# 단 흰 꽃은 k개 단위로만 먹을 수 있다.
# 예) k = 2일때, 꽃 4개를 먹을 때는 흰색만 4개를 먹을 수 있지만,
#     k = 3일때는 3개를 먹을 수 없다.
# 이때 빨간 꽃 R과 흰꽃 W를 섞어서 먹을 수 있는 경우의 수를 modulo 10**9 + 7 로 계산
MODULO_BASE = 10**9 + 7
MAX_HEIGHT = 10**5
# 혹시 k-Tree 문제 생각나십니까? 음 도움이 될지 모르겠는데
# 각 자리에 올 수 있는건 R 또는 W입니다. 이것은 이진트리입니다.
# 이진트리의 순회는 DFS와 BFS중 하나로 풀 수 있겠죠.
# growing을 어떻게 할까요, 되는 노드만 계산합시다. 언제 망한 노드도 계산해요
# D0: (root) (K = 3) Z = WWW (unbalanced)
# D1:                         R1                                            Z3
# D2:              RR2                 RZ4                          ZR4                  ZZ6
# D3:       RRR3       RRZ5        RZR5       RZZ7            ZRR5     ZRZ7          ZZR7       ZZZ9
# D4:   RRRR4 RRRZ6 RRZR6 RRZZ8 RZRR6 RZRZ8 RZZR8 RZZZ10   ZRRR6  ZRRZ8 ZRZR8 ZRZZ10  ZZRR8 ZZRZ10  ZZZR10 ZZZZ12
t, k = gets.split.map(&:to_i)
# 아 시발 이런 뜻이라니
# 각 꽃의 개수를 목적치로 설정합니다.
# 모든 경우에 대해 R로 채우는 1가지가 있으므로 dp[x] += 1을 적용합니다.
# dp[x]로부터, k씩 더해 방문 가능한 개수를 1씩 증가시킵니다
# dp[x+1]로 넘어가서 dp[x+1]에 대해 방문하였으므로 += 1을 수행하고, 여기로부터 방문 가능한 x+k배수를 모두 += 1합니다.
# 자연스럽게 x' 가 x + k 와 같아지는 순간이 있습니다. 이때도 += 1을 적용합니다.
#
dp = Array.new(MAX_HEIGHT + k) { 0 } # 0번 인덱스 안써요
# 이렇게 초기화해야하는 이유가 있음
# K = 1일때는 한 자리에 두가지 경우가 바로 발생됨. 그걸 표현하려면 이 방법이 좋다.
dp[1] += 1
dp[k] += 1
acc_dp = Array.new(MAX_HEIGHT + k)
acc_dp[0] = 0
acc_dp[1] = dp[1] # 여기도 초기화를 이렇게 해야함, 왜 항상 처음이 1일거라 생각하는거지? K=1이면 이 자리는 2이다.
acc = 1
for i in 2..MAX_HEIGHT
    if i < k
        dp[i] += 1 # No more cases...
    else
        dp[i] += (dp[i-1]%MODULO_BASE + dp[i-k]%MODULO_BASE) % MODULO_BASE # Came from prev R(i-1), from prev Z(i-k)
    end
    acc += dp[i]
    acc_dp[i] = acc
end

t.times {
    a, b = gets.split.map(&:to_i)
    # p "#{acc_dp[b]} #{acc_dp[a-1]}"
    puts (acc_dp[b]%MODULO_BASE - acc_dp[a-1]%MODULO_BASE)%MODULO_BASE
}

# coding: utf-8

# 총 테스트 케이스 t 에 대해, 꽃을 a개부터 b개 사이로 먹는 경우의 수를 계산한다
# 단 흰 꽃은 k개 단위로만 먹을 수 있다.
# 예) k = 2일때, 꽃 4개를 먹을 때는 흰색만 4개를 먹을 수 있지만,
#     k = 3일때는 3개를 먹을 수 없다.
# 이때 빨간 꽃 R과 흰꽃 W를 섞어서 먹을 수 있는 경우의 수를 modulo 10**9 + 7 로 계산
MODULO_BASE = 10**9 + 7
MAX_HEIGHT = 10**5
# 혹시 k-Tree 문제 생각나십니까? 음 도움이 될지 모르겠는데
# 각 자리에 올 수 있는건 R 또는 W입니다. 이것은 이진트리입니다.
# 이진트리의 순회는 DFS와 BFS중 하나로 풀 수 있겠죠.
# growing을 어떻게 할까요, 되는 노드만 계산합시다. 언제 망한 노드도 계산해요
# D0: (root) (K = 3) Z = WWW (unbalanced)
# D1:                         R1                                            Z3
# D2:              RR2                 RZ4                          ZR4                  ZZ6
# D3:       RRR3       RRZ5        RZR5       RZZ7            ZRR5     ZRZ7          ZZR7       ZZZ9
# D4:   RRRR4 RRRZ6 RRZR6 RRZZ8 RZRR6 RZRZ8 RZZR8 RZZZ10   ZRRR6  ZRRZ8 ZRZR8 ZRZZ10  ZZRR8 ZZRZ10  ZZZR10 ZZZZ12
t, k = gets.split.map(&:to_i)
# 아 시발 이런 뜻이라니
# 각 꽃의 개수를 목적치로 설정합니다.
# 모든 경우에 대해 R로 채우는 1가지가 있으므로 dp[x] += 1을 적용합니다.
# dp[x]로부터, k씩 더해 방문 가능한 개수를 1씩 증가시킵니다
# dp[x+1]로 넘어가서 dp[x+1]에 대해 방문하였으므로 += 1을 수행하고, 여기로부터 방문 가능한 x+k배수를 모두 += 1합니다.
# 자연스럽게 x' 가 x + k 와 같아지는 순간이 있습니다. 이때도 += 1을 적용합니다.
#
dp = Array.new(MAX_HEIGHT + k) { 0 } # 0번 인덱스 안써요
dp[1] = 1
dp[k] = 1
acc_dp = Array.new(MAX_HEIGHT + k)
acc_dp[0] = 0
acc_dp[1] = 1
acc = 1
for i in 2..MAX_HEIGHT
    if i < k
        dp[i] += 1 # No more cases...
    else
        dp[i] += (dp[i-1]%MODULO_BASE + dp[i-k]%MODULO_BASE) % MODULO_BASE # Came from prev R(i-1), from prev Z(i-k)
    end
    acc += dp[i]
    acc_dp[i] = acc
end

t.times {
    a, b = gets.split.map(&:to_i)
    puts (acc_dp[b] - acc_dp[a-1])
}

# coding: utf-8

# 총 테스트 케이스 t 에 대해, 꽃을 a개부터 b개 사이로 먹는 경우의 수를 계산한다
# 단 흰 꽃은 k개 단위로만 먹을 수 있다.
# 예) k = 2일때, 꽃 4개를 먹을 때는 흰색만 4개를 먹을 수 있지만,
#     k = 3일때는 3개를 먹을 수 없다.
# 이때 빨간 꽃 R과 흰꽃 W를 섞어서 먹을 수 있는 경우의 수를 modulo 10**9 + 7 로 계산
MODULO_BASE = 10**9 + 7
MAX_HEIGHT = 10**5
# 혹시 k-Tree 문제 생각나십니까? 음 도움이 될지 모르겠는데
# 각 자리에 올 수 있는건 R 또는 W입니다. 이것은 이진트리입니다.
# 이진트리의 순회는 DFS와 BFS중 하나로 풀 수 있겠죠.
# growing을 어떻게 할까요, 되는 노드만 계산합시다. 언제 망한 노드도 계산해요
# D0: (root) (K = 3) Z = WWW (unbalanced)
# D1:                         R1                                            Z3
# D2:              RR2                 RZ4                          ZR4                  ZZ6
# D3:       RRR3       RRZ5        RZR5       RZZ7            ZRR5     ZRZ7          ZZR7       ZZZ9
# D4:   RRRR4 RRRZ6 RRZR6 RRZZ8 RZRR6 RZRZ8 RZZR8 RZZZ10   ZRRR6  ZRRZ8 ZRZR8 ZRZZ10  ZZRR8 ZZRZ10  ZZZR10 ZZZZ12
t, k = gets.split.map(&:to_i)
# 아 시발 이런 뜻이라니
# 각 꽃의 개수를 목적치로 설정합니다.
# 모든 경우에 대해 R로 채우는 1가지가 있으므로 dp[x] += 1을 적용합니다.
# dp[x]로부터, k씩 더해 방문 가능한 개수를 1씩 증가시킵니다
# dp[x+1]로 넘어가서 dp[x+1]에 대해 방문하였으므로 += 1을 수행하고, 여기로부터 방문 가능한 x+k배수를 모두 += 1합니다.
# 자연스럽게 x' 가 x + k 와 같아지는 순간이 있습니다. 이때도 += 1을 적용합니다.
#
dp = Array.new(MAX_HEIGHT + k) { 0 } # 0번 인덱스 안써요
# 이렇게 초기화해야하는 이유가 있음
# K = 1일때는 한 자리에 두가지 경우가 바로 발생됨. 그걸 표현하려면 이 방법이 좋다.
dp[1] += 1
dp[k] += 1
acc_dp = Array.new(MAX_HEIGHT + k)
acc_dp[0] = 0
acc_dp[1] = dp[1] # 여기도 초기화를 이렇게 해야함, 왜 항상 처음이 1일거라 생각하는거지? K=1이면 이 자리는 2이다.
acc = 1
for i in 2..MAX_HEIGHT
    if i < k
        dp[i] += 1 # No more cases...
    else
        dp[i] += (dp[i-1]%MODULO_BASE + dp[i-k]%MODULO_BASE) % MODULO_BASE # Came from prev R(i-1), from prev Z(i-k)
    end
    acc += dp[i]
    acc_dp[i] = acc
end

t.times {
    a, b = gets.split.map(&:to_i)
    # p "#{acc_dp[b]} #{acc_dp[a-1]}"
    puts (acc_dp[b] - acc_dp[a-1])%MODULO_BASE
}


You talked to Polycarp and asked him a question. You know that when he wants to answer "yes", he repeats Yes many times in a row.Because of the noise, you only heard part of the answer — some substring of it. That is, if he answered YesYes, then you could hear esY, YesYes, sYes, e, but you couldn't Yess, YES or se.Determine if it is true that the given string $$$s$$$ is a substring of YesYesYes... (Yes repeated many times in a row).

The first line of input data contains the singular $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Each test case is described by a single string of Latin letters $$$s$$$ ($$$1 \le |s| \le 50$$$) — the part of Polycarp's answer that you heard, where $$$|s|$$$ — is the length of the string $$$s$$$.

Output $$$t$$$ lines, each of which is the answer to the corresponding test case. As an answer, output "YES" if the specified string $$$s$$$ is a substring of the string YesYesYes...Yes (the number of words Yes is arbitrary), and "NO" otherwise. You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).

12

YES

esYes

codeforces

es

se

YesY

esYesYesYesYesYesYe

seY

Yess

sY

o

Yes

NO
YES
NO
YES
NO
YES
YES
NO
NO
YES
NO
YES

main = -> {
  s = gets.chomp
  yes = "Yes" * 50
  yes.include?(s) ? "YES" : "NO"
}

t = gets.to_i
puts t.times.map{ main.call }.join("\n")

ans = []
gets.to_i.times do
  s = gets.chomp
  a = 'Yes' * 50
  ans << if a.include? s
           'YES'
         else
           'NO'
         end
end
puts ans

gets.to_i.times do
    s=gets.chomp
    cur=nil
    s.each_char do|c|
        if cur==nil
            if c!='Y' and c!='e' and c!='s'
                cur=nil
                break
            else
                cur=c
            end
        elsif (cur=='Y' and c=='e') or (cur=='e' and c=='s') or (cur=='s' and c=='Y')
            cur=c
        else
            cur=nil
            break
        end
    end
    if cur==nil
        puts 'NO'
    else
        puts 'YES'
    end
end


You are asked to watch your nephew who likes to play with toy blocks in a strange way.He has $$$n$$$ boxes and the $$$i$$$-th box has $$$a_i$$$ blocks. His game consists of two steps:   he chooses an arbitrary box $$$i$$$;  he tries to move all blocks from the $$$i$$$-th box to other boxes.  If he can make the same number of blocks in each of $$$n - 1$$$ other boxes then he will be happy, otherwise, will be sad. Note that your nephew can only move the blocks from the chosen box to the other boxes; he cannot move blocks from the other boxes.You don't want to make your nephew sad, so you decided to put several extra blocks into some boxes in such a way that no matter which box $$$i$$$ he chooses he won't be sad. What is the minimum number of extra blocks you need to put?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of boxes. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^9$$$) — the number of blocks in each box. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$10^5$$$.

For each test case, print a single integer — the minimum number of blocks you need to put. It can be proved that the answer always exists, i. e. the number of blocks is finite.

NoteIn the first test case, you can, for example, put one extra block into the first box and make $$$a = [4, 2, 2]$$$. If your nephew chooses the box with $$$4$$$ blocks, then we will move two blocks to the second box and two blocks to the third box. If he chooses the box with $$$2$$$ blocks then he will move these two blocks to the other box with $$$2$$$ blocks.In the second test case, you don't need to put any extra blocks, since no matter which box your nephew chooses, he can always make other boxes equal.In the third test case, you should put $$$3$$$ extra blocks. For example, you can put $$$2$$$ blocks in the first box and $$$1$$$ block in the third box. You'll get array $$$a = [2, 3, 1]$$$.

DEBUG = false
MOD = 10**9+7
YESNO = %w(Yes No)

def main
  t = int
  t.times do
    n = int
    a = ints

    seg = Segtree.new(a, 0) { |x, y| max(x, y) }
    sum = a.sum

    ans_max = 0
    n.times do |i|
      othermax = max(seg.prod(0, i), seg.prod(i+1, n))
      diff = othermax * (n-1) - sum
      if diff < 0
        diff %= n - 1
      end
      ans_max = max(ans_max, diff)
    end

    puts ans_max
  end
end

def int; gets.to_i; end
def ints; gets.split.map &:to_i; end
def float; gets.to_f; end
def floats; gets.split.map &:to_f; end
def array(&convert); gets.split.map(&convert); end
def string; gets.chomp; end
def rep(n, &b); Array.new(n, &b); end
def yes; puts YESNO[0]; end
def no; puts YESNO[1]; end
def yesno t; t ? yes : no; end
def zip(xs, *yss); Enumerator.new { |y| xs.zip(*yss) { |a| y.yield(*a) } }; end
def sorted_uniq(xs); x = nil; xs.filter! { |y| c = x === y; x = y; !c }; end
def max(*xs); xs.max; end
def min(*xs); xs.min; end
def minmax(*xs); xs.minmax; end
def matrix(h, w, fill=nil, &block); return Array.new(h) { Array.new(w, &block) } if block_given?; Array.new(h) { [fill] * w }; end
def debug(x); if DEBUG; STDERR.puts (block_given? ? yield(x) : x).inspect; end; x; end
def debug_grid(grid, width = 1); grid.each { |row| STDERR.puts row.map { |x| x.inspect.ljust(width) }.join("") } if DEBUG; grid; end
def if_debug; yield if DEBUG; end

def div_ceil(x, y); (x + y - 1) / y; end
def gcd(*xs); xs.inject(0) { |y, x| y.gcd(x) }; end
def factorial(n, mod); (2..n).inject(1) { |f, x| f * x % mod }; end
def cumsum(xs); ys = [0]; xs.each { |x| ys << x + ys[-1] }; ys; end
def cumdiff(ys); xs = []; xs.inject { |x, y| xs << (d = y - x); d }; end
def cumfold(ys, range); r = range.end; r -= 1 if range.exclusive_end?; ys[r] - ys[range.begin-1]; end
def mod_inv(x, mod); x.pow(mod-2, mod); end
def mod_div(x, y, mod); x * mod_inv(y, mod) % mod; end
def bitbrute(size, &block); (1<<size).times(&block); end

class UnionFind
  def initialize(size); @p, @r = size.times.to_a, [1] * size; end
  def merge(i, j); k, l = leader(i), leader(j); return if k == l; k, l = l, k if @r[k] < @r[l]; @p[l] = k; @r[k] += @r[l]; end
  def size(i); @r[leader(i)]; end
  def same?(i, j); leader(i) == leader(j); end
  def leader(i); j = i; until i == @p[i]; j, i = i, @p[j] = @p[i]; end; i; end
end

# Segment Tree
class Segtree
  attr_reader :d, :op, :n, :leaf_size, :log

  def initialize(arg = 0, e, &block)
    case arg
    when Integer
      v = Array.new(arg) { e }
    when Array
      v = arg
    end

    @e  = e
    @op = proc(&block)

    @n = v.size
    @log = (@n - 1).bit_length
    @leaf_size = 1 << @log
    @d = Array.new(@leaf_size * 2) { e }
    v.each_with_index { |v_i, i| @d[@leaf_size + i] = v_i }
    (@leaf_size - 1).downto(1) { |i| update(i) }
  end

  def set(q, x)
    q += @leaf_size
    @d[q] = x
    1.upto(@log) { |i| update(q >> i) }
  end

  def get(pos)
    @d[@leaf_size + pos]
  end

  def prod(l, r)
    return @e if l == r

    sml = @e
    smr = @e
    l += @leaf_size
    r += @leaf_size

    while l < r
      if l[0] == 1
        sml = @op.call(sml, @d[l])
        l += 1
      end
      if r[0] == 1
        r -= 1
        smr = @op.call(@d[r], smr)
      end
      l /= 2
      r /= 2
    end

    @op.call(sml, smr)
  end

  def all_prod
    @d[1]
  end

  def max_right(l, &block)
    return @n if l == @n

    f = proc(&block)

    l += @leaf_size
    sm = @e
    loop do
      l /= 2 while l.even?
      unless f.call(@op.call(sm, @d[l]))
        while l < @leaf_size
          l *= 2
          if f.call(@op.call(sm, @d[l]))
            sm = @op.call(sm, @d[l])
            l += 1
          end
        end

        return l - @leaf_size
      end

      sm = @op.call(sm, @d[l])
      l += 1
      break if (l & -l) == l
    end

    @n
  end

  def min_left(r, &block)
    return 0 if r == 0

    f = proc(&block)

    r += @leaf_size
    sm = @e
    loop do
      r -= 1
      r /= 2 while r > 1 && r.odd?
      unless f.call(@op.call(@d[r], sm))
        while r < @leaf_size
          r = r * 2 + 1
          if f.call(@op.call(@d[r], sm))
            sm = @op.call(@d[r], sm)
            r -= 1
          end
        end

        return r + 1 - @leaf_size
      end

      sm = @op.call(@d[r], sm)
      break if (r & -r) == r
    end

    0
  end

  def update(k)
    @d[k] = @op.call(@d[2 * k], @d[2 * k + 1])
  end

  def inspect
    t = 0
    res = "SegmentTree @e = #{@e}, @n = #{@n}, @leaf_size = #{@leaf_size} @op = #{@op}\n  "
    a = @d[1, @d.size - 1]
    a.each_with_index do |e, i|
      res << e.to_s << ' '
      if t == i && i < @leaf_size
        res << "\n  "
        t = t * 2 + 2
      end
    end
    res
  end
end

main

testcases = gets.to_i
testcases.times do
  n = gets.to_i
  an = gets.chomp!.split.map(&:to_i)
  if an.size <= 2
    p 0
  else
    res =  an.max * (n - 1) - an.sum
    p res >=0 ? res : res % (n-1)
  end
end

testcases = gets.to_i
testcases.times do
  n = gets.to_i
  an = gets.chomp!.split.map(&:to_i)
  an.sort!
  an.reverse!
  if an.size <= 2
    p 0
  else
    res =  an[0] * (n - 1) - an.sum
    p res >=0 ? res : res % (n-1)
  end
end

DEBUG = false
MOD = 10**9+7
YESNO = %w(Yes No)

def main
  t = int
  t.times do
    n = int
    a = ints

    seg = Segtree.new(a, 0) { |x, y| max(x, y) }
    sum = a.sum

    ans_min = 2e9
    n.times do |i|
      othermax = max(seg.prod(0, i), seg.prod(i+1, n))
      diff = othermax * (n-1) - sum
      diff %= n - 1 if diff < 0
      ans_min = min(ans_min, diff)
    end

    puts ans_min
  end
end

def int; gets.to_i; end
def ints; gets.split.map &:to_i; end
def float; gets.to_f; end
def floats; gets.split.map &:to_f; end
def array(&convert); gets.split.map(&convert); end
def string; gets.chomp; end
def rep(n, &b); Array.new(n, &b); end
def yes; puts YESNO[0]; end
def no; puts YESNO[1]; end
def yesno t; t ? yes : no; end
def zip(xs, *yss); Enumerator.new { |y| xs.zip(*yss) { |a| y.yield(*a) } }; end
def sorted_uniq(xs); x = nil; xs.filter! { |y| c = x === y; x = y; !c }; end
def max(*xs); xs.max; end
def min(*xs); xs.min; end
def minmax(*xs); xs.minmax; end
def matrix(h, w, fill=nil, &block); return Array.new(h) { Array.new(w, &block) } if block_given?; Array.new(h) { [fill] * w }; end
def debug(x); if DEBUG; STDERR.puts (block_given? ? yield(x) : x).inspect; end; x; end
def debug_grid(grid, width = 1); grid.each { |row| STDERR.puts row.map { |x| x.inspect.ljust(width) }.join("") } if DEBUG; grid; end
def if_debug; yield if DEBUG; end

def div_ceil(x, y); (x + y - 1) / y; end
def gcd(*xs); xs.inject(0) { |y, x| y.gcd(x) }; end
def factorial(n, mod); (2..n).inject(1) { |f, x| f * x % mod }; end
def cumsum(xs); ys = [0]; xs.each { |x| ys << x + ys[-1] }; ys; end
def cumdiff(ys); xs = []; xs.inject { |x, y| xs << (d = y - x); d }; end
def cumfold(ys, range); r = range.end; r -= 1 if range.exclusive_end?; ys[r] - ys[range.begin-1]; end
def mod_inv(x, mod); x.pow(mod-2, mod); end
def mod_div(x, y, mod); x * mod_inv(y, mod) % mod; end
def bitbrute(size, &block); (1<<size).times(&block); end

class UnionFind
  def initialize(size); @p, @r = size.times.to_a, [1] * size; end
  def merge(i, j); k, l = leader(i), leader(j); return if k == l; k, l = l, k if @r[k] < @r[l]; @p[l] = k; @r[k] += @r[l]; end
  def size(i); @r[leader(i)]; end
  def same?(i, j); leader(i) == leader(j); end
  def leader(i); j = i; until i == @p[i]; j, i = i, @p[j] = @p[i]; end; i; end
end

# Segment Tree
class Segtree
  attr_reader :d, :op, :n, :leaf_size, :log

  def initialize(arg = 0, e, &block)
    case arg
    when Integer
      v = Array.new(arg) { e }
    when Array
      v = arg
    end

    @e  = e
    @op = proc(&block)

    @n = v.size
    @log = (@n - 1).bit_length
    @leaf_size = 1 << @log
    @d = Array.new(@leaf_size * 2) { e }
    v.each_with_index { |v_i, i| @d[@leaf_size + i] = v_i }
    (@leaf_size - 1).downto(1) { |i| update(i) }
  end

  def set(q, x)
    q += @leaf_size
    @d[q] = x
    1.upto(@log) { |i| update(q >> i) }
  end

  def get(pos)
    @d[@leaf_size + pos]
  end

  def prod(l, r)
    return @e if l == r

    sml = @e
    smr = @e
    l += @leaf_size
    r += @leaf_size

    while l < r
      if l[0] == 1
        sml = @op.call(sml, @d[l])
        l += 1
      end
      if r[0] == 1
        r -= 1
        smr = @op.call(@d[r], smr)
      end
      l /= 2
      r /= 2
    end

    @op.call(sml, smr)
  end

  def all_prod
    @d[1]
  end

  def max_right(l, &block)
    return @n if l == @n

    f = proc(&block)

    l += @leaf_size
    sm = @e
    loop do
      l /= 2 while l.even?
      unless f.call(@op.call(sm, @d[l]))
        while l < @leaf_size
          l *= 2
          if f.call(@op.call(sm, @d[l]))
            sm = @op.call(sm, @d[l])
            l += 1
          end
        end

        return l - @leaf_size
      end

      sm = @op.call(sm, @d[l])
      l += 1
      break if (l & -l) == l
    end

    @n
  end

  def min_left(r, &block)
    return 0 if r == 0

    f = proc(&block)

    r += @leaf_size
    sm = @e
    loop do
      r -= 1
      r /= 2 while r > 1 && r.odd?
      unless f.call(@op.call(@d[r], sm))
        while r < @leaf_size
          r = r * 2 + 1
          if f.call(@op.call(@d[r], sm))
            sm = @op.call(@d[r], sm)
            r -= 1
          end
        end

        return r + 1 - @leaf_size
      end

      sm = @op.call(@d[r], sm)
      break if (r & -r) == r
    end

    0
  end

  def update(k)
    @d[k] = @op.call(@d[2 * k], @d[2 * k + 1])
  end

  def inspect
    t = 0
    res = "SegmentTree @e = #{@e}, @n = #{@n}, @leaf_size = #{@leaf_size} @op = #{@op}\n  "
    a = @d[1, @d.size - 1]
    a.each_with_index do |e, i|
      res << e.to_s << ' '
      if t == i && i < @leaf_size
        res << "\n  "
        t = t * 2 + 2
      end
    end
    res
  end
end

main

DEBUG = false
MOD = 10**9+7
YESNO = %w(Yes No)

def main
  t = int
  t.times do
    n = int
    a = ints

    cumax1 = [0] + a
    1.upto(n) { |i| cumax1[i] = cumax1[i-1] if cumax1[i] < cumax1[i-1] }
    cumax2 = a + [0]
    (n-1).downto(0) { |i| cumax1[i] = cumax1[i+1] if cumax1[i] < cumax1[i+1] }
    sum = a.sum

    ans_min = 2e9
    n.times do |i|
      othermax = max(cumax1[i], cumax2[i+1])
      diff = othermax * (n-1) - sum
      diff %= n - 1 if diff < 0
      ans_min = min(ans_min, diff)
    end

    puts ans_min
  end
end

def int; gets.to_i; end
def ints; gets.split.map &:to_i; end
def float; gets.to_f; end
def floats; gets.split.map &:to_f; end
def array(&convert); gets.split.map(&convert); end
def string; gets.chomp; end
def rep(n, &b); Array.new(n, &b); end
def yes; puts YESNO[0]; end
def no; puts YESNO[1]; end
def yesno t; t ? yes : no; end
def zip(xs, *yss); Enumerator.new { |y| xs.zip(*yss) { |a| y.yield(*a) } }; end
def sorted_uniq(xs); x = nil; xs.filter! { |y| c = x === y; x = y; !c }; end
def max(*xs); xs.max; end
def min(*xs); xs.min; end
def minmax(*xs); xs.minmax; end
def matrix(h, w, fill=nil, &block); return Array.new(h) { Array.new(w, &block) } if block_given?; Array.new(h) { [fill] * w }; end
def debug(x); if DEBUG; STDERR.puts (block_given? ? yield(x) : x).inspect; end; x; end
def debug_grid(grid, width = 1); grid.each { |row| STDERR.puts row.map { |x| x.inspect.ljust(width) }.join("") } if DEBUG; grid; end
def if_debug; yield if DEBUG; end

def div_ceil(x, y); (x + y - 1) / y; end
def gcd(*xs); xs.inject(0) { |y, x| y.gcd(x) }; end
def factorial(n, mod); (2..n).inject(1) { |f, x| f * x % mod }; end
def cumsum(xs); ys = [0]; xs.each { |x| ys << x + ys[-1] }; ys; end
def cumdiff(ys); xs = []; xs.inject { |x, y| xs << (d = y - x); d }; end
def cumfold(ys, range); r = range.end; r -= 1 if range.exclusive_end?; ys[r] - ys[range.begin-1]; end
def mod_inv(x, mod); x.pow(mod-2, mod); end
def mod_div(x, y, mod); x * mod_inv(y, mod) % mod; end
def bitbrute(size, &block); (1<<size).times(&block); end

class UnionFind
  def initialize(size); @p, @r = size.times.to_a, [1] * size; end
  def merge(i, j); k, l = leader(i), leader(j); return if k == l; k, l = l, k if @r[k] < @r[l]; @p[l] = k; @r[k] += @r[l]; end
  def size(i); @r[leader(i)]; end
  def same?(i, j); leader(i) == leader(j); end
  def leader(i); j = i; until i == @p[i]; j, i = i, @p[j] = @p[i]; end; i; end
end

main

DEBUG = false
MOD = 10**9+7
YESNO = %w(Yes No)

def main
  t = int
  t.times do
    n = int
    a = ints

    seg = Segtree.new(a, 0) { |x, y| max(x, y) }
    sum = a.sum

    ans_min = 2e9
    n.times do |i|
      othermax = max(seg.prod(0, i), seg.prod(i+1, n))
      p [:max, othermax]
      diff = othermax * (n-1) - sum
      diff %= n - 1 if diff < 0
      ans_min = min(ans_min, diff)
    end

    puts ans_min
  end
end

def int; gets.to_i; end
def ints; gets.split.map &:to_i; end
def float; gets.to_f; end
def floats; gets.split.map &:to_f; end
def array(&convert); gets.split.map(&convert); end
def string; gets.chomp; end
def rep(n, &b); Array.new(n, &b); end
def yes; puts YESNO[0]; end
def no; puts YESNO[1]; end
def yesno t; t ? yes : no; end
def zip(xs, *yss); Enumerator.new { |y| xs.zip(*yss) { |a| y.yield(*a) } }; end
def sorted_uniq(xs); x = nil; xs.filter! { |y| c = x === y; x = y; !c }; end
def max(*xs); xs.max; end
def min(*xs); xs.min; end
def minmax(*xs); xs.minmax; end
def matrix(h, w, fill=nil, &block); return Array.new(h) { Array.new(w, &block) } if block_given?; Array.new(h) { [fill] * w }; end
def debug(x); if DEBUG; STDERR.puts (block_given? ? yield(x) : x).inspect; end; x; end
def debug_grid(grid, width = 1); grid.each { |row| STDERR.puts row.map { |x| x.inspect.ljust(width) }.join("") } if DEBUG; grid; end
def if_debug; yield if DEBUG; end

def div_ceil(x, y); (x + y - 1) / y; end
def gcd(*xs); xs.inject(0) { |y, x| y.gcd(x) }; end
def factorial(n, mod); (2..n).inject(1) { |f, x| f * x % mod }; end
def cumsum(xs); ys = [0]; xs.each { |x| ys << x + ys[-1] }; ys; end
def cumdiff(ys); xs = []; xs.inject { |x, y| xs << (d = y - x); d }; end
def cumfold(ys, range); r = range.end; r -= 1 if range.exclusive_end?; ys[r] - ys[range.begin-1]; end
def mod_inv(x, mod); x.pow(mod-2, mod); end
def mod_div(x, y, mod); x * mod_inv(y, mod) % mod; end
def bitbrute(size, &block); (1<<size).times(&block); end

class UnionFind
  def initialize(size); @p, @r = size.times.to_a, [1] * size; end
  def merge(i, j); k, l = leader(i), leader(j); return if k == l; k, l = l, k if @r[k] < @r[l]; @p[l] = k; @r[k] += @r[l]; end
  def size(i); @r[leader(i)]; end
  def same?(i, j); leader(i) == leader(j); end
  def leader(i); j = i; until i == @p[i]; j, i = i, @p[j] = @p[i]; end; i; end
end

# Segment Tree
class Segtree
  attr_reader :d, :op, :n, :leaf_size, :log

  def initialize(arg = 0, e, &block)
    case arg
    when Integer
      v = Array.new(arg) { e }
    when Array
      v = arg
    end

    @e  = e
    @op = proc(&block)

    @n = v.size
    @log = (@n - 1).bit_length
    @leaf_size = 1 << @log
    @d = Array.new(@leaf_size * 2) { e }
    v.each_with_index { |v_i, i| @d[@leaf_size + i] = v_i }
    (@leaf_size - 1).downto(1) { |i| update(i) }
  end

  def set(q, x)
    q += @leaf_size
    @d[q] = x
    1.upto(@log) { |i| update(q >> i) }
  end

  def get(pos)
    @d[@leaf_size + pos]
  end

  def prod(l, r)
    return @e if l == r

    sml = @e
    smr = @e
    l += @leaf_size
    r += @leaf_size

    while l < r
      if l[0] == 1
        sml = @op.call(sml, @d[l])
        l += 1
      end
      if r[0] == 1
        r -= 1
        smr = @op.call(@d[r], smr)
      end
      l /= 2
      r /= 2
    end

    @op.call(sml, smr)
  end

  def all_prod
    @d[1]
  end

  def max_right(l, &block)
    return @n if l == @n

    f = proc(&block)

    l += @leaf_size
    sm = @e
    loop do
      l /= 2 while l.even?
      unless f.call(@op.call(sm, @d[l]))
        while l < @leaf_size
          l *= 2
          if f.call(@op.call(sm, @d[l]))
            sm = @op.call(sm, @d[l])
            l += 1
          end
        end

        return l - @leaf_size
      end

      sm = @op.call(sm, @d[l])
      l += 1
      break if (l & -l) == l
    end

    @n
  end

  def min_left(r, &block)
    return 0 if r == 0

    f = proc(&block)

    r += @leaf_size
    sm = @e
    loop do
      r -= 1
      r /= 2 while r > 1 && r.odd?
      unless f.call(@op.call(@d[r], sm))
        while r < @leaf_size
          r = r * 2 + 1
          if f.call(@op.call(@d[r], sm))
            sm = @op.call(@d[r], sm)
            r -= 1
          end
        end

        return r + 1 - @leaf_size
      end

      sm = @op.call(@d[r], sm)
      break if (r & -r) == r
    end

    0
  end

  def update(k)
    @d[k] = @op.call(@d[2 * k], @d[2 * k + 1])
  end

  def inspect
    t = 0
    res = "SegmentTree @e = #{@e}, @n = #{@n}, @leaf_size = #{@leaf_size} @op = #{@op}\n  "
    a = @d[1, @d.size - 1]
    a.each_with_index do |e, i|
      res << e.to_s << ' '
      if t == i && i < @leaf_size
        res << "\n  "
        t = t * 2 + 2
      end
    end
    res
  end
end

main


Overall there are m actors in Berland. Each actor has a personal identifier — an integer from 1 to m (distinct actors have distinct identifiers). Vasya likes to watch Berland movies with Berland actors, and he has k favorite actors. He watched the movie trailers for the next month and wrote the following information for every movie: the movie title, the number of actors who starred in it, and the identifiers of these actors. Besides, he managed to copy the movie titles and how many actors starred there, but he didn't manage to write down the identifiers of some actors. Vasya looks at his records and wonders which movies may be his favourite, and which ones may not be. Once Vasya learns the exact cast of all movies, his favorite movies will be determined as follows: a movie becomes favorite movie, if no other movie from Vasya's list has more favorite actors.Help the boy to determine the following for each movie: whether it surely will be his favourite movie; whether it surely won't be his favourite movie;  can either be favourite or not.

The first line of the input contains two integers m and k (1 ≤ m ≤ 100, 1 ≤ k ≤ m) — the number of actors in Berland and the number of Vasya's favourite actors.  The second line contains k distinct integers ai (1 ≤ ai ≤ m) — the identifiers of Vasya's favourite actors. The third line contains a single integer n (1 ≤ n ≤ 100) — the number of movies in Vasya's list. Then follow n blocks of lines, each block contains a movie's description. The i-th movie's description contains three lines:    the first line contains string si (si consists of lowercase English letters and can have the length of from 1 to 10 characters, inclusive) — the movie's title,  the second line contains a non-negative integer di (1 ≤ di ≤ m) — the number of actors who starred in this movie, the third line has di integers bi, j (0 ≤ bi, j ≤ m) — the identifiers of the actors who star in this movie. If bi, j = 0, than Vasya doesn't remember the identifier of the j-th actor. It is guaranteed that the list of actors for a movie doesn't contain the same actors.  All movies have distinct names. The numbers on the lines are separated by single spaces.

Print n lines in the output. In the i-th line print:    0, if the i-th movie will surely be the favourite;  1, if the i-th movie won't surely be the favourite;  2, if the i-th movie can either be favourite, or not favourite.

5 3
1 2 3
6
firstfilm
3
0 0 0
secondfilm
4
0 0 4 5
thirdfilm
1
2
fourthfilm
1
5
fifthfilm
1
4
sixthfilm
2
1 0

5 3
1 3 5
4
jumanji
3
0 0 0
theeagle
5
1 2 3 4 0
matrix
3
2 4 0
sourcecode
2
2 4

NoteNote to the second sample:   Movie jumanji can theoretically have from 1 to 3 Vasya's favourite actors.  Movie theeagle has all three favourite actors, as the actor Vasya failed to remember, can only have identifier 5.  Movie matrix can have exactly one favourite actor.  Movie sourcecode doesn't have any favourite actors. Thus, movie theeagle will surely be favourite, movies matrix and sourcecode won't surely be favourite, and movie jumanji can be either favourite (if it has all three favourite actors), or not favourite.

if ENV['USER'] != 'watashi'
  $stdin = open('input.txt')
  $> = open('output.txt', 'w')
end

I = ->{gets.split.map(&:to_i)}
m, k = I[]
f = I[]
n, _ = I[]
a = Array.new(n){
  I[]
  I[]
  b = I[]
  x = b.count{|_| f.index(_)}
  y = b.count(0)
  [[x + y, k].min, [x, b.size - (m - k)].max]
}
puts a.map{|i|
  a.all?{|j| i === j || i[1] >= j[0]} ?
    0 :
    a.all?{|j| i[0] >= j[1]} ? 2 : 1
} * "\n"


This morning Tolik has understood that while he was sleeping he had invented an incredible problem which will be a perfect fit for Codeforces! But, as a "Discuss tasks" project hasn't been born yet (in English, well), he decides to test a problem and asks his uncle.After a long time thinking, Tolik's uncle hasn't any ideas on how to solve it. But, he doesn't want to tell Tolik about his inability to solve it, so he hasn't found anything better than asking you how to solve this task.In this task you are given a cell field $$$n \cdot m$$$, consisting of $$$n$$$ rows and $$$m$$$ columns, where point's coordinates $$$(x, y)$$$ mean it is situated in the $$$x$$$-th row and $$$y$$$-th column, considering numeration from one ($$$1 \leq x \leq n, 1 \leq y \leq m$$$). Initially, you stand in the cell $$$(1, 1)$$$. Every move you can jump from cell $$$(x, y)$$$, which you stand in, by any non-zero vector $$$(dx, dy)$$$, thus you will stand in the $$$(x+dx, y+dy)$$$ cell. Obviously, you can't leave the field, but also there is one more important condition — you're not allowed to use one vector twice. Your task is to visit each cell of the field exactly once (the initial cell is considered as already visited).Tolik's uncle is a very respectful person. Help him to solve this task!

The first and only line contains two positive integers $$$n, m$$$ ($$$1 \leq n \cdot m \leq 10^{6}$$$) — the number of rows and columns of the field respectively.

Print "-1" (without quotes) if it is impossible to visit every cell exactly once. Else print $$$n \cdot m$$$ pairs of integers, $$$i$$$-th from them should contain two integers $$$x_i, y_i$$$ ($$$1 \leq x_i \leq n, 1 \leq y_i \leq m$$$) — cells of the field in order of visiting, so that all of them are distinct and vectors of jumps between them are distinct too. Notice that the first cell should have $$$(1, 1)$$$ coordinates, according to the statement.

NoteThe vectors from the first example in the order of making jumps are $$$(0, 2), (0, -1), (1, 0), (0, 1), (0, -2)$$$.


Vasya's house is situated in a forest, and there is a mushroom glade near it. The glade consists of two rows, each of which can be divided into n consecutive cells. For each cell Vasya knows how fast the mushrooms grow in this cell (more formally, how many grams of mushrooms grow in this cell each minute). Vasya spends exactly one minute to move to some adjacent cell. Vasya cannot leave the glade. Two cells are considered adjacent if they share a common side. When Vasya enters some cell, he instantly collects all the mushrooms growing there.Vasya begins his journey in the left upper cell. Every minute Vasya must move to some adjacent cell, he cannot wait for the mushrooms to grow. He wants to visit all the cells exactly once and maximize the total weight of the collected mushrooms. Initially, all mushrooms have a weight of 0. Note that Vasya doesn't need to return to the starting cell.Help Vasya! Calculate the maximum total weight of mushrooms he can collect.

The first line contains the number n (1 ≤ n ≤ 3·105) — the length of the glade. The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 106) — the growth rate of mushrooms in the first row of the glade. The third line contains n numbers b1, b2, ..., bn (1 ≤ bi ≤ 106) is the growth rate of mushrooms in the second row of the glade.

Output one number — the maximum total weight of mushrooms that Vasya can collect by choosing the optimal route. Pay attention that Vasya must visit every cell of the glade exactly once.

NoteIn the first test case, the optimal route is as follows:    Thus, the collected weight of mushrooms will be 0·1 + 1·2 + 2·3 + 3·4 + 4·5 + 5·6 = 70.In the second test case, the optimal route is as follows:    Thus, the collected weight of mushrooms will be 0·1 + 1·10 + 2·100 + 3·1000 + 4·10000 + 5·100000 = 543210.


A permutation of length $$$n$$$ is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).For a positive integer $$$n$$$, we call a permutation $$$p$$$ of length $$$n$$$ good if the following condition holds for every pair $$$i$$$ and $$$j$$$ ($$$1 \le i \le j \le n$$$) —   $$$(p_i \text{ OR } p_{i+1} \text{ OR } \ldots \text{ OR } p_{j-1} \text{ OR } p_{j}) \ge j-i+1$$$, where $$$\text{OR}$$$ denotes the bitwise OR operation. In other words, a permutation $$$p$$$ is good if for every subarray of $$$p$$$, the $$$\text{OR}$$$ of all elements in it is not less than the number of elements in that subarray. Given a positive integer $$$n$$$, output any good permutation of length $$$n$$$. We can show that for the given constraints such a permutation always exists.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first and only line of every test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$).

For every test, output any good permutation of length $$$n$$$ on a separate line.

t = gets.chomp.to_i
t.times do
    n = gets.chomp.to_i
    n.downto (1) do |i|
        print i
        if i != 1
        print " "
        elsif i == 1
            print "\n"
        end
    end
end

t = gets.to_i
ans = []
t.times do
  n = gets.to_i
  arr = []
  n.times do |i|
    arr << i+1
  end
  ans << arr
end
ans.each do |ar|
  ar.each do |x|
    print "#{x} "
  end
  puts ""
end


Palo Alto is an unusual city because it is an endless coordinate line. It is also known for the office of Lyft Level 5.Lyft has become so popular so that it is now used by all $$$m$$$ taxi drivers in the city, who every day transport the rest of the city residents — $$$n$$$ riders.Each resident (including taxi drivers) of Palo-Alto lives in its unique location (there is no such pair of residents that their coordinates are the same).The Lyft system is very clever: when a rider calls a taxi, his call does not go to all taxi drivers, but only to the one that is the closest to that person. If there are multiple ones with the same distance, then to taxi driver with a smaller coordinate is selected.But one morning the taxi drivers wondered: how many riders are there that would call the given taxi driver if they were the first to order a taxi on that day? In other words, you need to find for each taxi driver $$$i$$$ the number $$$a_{i}$$$ — the number of riders that would call the $$$i$$$-th taxi driver when all drivers and riders are at their home?The taxi driver can neither transport himself nor other taxi drivers.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n,m \le 10^5$$$) — number of riders and taxi drivers. The second line contains $$$n + m$$$ integers $$$x_1, x_2, \ldots, x_{n+m}$$$ ($$$1 \le x_1 < x_2 < \ldots < x_{n+m} \le 10^9$$$), where $$$x_i$$$ is the coordinate where the $$$i$$$-th resident lives.  The third line contains $$$n + m$$$ integers $$$t_1, t_2, \ldots, t_{n+m}$$$ ($$$0 \le t_i \le 1$$$). If $$$t_i = 1$$$, then the $$$i$$$-th resident is a taxi driver, otherwise $$$t_i = 0$$$. It is guaranteed that the number of $$$i$$$ such that $$$t_i = 1$$$ is equal to $$$m$$$.

Print $$$m$$$ integers $$$a_1, a_2, \ldots, a_{m}$$$, where $$$a_i$$$ is the answer for the $$$i$$$-th taxi driver. The taxi driver has the number $$$i$$$ if among all the taxi drivers he lives in the $$$i$$$-th smallest coordinate (see examples for better understanding).

NoteIn the first example, we have only one taxi driver, which means an order from any of $$$n$$$ riders will go to him.In the second example, the first taxi driver lives at the point with the coordinate $$$2$$$, and the second one lives at the point with the coordinate $$$6$$$. Obviously, the nearest taxi driver to the rider who lives on the $$$3$$$ coordinate is the first one, and to the rider who lives on the coordinate $$$5$$$ is the second one. The rider who lives on the $$$4$$$ coordinate has the same distance to the first and the second taxi drivers, but since the first taxi driver has a smaller coordinate, the call from this rider will go to the first taxi driver.In the third example, we have one rider and the taxi driver nearest to him is the fourth one.

n, m = gets.split.map(&:to_i)
X = gets.split.map(&:to_i)
T = gets.split.map(&:to_i)

TM = X.select.with_index do |val, i|
  T[i] != 0
end

XR = X.select.with_index do |val, i|
  T[i] == 0
end

R = Array.new(m, 0)

i = 0
XR.each do |x|
  i += 1 while i < (m - 1) && (TM[i + 1] - x).abs < (TM[i] - x).abs
  R[i] += 1
end

R.each { |x| print(x, " ") }


Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of length $$$k$$$ have the same sum. A subarray of an array is any sequence of consecutive elements.Phoenix currently has an array $$$a$$$ of length $$$n$$$. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautiful. The inserted integers must be between $$$1$$$ and $$$n$$$ inclusive. Integers may be inserted anywhere (even before the first or after the last element), and he is not trying to minimize the number of inserted integers.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 50$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 100$$$). The second line of each test case contains $$$n$$$ space-separated integers ($$$1 \le a_i \le n$$$) — the array that Phoenix currently has. This array may or may not be already beautiful.

For each test case, if it is impossible to create a beautiful array, print -1. Otherwise, print two lines. The first line should contain the length of the beautiful array $$$m$$$ ($$$n \le m \le 10^4$$$). You don't need to minimize $$$m$$$. The second line should contain $$$m$$$ space-separated integers ($$$1 \le b_i \le n$$$) — a beautiful array that Phoenix can obtain after inserting some, possibly zero, integers into his array $$$a$$$. You may print integers that weren't originally in array $$$a$$$. If there are multiple solutions, print any. It's guaranteed that if we can make array $$$a$$$ beautiful, we can always make it with resulting length no more than $$$10^4$$$.

NoteIn the first test case, we can make array $$$a$$$ beautiful by inserting the integer $$$1$$$ at index $$$3$$$ (in between the two existing $$$2$$$s). Now, all subarrays of length $$$k=2$$$ have the same sum $$$3$$$. There exists many other possible solutions, for example:   $$$2, 1, 2, 1, 2, 1$$$  $$$1, 2, 1, 2, 1, 2$$$ In the second test case, the array is already beautiful: all subarrays of length $$$k=3$$$ have the same sum $$$5$$$.In the third test case, it can be shown that we cannot insert numbers to make array $$$a$$$ beautiful.In the fourth test case, the array $$$b$$$ shown is beautiful and all subarrays of length $$$k=4$$$ have the same sum $$$10$$$. There exist other solutions also.

require 'set'

$cpp = []
def solve arr, k
  return [arr.length, arr] if arr.length == k
  uniq = arr.to_set
  return [-1, nil] if uniq.length > k
  expect = uniq.to_a
  expect << 1 while expect.length < k
  idx = 0
  iter = 0
  arr.each do |i|
    until i == expect[idx % k]
      $cpp << expect[idx % k]
      idx += 1
    end
    $cpp << i
    idx += 1
  end
  [$cpp.length, $cpp]
end

t = STDIN.gets.chomp.to_i

(1..t).each do |i|
  n, k = STDIN.gets.chomp.split.map {|i| i.to_i}
  arr = STDIN.gets.chomp.split.map {|i| i.to_i}
  res = solve arr, k
  puts res[0]
  puts res[1].join(" ") unless res[0] == -1
  $cpp = []
end

require 'set'

def solve arr, k
  return [arr.length, arr] if arr.length == k
  uniq = arr.to_set
  return [-1, nil] if uniq.length > k
  res = []
  expect = uniq.to_a
  expect << 1 while expect.length < k
  idx = 0
  iter = 0
  arr.each do |i|
    until i == expect[idx % k]
      res << expect[idx % k]
      idx += 1
    end
    res << i
    idx += 1
  end
  [res.length, res]
end

t = STDIN.gets.chomp.to_i

(1..t).each do |i|
  n, k = STDIN.gets.chomp.split.map {|i| i.to_i}
  arr = STDIN.gets.chomp.split.map {|i| i.to_i}
  res = solve arr, k
  puts res[0]
  puts res[1].join(" ") unless res[0] == -1
end


A widely known among some people Belarusian sport programmer Lesha decided to make some money to buy a one square meter larger flat. To do this, he wants to make and carry out a Super Rated Match (SRM) on the site Torcoder.com. But there's a problem — a severe torcoder coordinator Ivan does not accept any Lesha's problem, calling each of them an offensive word "duped" (that is, duplicated). And one day they nearely quarrelled over yet another problem Ivan wouldn't accept.You are invited to act as a fair judge and determine whether the problem is indeed brand new, or Ivan is right and the problem bears some resemblance to those used in the previous SRMs.You are given the descriptions of Lesha's problem and each of Torcoder.com archive problems. The description of each problem is a sequence of words. Besides, it is guaranteed that Lesha's problem has no repeated words, while the description of an archive problem may contain any number of repeated words.The "similarity" between Lesha's problem and some archive problem can be found as follows. Among all permutations of words in Lesha's problem we choose the one that occurs in the archive problem as a subsequence. If there are multiple such permutations, we choose the one with the smallest number of inversions. Then the "similarity" of a problem can be written as , where n is the number of words in Lesha's problem and x is the number of inversions in the chosen permutation. Note that the "similarity" p is always a positive integer.The problem is called brand new if there is not a single problem in Ivan's archive which contains a permutation of words from Lesha's problem as a subsequence.Help the boys and determine whether the proposed problem is new, or specify the problem from the archive which resembles Lesha's problem the most, otherwise.

The first line contains a single integer n (1 ≤ n ≤ 15) — the number of words in Lesha's problem. The second line contains n space-separated words — the short description of the problem. The third line contains a single integer m (1 ≤ m ≤ 10) — the number of problems in the Torcoder.com archive. Next m lines contain the descriptions of the problems as "k s1 s2 ... sk", where k (1 ≤ k ≤ 500000) is the number of words in the problem and si is a word of the problem description. All words from all problem descriptions contain no more than 10 lowercase English letters. It is guaranteed that the total length of words in all problem descriptions does not exceed 500015.

If Lesha's problem is brand new, print string "Brand new problem!" (without quotes).  Otherwise, on the first line print the index of the archive problem which resembles Lesha's problem most. If there are multiple such problems, print the one with the smallest index. On the second line print a string consisting of characters [:, character | repeated p times, and characters :], where p is the "similarity" between this problem and Lesha's one. The archive problems are numbered starting from one in the order in which they are given in the input.

4
find the next palindrome
1
10 find the previous palindrome or print better luck next time

3
add two numbers
3
1 add
2 two two
3 numbers numbers numbers

4
these papers are formulas
3
6 what are these formulas and papers
5 papers are driving me crazy
4 crazy into the night

3
add two decimals
5
4 please two decimals add
5 decimals want to be added
4 two add decimals add
4 add one two three
7 one plus two plus three equals six

NoteLet us remind you that the number of inversions is the number of pairs of words that follow in the permutation not in their original order. Thus, for example, if the original problem is "add two numbers", then permutation "numbers add two" contains two inversions — pairs of words "numbers" and "add", "numbers" and "two". Sequence b1,  b2,  ...,  bk is a subsequence of sequence a1, a2,  ...,  an if there exists such a set of indices 1 ≤ i1 <  i2 < ...   < ik ≤ n that aij  =  bj (in other words, if sequence b can be obtained from a by deleting some of its elements).In the first test case the first problem contains the "find the palindrome next" permutation as a subsequence, in which the number of inversions equals 1 (words "palindrome" and "next").In the second test case there is no problem that contains a permutation of words from Lesha's problem as a subsequence.

#!/usr/bin/ruby1.9

n = STDIN.readline.to_i
problem = STDIN.readline.split
m = STDIN.readline.to_i

best_candidate_index = -1
max_similarity = 0

def find_similarity(problem, pi, candidate, ci, permutation)
	return 0 if ci == candidate.length
	a = find_similarity(problem, pi, candidate, ci+1, permutation)
	permutation[pi] = candidate[ci]
	if pi+1 < problem.length
		b = find_similarity(problem, pi+1, candidate, ci+1, permutation)
	elsif permutation.sort != problem.sort
		b = 0
	else
		invert = []
		permutation.each {|word| invert.push(problem.index(word)) }
		x = 0
		n = invert.length
		n.times do |j|
			j.times do |i|
				x += 1 if invert[i] > invert[j]
			end
		end
		b = n*(n-1)/2 - x + 1
	end
	return (a > b ? a : b)
end

m.times do |candidate_index|
	candidate = STDIN.readline.split[1..-1]
	permutation = Array.new(n)
	similarity = find_similarity(problem, 0, candidate, 0, permutation)
	if similarity > max_similarity
		max_similarity = similarity
		best_candidate_index = candidate_index
	end
end

if max_similarity == 0
	puts 'Brand new problem!'
else
	puts best_candidate_index+1
	puts '[:%s:]' % ('|'*max_similarity)
end


Some people leave the lights at their workplaces on when they leave that is a waste of resources. As a hausmeister of DHBW, Sagheer waits till all students and professors leave the university building, then goes and turns all the lights off.The building consists of n floors with stairs at the left and the right sides. Each floor has m rooms on the same line with a corridor that connects the left and right stairs passing by all the rooms. In other words, the building can be represented as a rectangle with n rows and m + 2 columns, where the first and the last columns represent the stairs, and the m columns in the middle represent rooms.Sagheer is standing at the ground floor at the left stairs. He wants to turn all the lights off in such a way that he will not go upstairs until all lights in the floor he is standing at are off. Of course, Sagheer must visit a room to turn the light there off. It takes one minute for Sagheer to go to the next floor using stairs or to move from the current room/stairs to a neighboring room/stairs on the same floor. It takes no time for him to switch the light off in the room he is currently standing in. Help Sagheer find the minimum total time to turn off all the lights.Note that Sagheer does not have to go back to his starting position, and he does not have to visit rooms where the light is already switched off.

The first line contains two integers n and m (1 ≤ n ≤ 15 and 1 ≤ m ≤ 100) — the number of floors and the number of rooms in each floor, respectively. The next n lines contains the building description. Each line contains a binary string of length m + 2 representing a floor (the left stairs, then m rooms, then the right stairs) where 0 indicates that the light is off and 1 indicates that the light is on. The floors are listed from top to bottom, so that the last line represents the ground floor. The first and last characters of each string represent the left and the right stairs, respectively, so they are always 0.

Print a single integer — the minimum total time needed to turn off all the lights.

NoteIn the first example, Sagheer will go to room 1 in the ground floor, then he will go to room 2 in the second floor using the left or right stairs.In the second example, he will go to the fourth room in the ground floor, use right stairs, go to the fourth room in the second floor, use right stairs again, then go to the second room in the last floor.In the third example, he will walk through the whole corridor alternating between the left and right stairs at each floor.

def normalize(a)
  a.length.times do |i|
    l = a[i].index('1')
    r = a[i].rindex('1')
    l = l + 1 if l != nil
    r = r + 1 if r != nil
    a[i] = {:l => l, :r => r}
  end
end

n, m = gets.chomp.split.map(&:to_i)
m += 2
a = []
cur_pos = 1
ans = n * m

vars = [:l, :r].repeated_permutation(n).to_a

n.times do |x|
  a.push(gets.chomp)
end

a.reverse!
normalize(a)

while n > 0 and a[-1][:l] == nil
  n -= 1
  a.pop
end

if n == 0
  puts 0
  exit
end

vars.length.times do |i|
  if vars[i][0] != :r
    lans = 0
    (1..n-1).each do |j|
      if vars[i][j-1] != vars[i][j]
        lans += (m - 1)
      elsif a[j-1][:l] == nil
        lans += 0
      elsif vars[i][j] == :r
        lans += (m - a[j-1][:l]) * 2
      elsif vars[i][j] == :l
        lans += (a[j-1][:r] - 1) * 2
      end
    end
    if a[n-1][:l] == nil
      lans += 0
    elsif vars[i][n-1] == :r
      lans += (m - a[n-1][:l])
    else
      lans += (a[n-1][:r] - 1)
    end
    if lans < ans
      ans = lans
    end
  end
end

ans += n - 1
puts ans

N, M = gets.chomp.split(" ").map(&:to_i)
$bldg = Array.new()

nflr = 0
N.times do
  flr = gets.chomp.split("").map(&:to_i)
  $bldg << flr
  nflr += 1 if flr.include?(1)
end
$bldg.reverse!
$ret = []

def hausmeister(i, s, t, last)
  curr = 0
  flr = $bldg[i]
  if flr.include?(1) then
    if s == 0 then
      pos = flr.rindex(1)
      curr += pos
    else
      pos = flr.index(1)
      curr += (M + 2 - pos - 1)
    end
    left = pos + 1
    right = M + 2 - pos
    if i == N - 1 then
      $ret << t + curr
      return t + curr
    end
    hausmeister(i+1, 0, t + curr + left, left)
    hausmeister(i+1, -1, t + curr + right, right)
  else
    if i == N - 1 then
      $ret << t - last
      return t - last
    end
    if s == 0 then
      pos = 0
    else
      pos = M + 1
    end
    left = pos + 1
    right = M + 2 - pos
    hausmeister(i+1, 0, t + left, last + left)
    hausmeister(i+1, -1, t + right, last + right)
  end
end
if nflr > 0 then
  hausmeister(0, 0, 0, 0)
  puts $ret.min
else
  puts 0
end

n, M = gets.chomp.split(" ").map(&:to_i)
$bldg = Array.new()
n.times do
  flr = gets.chomp.split("").map(&:to_i)
  $bldg << flr if flr.include?(1)
end
$bldg.reverse!
$ret = []
N = $bldg.length
def hausmeister(i, s, t)
  curr = 0
  flr = $bldg[i]

  if flr.include?(1) then
    if s == 0 then
      pos = flr.rindex(1)
      curr += pos
    else
      pos = flr.index(1)
      curr += (M + 2 - pos - 1)
    end
    left = pos + 1
    right = M + 2 - pos
    if i == N - 1 then
      $ret << t + curr
      return t + curr
    end
    hausmeister(i+1, 0, t + curr + left)
    hausmeister(i+1, -1, t + curr + right)
  else
    if i == N - 1 then
      $ret << t
      return t + curr
    end
    if s == 0 then
      pos = 0
    else
      pos = M + 1
    end
    left = pos + 1
    right = M + 2 - pos
    hausmeister(i+1, 0, t + left)
    hausmeister(i+1, -1, t + right)
  end
end
if N > 0 then
  hausmeister(0, 0, 0)
  puts $ret.min
else
  puts 0
end

N, M = gets.chomp.split(" ").map(&:to_i)
$bldg = Array.new()
N.times do
  flr = gets.chomp.split("").map(&:to_i)
  $bldg << flr
end
$bldg.reverse!
$ret = []
def hausmeister(i, s, t)
  curr = 0
  flr = $bldg[i]

  nlight = flr.inject(:+)
  if nlight > 0 then
    if s == 0 then
      pos = flr.rindex(1)
      curr += pos
    else
      pos = flr.index(1)
      curr += (M + 2 - pos - 1)
    end
    left = pos + 1
    right = M + 2 - pos
    if i == N - 1 then
      $ret << t + curr
      return t + curr
    end
    hausmeister(i+1, 0, t + curr + left)
    hausmeister(i+1, -1, t + curr + right)
  else
    if i == N - 1 then
      $ret << t + curr
      return t + curr
    end
    if s == 0 then
      pos = 0
    else
      pos = M + 1
    end
    left = pos + 1
    right = M + 2 - pos
    hausmeister(i+1, 0, t + left)
    hausmeister(i+1, -1, t + right)
  end
end

hausmeister(0, 0, 0)
puts $ret.min

N, M = gets.chomp.split(" ").map(&:to_i)
$bldg = Array.new()

nflr = 0
N.times do
  flr = gets.chomp.split("").map(&:to_i)
  $bldg << flr
  nflr += 1 if flr.include?(1)
end
$bldg.reverse!
$ret = []

def hausmeister(i, s, t, last)
  curr = 0
  flr = $bldg[i]
  if flr.include?(1) then
    if s == 0 then
      pos = flr.rindex(1)
      curr += pos
    else
      pos = flr.index(1)
      curr += (M + 2 - pos - 1)
    end
    left = pos + 1
    right = M + 2 - pos
    if i == N - 1 then
      $ret << t + curr
      return t + curr
    end
    hausmeister(i+1, 0, t + curr + left, left)
    hausmeister(i+1, -1, t + curr + right, right)
  else
    if i == N - 1 then
      $ret << t - last
      return t - last
    end
    if s == 0 then
      pos = 0
    else
      pos = M + 1
    end
    left = pos + 1
    right = M + 2 - pos
    hausmeister(i+1, 0, t + left, left)
    hausmeister(i+1, -1, t + right, right)
  end
end
if nflr > 0 then
  hausmeister(0, 0, 0, 0)
  puts $ret.min
else
  puts 0
end


Vasya became interested in bioinformatics. He's going to write an article about similar cyclic DNA sequences, so he invented a new method for determining the similarity of cyclic sequences.Let's assume that strings s and t have the same length n, then the function h(s, t) is defined as the number of positions in which the respective symbols of s and t are the same. Function h(s, t) can be used to define the function of Vasya distance ρ(s, t):  where  is obtained from string s, by applying left circular shift i times. For example, ρ("AGC", "CGT") =  h("AGC", "CGT") + h("AGC", "GTC") + h("AGC", "TCG") +  h("GCA", "CGT") + h("GCA", "GTC") + h("GCA", "TCG") +  h("CAG", "CGT") + h("CAG", "GTC") + h("CAG", "TCG") =  1 + 1 + 0 + 0 + 1 + 1 + 1 + 0 + 1 = 6Vasya found a string s of length n on the Internet. Now he wants to count how many strings t there are such that the Vasya distance from the string s attains maximum possible value. Formally speaking, t must satisfy the equation: .Vasya could not try all possible strings to find an answer, so he needs your help. As the answer may be very large, count the number of such strings modulo 109 + 7.

The first line of the input contains a single integer n (1 ≤ n ≤ 105). The second line of the input contains a single string of length n, consisting of characters "ACGT".

Print a single number — the answer modulo 109 + 7.

NotePlease note that if for two distinct strings t1 and t2 values ρ(s, t1) и ρ(s, t2) are maximum among all possible t, then both strings must be taken into account in the answer even if one of them can be obtained by a circular shift of another one.In the first sample, there is ρ("C", "C") = 1, for the remaining strings t of length 1 the value of ρ(s, t) is 0.In the second sample, ρ("AG", "AG") = ρ("AG", "GA") = ρ("AG", "AA") = ρ("AG", "GG") = 4.In the third sample, ρ("TTT", "TTT") = 27

n=gets.to_i
s=gets
a="ACGT".chars.map{|c|s.count(c)}
p (a.count(a.max)**n)%1000000007

n = gets.to_i
s = gets.chomp
m = [s.count("A"), s.count("C"), s.count("T"), s.count("G")]
cntmax = m.max
cnt = 0
m.each{|mm| cnt += 1 if mm == cntmax}
puts (cnt**n)%(10**9+7)

n=gets.to_i
s=gets
a="ACGT".chars.map{|c|s.count(c)}.sort-[0]
b=a.chunk{|i|i}
c=b.map{|k,v|[k,k*v.size]}
d=b.map{|k,v|v.size**(k*v.size)}.inject(:*)
p (1..n).inject(:*)/c.map{|_,i|(1..i).inject(:*)}.inject(:*)*d%1000000007


You are given two integers $$$A$$$ and $$$B$$$, calculate the number of pairs $$$(a, b)$$$ such that $$$1 \le a \le A$$$, $$$1 \le b \le B$$$, and the equation $$$a \cdot b + a + b = conc(a, b)$$$ is true; $$$conc(a, b)$$$ is the concatenation of $$$a$$$ and $$$b$$$ (for example, $$$conc(12, 23) = 1223$$$, $$$conc(100, 11) = 10011$$$). $$$a$$$ and $$$b$$$ should not contain leading zeroes.

The first line contains $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each test case contains two integers $$$A$$$ and $$$B$$$ $$$(1 \le A, B \le 10^9)$$$.

Print one integer — the number of pairs $$$(a, b)$$$ such that $$$1 \le a \le A$$$, $$$1 \le b \le B$$$, and the equation $$$a \cdot b + a + b = conc(a, b)$$$ is true.

NoteThere is only one suitable pair in the first test case: $$$a = 1$$$, $$$b = 9$$$ ($$$1 + 9 + 1 \cdot 9 = 19$$$).

T = gets.to_i

T.times do
  a, b = gets.split.map(&:to_i)

  cnt = 0

  1.upto(b.to_s.size) do |n|
    s = ('9' * n).to_i

    cnt += 1 if s <= b
  end

  puts a * cnt
end


Asya loves animals very much. Recently, she purchased $$$n$$$ kittens, enumerated them from $$$1$$$ and $$$n$$$ and then put them into the cage. The cage consists of one row of $$$n$$$ cells, enumerated with integers from $$$1$$$ to $$$n$$$ from left to right. Adjacent cells had a partially transparent partition wall between them, hence there were $$$n - 1$$$ partitions originally. Initially, each cell contained exactly one kitten with some number.Observing the kittens, Asya noticed, that they are very friendly and often a pair of kittens in neighboring cells wants to play together. So Asya started to remove partitions between neighboring cells. In particular, on the day $$$i$$$, Asya:  Noticed, that the kittens $$$x_i$$$ and $$$y_i$$$, located in neighboring cells want to play together.  Removed the partition between these two cells, efficiently creating a single cell, having all kittens from two original cells. Since Asya has never putted partitions back, after $$$n - 1$$$ days the cage contained a single cell, having all kittens.For every day, Asya remembers numbers of kittens $$$x_i$$$ and $$$y_i$$$, who wanted to play together, however she doesn't remember how she placed kittens in the cage in the beginning. Please help her and find any possible initial arrangement of the kittens into $$$n$$$ cells.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 150\,000$$$) — the number of kittens. Each of the following $$$n - 1$$$ lines contains integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$) — indices of kittens, which got together due to the border removal on the corresponding day. It's guaranteed, that the kittens $$$x_i$$$ and $$$y_i$$$ were in the different cells before this day.

For every cell from $$$1$$$ to $$$n$$$ print a single integer — the index of the kitten from $$$1$$$ to $$$n$$$, who was originally in it. All printed integers must be distinct. It's guaranteed, that there is at least one answer possible. In case there are multiple possible answers, print any of them.

NoteThe answer for the example contains one of several possible initial arrangements of the kittens.The picture below shows how the cells were united for this initial arrangement. Note, that the kittens who wanted to play together on each day were indeed in adjacent cells.

def init(n)
  n.times do |i|
    Parent[i] = i
    Next[i] = nil
    Last[i] = i
    Rank[i] = 0
  end
end

def find(x)
  if Parent[x] == x
    return x
  else
    return Parent[x] = find(Parent[x])
  end
end

def unite(x,y)
  x,y = find(x),find(y)
  return if x==y

  x,y = y,x if Rank[x] < Rank[y]
  Rank[x] += 1 if Rank[x] == Rank[y]

  Parent[y] = x;
  Next[Last[x]] = y
  Last[x] = Last[y]
end

n = gets.to_i
Parent,Rank,Next,Last = [],[],[],[]
init(n+1)

(n-1).times do
  a,b = gets.split.map(&:to_i)
  unite(a,b)
end
t = find(1)
n.times do |i|
  print "#{t}"
  print " "  if i < n-1
  t = Next[t]
end

class Base
  attr_accessor :parent
  def root
    parent ? parent.root : self
  end
end

class Integer
  def size
    1
  end

  def parent=(a)
  end
end

class Node < Base
  attr_reader :size, :items
  def initialize(items)
    @size = items.map(&:size).reduce(&:+)
    @items = items
    @items.each do |item|
      item.parent = item
    end
  end

  def add(item)
    @items << item
    @size += item.size
    item.parent = self
    self
  end

  def merge(b)
    if size >= b.size
      add(b)
    else
      b.add(self)
    end
  end
end

N = STDIN.gets.to_i
map = Array.new(N) { nil }

(N-1).times do |i|
  a,b = STDIN.gets.strip.split.map(&:to_i)
  a -= 1
  b -= 1
  map[a] ||= Node.new([a])
  map[b] ||= Node.new([b])
  map[a].root.merge(map[b].root)
end

def print_node(node)
  case node
  when Integer
    print("#{node+1} ")
  else
    node.items.each do |item|
      print_node(item)
    end
  end
end

print_node(map[0].root)
puts

DBG = !true

def edge(x)
  return x if $lbl[x] == -1
  y = edge($lbl[x])
  $lbl[x] = y if y != x
  return y
end

def setedge(x,lb)
  if $lbl[x] != -1 && $lbl[x] != lb
    setedge($lbl[x], lb)
  end
  $lbl[x] = lb if lb != x
end

def con(x,y)
  p = edge(x)
  q = edge(y)
  setedge(x,$top)
  setedge(y,$top)
  $lbl[p] = $top
  $lbl[q] = $top
  $rev1[$top] = p
  $rev2[$top] = q
  $top += 1
  if DBG
    print $a
    puts " - a"
    print $rev1
    puts " - rev1"
    print $rev2
    puts " - rev2"
    print $lbl
    puts " - lbl"
  end
end

def pr(y)
  stk = [y]
  while !stk.empty?
    x = stk.pop
    if x >= $n
      stk << ($rev2[x])
      stk << ($rev1[x])
    else
      print "#{x+1} "
    end
  end
  puts ""
end

#### main

n = gets.to_i
$n = n
$top = n
$a = Array.new(2*n+1, -1)
$rev1 = Array.new(2*n+1, -1)
$rev2 = Array.new(2*n+1, -1)
$lbl = Array.new(2*n+1, -1)

for i in 1...n
  x,y = gets.split.map{|z| z.to_i}
  puts "do #{x-1} #{y-1}" if DBG
  con(x-1, y-1)
end
pr($top-1)

def init(n)
  n.times do |i|
    Parent[i] = i
    Member[i] =[i]
    Rank[i] = 0
  end
end

def find(x)
  if Parent[x] == x
    return x
  else
    return Parent[x] = find(Parent[x])
  end
end

def unite(x,y)
  x,y = find(x),find(y)
  return if x==y

  if Rank[x] < Rank[y]
    Parent[x] = y
    Member[y] += Member[x]
  else
    Parent[y] = x;
    Member[x] += Member[y]
    Rank[x] += 1 if Rank[x] == Rank[y]
  end
end

n = gets.to_i
Parent = []*(n+1)
Rank = []*(n+1)
Member = []*(n+1)
init(n+1)

(n-1).times do
  a,b = gets.split.map(&:to_i)
  unite(a,b)
end
n.times do |i|
  print "#{Member[1][i]}"
  print " "  if i < n-1
end


The R2 company has n employees working for it. The work involves constant exchange of ideas, sharing the stories of success and upcoming challenging. For that, R2 uses a famous instant messaging program Spyke.R2 has m Spyke chats just to discuss all sorts of issues. In each chat, some group of employees exchanges messages daily. An employee can simultaneously talk in multiple chats. If some employee is in the k-th chat, he can write messages to this chat and receive notifications about messages from this chat. If an employee writes a message in the chat, all other participants of the chat receive a message notification.The R2 company is conducting an audit. Now the specialists study effective communication between the employees. For this purpose, they have a chat log and the description of chat structure. You, as one of audit specialists, are commissioned to write a program that will use this data to determine the total number of message notifications received by each employee.

The first line contains three space-separated integers n, m and k (2 ≤ n ≤ 2·104; 1 ≤ m ≤ 10; 1 ≤ k ≤ 2·105) — the number of the employees, the number of chats and the number of events in the log, correspondingly.  Next n lines contain matrix a of size n × m, consisting of numbers zero and one. The element of this matrix, recorded in the j-th column of the i-th line, (let's denote it as aij) equals 1, if the i-th employee is the participant of the j-th chat, otherwise the element equals 0. Assume that the employees are numbered from 1 to n and the chats are numbered from 1 to m. Next k lines contain the description of the log events. The i-th line contains two space-separated integers xi and yi (1 ≤ xi ≤ n; 1 ≤ yi ≤ m) which mean that the employee number xi sent one message to chat number yi. It is guaranteed that employee number xi is a participant of chat yi. It is guaranteed that each chat contains at least two employees.

Print in the single line n space-separated integers, where the i-th integer shows the number of message notifications the i-th employee receives.

r=lambda{gets.split.map{|i| i.to_i}}
n,m,k=r.call
a=[]
s=[0]*m
b=[0]*n
n.times{a<<r.call}
k.times{t,q=r.call;s[q-1]+=1;b[t-1]-=1}
n.times{|i| m.times{|j| b[i]+=s[j] if a[i][j]==1}}
puts b.join " "


Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result.

The input data consists of a single line to be processed. The length of the line is from 1 to 2·105 characters inclusive. The string contains only lowercase Latin letters.

Print the given string after it is processed. It is guaranteed that the result will contain at least one character.

s=[' '];gets.scan(/./).each{|i|s[-1]==i ? s.pop : s<<i};puts s.join

s = []
input = gets.chomp
input.each_char do |ch|
  if s[-1] == ch
    s.pop
  else
    s << ch
  end
end
puts s.join

s=[' ']
gets.scan(/./).each do |i|
	s[-1]==i ? s.pop : s<<i
end
puts s.join

def collapse
  if $array.size >= 2 and  $array[-1] == $array[-2]
    $array.pop
    $array.pop
    collapse
  end
end
s = gets.chomp
$array = []
s.split('').each do |c|
  $array.push c
  collapse
end
puts $array*''

stack=[]
gets.split(//).each{|ch|
	if stack.empty?
		stack << ch
	else
		if stack[-1] == ch
			stack.pop
		else
			stack << ch
		end
	end
}

puts stack.join

str = gets.chomp

str1 = []
str.scan(/./).each do |i|
  if i == str1.last
    str1.pop
  else
    str1 << i
  end
end
puts str1.join

str = gets.chomp

while str =~ /(.)\1+/
  str.gsub!(/(.)\1+/,'')
end

puts str

str = gets.chomp

while str =~ /(.)\1/
  str.gsub!(/([a-z])\1+/,'')
end

puts str

str = gets.chomp

while str =~ /(.)\1/
  str.gsub!(/(.)(\1)+/,'')
end

puts str

str = gets.chomp

while str =~ /(.)\1/
  str.gsub!(/(.)\1/,'\1')
end

puts str

str = gets.chomp.split(//)
str2 = ""
flag = false
i = 0
15.times do
  flag = true
  while(i < str.length)
    if str[i] == str[i+1]
      i+=2
    else
      str2 << str[i]
      i+=1
    end
  end
  str = str2.split(//)
end

if flag
  puts str2
else
  puts str.join
end

str = gets.chomp

while str =~ /(.)\1/
  str.gsub!(/(.)\1+/,'')
end

puts str


Having bought his own apartment, Boris decided to paper the walls in every room. Boris's flat has n rooms, each of which has the form of a rectangular parallelepiped. For every room we known its length, width and height of the walls in meters (different rooms can have different dimensions, including height).Boris chose m types of wallpaper to paper the walls of the rooms with (but it is not necessary to use all the types). Each type of wallpaper is sold in rolls of a fixed length and width (the length, naturally, shows how long the unfolded roll will be). In addition, for each type we know the price of one roll of this type.The wallpaper of each type contains strips running along the length of the roll. When gluing the strips must be located strictly vertically (so the roll cannot be rotated, even if the length is less than the width). Besides, a roll can be cut in an arbitrary manner, but the joints of glued pieces should also be vertical. In addition, each room should be papered by only one type of wallpaper. And pieces of the same roll cannot be used to paper different rooms. That is, for each room the rolls are purchased separately. Also, some rolls can be used not completely.After buying an apartment Boris is short of cash, so he wants to spend the minimum money on wallpaper. Help him.

The first line contains a positive integer n (1 ≤ n ≤ 500) — the number of rooms in Boris's apartment. Each of the next n lines contains three space-separated positive integers — the length, width and height of the walls in a given room in meters, respectively. The next line contains a positive integer m (1 ≤ m ≤ 500) — the number of available wallpaper types. Each of the following m lines contains three space-separated positive integers — the length and width in meters of a given wallpaper and the price of one roll, respectively. All numbers in the input data do not exceed 500. It is guaranteed that each room can be papered using these types of wallpaper.

Print a single number — the minimum total cost of the rolls.

NoteNote to the sample:The total length of the walls (the perimeter) of the room is 20 m.One roll of the first type can be cut into pieces to get three vertical 1 meter wide strips, ergo you need 7 rolls of this type, the price equals 700.A roll of the second type can be cut into pieces to get five 2 meter wide strips, we need 2 rolls, the price is 640.One roll of the third type can immediately paper 19 meters out of 20, but we cannot use other types and we have to buy a second roll, the price is 1000.

n = gets.chomp.to_i
na = Array.new(n)
for i in 0..n-1
	na[i] = gets.chomp.split(/ /).map!{|x| x.to_i}
end
m = gets.chomp.to_i
ma = Array.new(m)
for j in 0..m-1
	ma[j] = gets.chomp.split(/ /).map!{|x| x.to_i}
end
sum = 0
for i in 0..n-1
	sumwk = -1
	length = na[i][0]
	width = na[i][1]
	height = na[i][2]
	for j in 0..m-1
		if ma[j][0] < height
			next j
		end
		cutcount = ma[j][0].div(height)
		rollcount, amari = ((length+width)*2).divmod(cutcount * ma[j][1])
		if amari > 0
			rollcount += 1
		end
		wk = rollcount * ma[j][2]
		if sumwk < 0 || sumwk > wk
			sumwk = wk
		end
	end
	sum += sumwk
end
puts sum

n = gets.to_i
a = Array.new(n) do
    l, w, h = gets.split.map(&:to_i)
    [h, 2 * (l + w)]
end
m = gets.to_i
b = Array.new(m) do
    gets.split.map(&:to_i)
end

s = 0
a.each do |x, y|
    t = 9e9
    b.each do |u, v, w|
        u /= x
        next if u == 0
        v *= u
        t = [t, (y + v - 1) / v * w].min
    end
    s += t
end
p s

n=gets.split[0].to_i
room=Array.new()
n.times{ room.push(gets.split.map(&:to_i)) }
m=gets.split[0].to_i
paper=Array.new()
m.times{ paper.push(gets.split.map(&:to_i)) }

ans=0
room.each{|a|
    room_ans=[]
    paper.each{|p|
        t=2*(a[0]+a[1])
        next if p[0]<a[2]
        one=p[0]/a[2]
        count=(t+p[1]-1)/p[1]
        room_ans.push(((count+one-1)/one)*p[2])
    }
    ans+=room_ans.min
}
p ans

a = gets.to_i.times.map{gets.split.map{|i| i.to_i}}
b = gets.to_i.times.map{gets.split.map{|i| i.to_i}}
r = 0
a.each {|a|
	s = 1 << 20
	p = (a[0] + a[1]) * 2
	b.each{|b| s = [s, ((p - 1) / (b[0] / a[2] * b[1]) + 1) * b[2]].min if b[0] >= a[2] }
	r += s
}
puts r

a = gets.to_i.times.map{gets.split.map{|i| i.to_i}}
b = gets.to_i.times.map{gets.split.map{|i| i.to_i}}
r = 0
a.each{ |a|
	s = 1 << 20
	p = (a[0] + a[1]) * 2
	b.each{ |b|
		if b[0] >= a[2]
			h = b[0] / a[2] * b[1]
			w = (p - 1) / h + 1
			s = [s, w * b[2]].min
		end
	}
	r += s
}
puts r

#f = File.open("b.in", "r")
n = gets.to_i
a = Array.new(n) {Array.new(3)}
for i in 0...n
	a[i] = gets.split.map{|i| i.to_i}
end
m = gets.to_i
b = Array.new(m) {Array.new(3)}
r = 0
for i in 0...m
	b[i] = gets.split.map{|i| i.to_i}
end
for i in 0...n
	s = 1 << 20
	p = a[i][0] * 2 + a[i][1] * 2
	for j in 0...m
		if b[j][0] >= a[i][2]
			h = b[j][0] / a[i][2] * b[j][1]
			w = (p - 1) / h + 1
			s = [s, w * b[j][2]].min
		end
	end
	r += s
end
puts r

n = gets.to_i
a = n.times.map{gets.split.map{|i| i.to_i}}
m = gets.to_i
b = m.times.map{gets.split.map{|i| i.to_i}}
r = 0
for i in 0...n
	s = 1 << 20
	p = (a[i][0] + a[i][1]) * 2
	for j in 0...m
		if b[j][0] >= a[i][2]
			h = b[j][0] / a[i][2] * b[j][1]
			w = (p - 1) / h + 1
			s = [s, w * b[j][2]].min
		end
	end
	r += s
end
puts r

n = STDIN.readline.to_i
rooms = n.times.map { STDIN.readline.split.map {|s| s.to_i } }
m = STDIN.readline.to_i
wallpapers = m.times.map { STDIN.readline.split.map {|s| s.to_i } }
total = 0

rooms.each do |length, width, height|
  circumference = 2*(length + width)
  best = -1
  wallpapers.each do |length, width, price|
    strips = (circumference + width - 1) / width
    strips_per_roll = length / height
    next if strips_per_roll == 0
    rolls = (strips + strips_per_roll - 1) / strips_per_roll
    cost = rolls * price
    #puts '%d * %d = %d' % [rolls, price, cost]
    if best == -1 or cost < best
      best = cost
    end
  end
  total += best
end

puts total

#!/usr/bin/env ruby

def read_ints
  return gets.split.map(&:to_i)
end

n = gets.to_i
rooms = []
n.times do
  rooms << read_ints
end

m = gets.to_i
papers = []
m.times do
  papers << read_ints
end

result = 0
rooms.each do |rl, rw, rh|
  perimeter = 2 * (rl + rw)
  best = 10**10
  papers.each do |pl, pw, price|
    if pl >= rh
      cost = (perimeter.to_f / ((pl / rh) * pw)).ceil * price
      best = [best, cost].min
    end
  end
  result += best
end
puts result

#!/usr/bin/ruby
n = gets.chomp.to_i
mvys = Array.new(n)
msir = Array.new(n)
mhl = Array.new(n)
cenacelkem = 0
for i in 0..n-1
	k = gets.chomp.split(' ')
	msir[i] = k[0].to_i
	mhl[i] = k[1].to_i
	mvys[i] = k[2].to_i
	#puts(k)
end
m = gets.chomp.to_i
tapvys = Array.new(m)
tapsir = Array.new(m)
tapcena = Array.new(m)
for i in 0..m-1
	k = gets.chomp.split(' ')
	tapvys[i] = k[0].to_i
	#puts tapvys[i]
	tapsir[i] = k[1].to_i
	tapcena[i]  = k[2].to_i
end
for i in 0..n-1
	obvod = msir[i]+msir[i]+mhl[i]+mhl[i]
	vys = mvys[i]
	#puts obvod
	cenamin = 2147486646
	for j in 0..m-1
		vtap = tapvys[j]
		stap = tapsir[j]
		ctap = tapcena[j]
		#puts vtap
		if vtap >= vys
			#puts((vtap/vys).to_s)
			prouzku = vtap/vys
			rolem = prouzku*stap
			#puts rolem
			roli = (obvod/rolem.to_f).ceil
			cena = roli*ctap;
			if cenamin > cena
				cenamin = cena
			end
		end
	end
	cenacelkem = cenacelkem + cenamin
end
puts cenacelkem

n = gets.chomp.to_i
rooms = Array.new(n) { gets.split.collect{|x| x.to_i} }

m = gets.chomp.to_i
types = Array.new(m) { gets.split.collect{|x| x.to_i} }

sum_cost = 0
rooms.each{|room|
  l,w,h = room
  min_cost = nil

  types.each{|type|
    lt,wt,c = type
    cols = lt / h
    next if cols == 0

    cols_req = ((2 * l + 2 * w) / wt.to_f).ceil
    cost = c * (cols_req / cols.to_f).ceil

    min_cost = cost if min_cost.nil? or cost < min_cost
  }
  sum_cost += min_cost
}

puts sum_cost

n=gets.to_i
rooms=n.times.map{gets.split.map(&:to_i)}
m=gets.to_i
papers=m.times.map{gets.split.map(&:to_i)}

s=0
rooms.each{|l,w,h|
	perimeter=(l+w)*2
	s+=papers.map{|p_l,p_w,p_p|
		if p_l<h
			1<<30
		else
			strip_num=(p_l/h)*p_w
			((perimeter+strip_num-1)/strip_num)*p_p
		end
	}.min
}
p s

#f = File.open("b.in", "r")
n = gets.to_i
a = Array.new(n) {Array.new(3)}
for i in 0...n
	a[i] = gets.split.map{|i| i.to_i}
end
m = gets.to_i
b = Array.new(m) {Array.new(3)}
r = 0
for i in 0...m
	b[i] = gets.split.map{|i| i.to_i}
end
for i in 0...n
	s = 1 << 20
	p = a[i][0] * 2 + a[i][1] * 2
	for j in 0...m
		if b[j][0] > a[i][2]
			h = b[j][0] / a[i][2] * b[j][1]
			w = (p - 1) / h + 1
			s = [s, w * b[j][2]].min
		else
			h = (a[i][2] - 1) / b[j][0] + 1
			w = (p - 1) / b[j][1] + 1
			s = [s, w * b[j][2] * h].min
		end
	end
	r += s
end
puts r

#!/usr/bin/env ruby

def read_ints
  return gets.split.map(&:to_i)
end

n = gets.to_i
rooms = []
n.times do
  rooms << read_ints
end

m = gets.to_i
papers = []
m.times do
  papers << read_ints
end

rooms.each do |rl, rw, rh|
  perimeter = 2 * (rl + rw)
  best = 10**10
  papers.each do |pl, pw, price|
    if pl >= rh
      cost = (perimeter.to_f / ((pl / rh) * pw)).ceil * price
      best = [best, cost].min
    end
  end
  puts best
end

#!/usr/bin/env ruby

def read_ints
  return gets.split.map(&:to_i)
end

n = gets.to_i
rooms = []
n.times do
  rooms << read_ints
end

m = gets.to_i
papers = []
m.times do
  papers << read_ints
end

rooms.each do |rl, rw, rh|
  perimeter = 2 * (rl + rw)
  best = 10**10
  papers.each do |pl, pw, price|
    div = pl < rh ? 1 : pl / rh
    mul = pl < rh ? rh / pl : 1
    cost = (perimeter.to_f / (div * pw)).ceil * mul * price
    best = [best, cost].min
  end
  puts best
end


Professor GukiZ likes programming contests. He especially likes to rate his students on the contests he prepares. Now, he has decided to prepare a new contest. In total, n students will attend, and before the start, every one of them has some positive integer rating. Students are indexed from 1 to n. Let's denote the rating of i-th student as ai. After the contest ends, every student will end up with some positive integer position. GukiZ expects that his students will take places according to their ratings. He thinks that each student will take place equal to . In particular, if student A has rating strictly lower then student B, A will get the strictly better position than B, and if two students have equal ratings, they will share the same position. GukiZ would like you to reconstruct the results by following his expectations. Help him and determine the position after the end of the contest for each of his students if everything goes as expected.

The first line contains integer n (1 ≤ n ≤ 2000), number of GukiZ's students.  The second line contains n numbers a1, a2, ... an (1 ≤ ai ≤ 2000) where ai is the rating of i-th student (1 ≤ i ≤ n).

In a single line, print the position after the end of the contest for each of n students in the same order as they appear in the input.

NoteIn the first sample, students 2 and 3 are positioned first (there is no other student with higher rating), and student 1 is positioned third since there are two students with higher rating.In the second sample, first student is the only one on the contest.In the third sample, students 2 and 5 share the first position with highest rating, student 4 is next with third position, and students 1 and 3 are the last sharing fourth position.

gets
x=gets.split.map{|e| e.to_i}
c=(0..2000).map{0}
x.each{|e|
	c[e]+=1
}
ans=1
2000.downto(1){|i|
	if c[i]>0 then
		t=c[i]
		c[i]=ans
		ans+=t
	end
}

puts x.map{|e|
	c[e]
}*" "

n = gets.to_i
a = gets.chomp.split("\s").map.with_index { |e, i| [i, e.to_i] }.sort { |a, b| b[1] <=> a[1] }

before = -Float::INFINITY
position = 0
res = []

n.times do |i|
  position = i + 1 unless before == a[i][1]
  res << [a[i][0], position]
  before = a[i][1]
end

puts res.sort { |a, b| a[0] <=> b[0] }.map { |e| e[1] }.join("\s")

a=Hash[(1..gets.to_i).zip(gets.split.map{|t|t.to_i})]
puts a.map{|i,ai|1+a.select{|j,aj|(j!=i)&&(aj>ai)}.size}.join(' ')

n = gets.to_i
a = gets.split.map(&:to_i)
s = a.each_with_index.to_a.sort { |x,y| y <=> x }
answer = [0] * n
t = nil
last = nil
s.each_with_index do |tuple, index|
  if last != tuple[0]
    last = tuple[0]
    t = index + 1
  end
  answer[tuple[1]] = t

end
puts answer.join ' '

# coding: utf-8

n = gets.to_i
ar = gets.split.map(&:to_i)
ac = Array.new(2000 + 1) { 0 }
for i in ar
    ac[i] += 1
end
arc = [0]
acc = 0
for i in 1..2000
    acc += ac[i]
    arc << acc
end
results = []
for i in ar
    results << 1 + (arc[2000] - arc[i])
end
puts results.join(' ')

n = gets.to_i
a = gets.split.map(&:to_i)
b = a.map{|x| a.count{|y| y > x} + 1}
puts b.join(' ')

def solution(n, arr)
  arr2 = arr.sort
  h = {}
  (0...n).each do |i|
    j = i + 1
    while(arr2[j] == arr2[i]) do
      j += 1
    end
    h[arr2[i]] = n - j + 1
  end

  puts arr.map{|a| a = h[a]}.join(' ')
end

solution(gets.chomp.to_i, gets.split.map(&:to_i))

# http://codeforces.com/problemset/problem/551/A

n = gets.chomp.to_i
a = gets.chomp.split.map(&:to_i)

sorted_a = a.sort
result = {}

for i in 0..(n - 1)
  if sorted_a[i + 1] != sorted_a[i]
    result[sorted_a[i]] = n - i
  end
end

for i in 0..(n - 1)
  print result[a[i]], " "
end

n = gets().chomp().to_i
student = []
student = gets().split(' ').map {|p| p.to_i}

def find_max(student)
        n= student.size()
maximum =0
index =0
for i in (0..n-1)
        if student[i]>maximum
                maximum = student[i]
                index = i
        end
end

return maximum,index
end

position = Array.new(n,0)

found =false
rating = 1

last,index = find_max(student)

for j in (1..n)
        maximum,index = find_max(student)

        student[index]=0
        if last > maximum
                position[index]=j
                rating = j
        else
                position[index]=rating
        end
        last = maximum
=begin
        for i in (0..n-1)
                if student[i]==maximum
                        student[i]=0
                        position[i]=rating
                        found =true
                        break
                end
        end

        if found
                found = false
        else
                puts "hello"
                rating = j+1
        end
=end
end

position.each { |p| print "#{p} "}
puts

#!/usr/bin/ruby
#coding:utf-8
#derived from 3年C組の成績表
gets
m=gets.split.map(&:to_i).each_with_index.to_a
1.times{|i| # 各列を順位に変換
	m.sort_by!{|e|-e[i]}
	a=[] # 順位
	rank=1
	add=0
	a<<rank
	(1...m.size).each{|j|
		add+=1
		if m[j-1][i]>m[j][i] # 点数が異なっていたら、同じだった人数を順位に加える
			rank+=add
			add=0
		end
		a<<rank
	}
	m.size.times{|j|m[j][i]=a[j]} # 行列を順位で上書き
}
m.sort_by!{|e|e.last}
m.size.times{|i|m[i].pop}
puts m*' '

n = gets.chomp.to_i
rates = gets.chomp.split.map(&:to_i)

hash = {}
rank = 1
rates.sort.reverse.each do |rate|
  hash[rate] = rank unless hash.key?(rate)

  rank += 1
end

puts rates.map { |rate| hash[rate] }.join(' ')

stuNum = gets.chomp.to_i
score = gets.chomp.split(' ').map{|item| item.to_i}
hash = {}

newScore = score.sort {|a, b| b <=> a}

newScore.each_with_index do |value, index|
	if !hash.has_key?(value)
		hash[value] = index + 1
	end
end

score.each do |value|
	print "#{hash[value]} "
end

puts ''

n = gets.to_i
a = gets.split.map{|r| r.to_i}
f = Array.new(n)

for i in 0..n-1
 f[i] = 1
 max = a[i]
 a.each do |x|
  if x>max
     f[i]+=1
  end
 end
end
puts f

gets
arr = gets.split.map { |x| x.to_i }
hashed = Hash.new(0)
arr.uniq.each { |x| hashed[x] = arr.sort.count { |y| y > x } + 1 }
arr.each do |x|
 print hashed[x], " "
end

n = gets.chomp.to_i
arr = gets.split.map(&:to_i)
arr2 = arr.sort
number = Hash.new
n.times do |i|
  number[arr2[i]] = i
end
n.times do |i|
  print n-number[arr[i]] ; print " "
end

n = gets.split(' ').map(&:to_i)
a = gets.split(' ').map(&:to_i)
b = a.clone()
b = b.sort!.reverse
for x in a
  b.length.times{ |i|
    if (b[i]==x)
      print i+1
      print ' '
      break
    end
  }
end

def solution(n, arr)
  arr.sort!
  (0...n).each do |index|
    arr[index] = arr[n-1] - arr[index] + 1
  end
  print arr
end

solution(gets.chomp.to_i, gets.split.map(&:to_i))

def solution(n, arr)
  arr.sort!
  (0...n).each do |i|
    j = i + 1
    while(arr[j] == arr[i]) do
      j += 1
    end
    arr[i] = n - j + 1
  end
  puts arr.join(' ')
end

solution(gets.chomp.to_i, gets.split.map(&:to_i))

gets
arr = gets.chomp.split.join("")
max = 0
arr.scan(/0+/) { |x| max = x.length if x.length > max }
puts arr.split("").count { |x| x == "1" } + max

n = gets.chomp.to_i
arr = gets.split.map(&:to_i)
number = Hash.new
n.times do |i|
  number[arr[i]] = i
end
n.times do |i|
  print n-number[arr[i]] ; print " "
end