qyliang/CodeNanoFix huggingface dataset:
Sale Result:

There is data on sales of your company. Your task is to write a program that identifies good workers. The program should read a list of data where each item includes the employee ID (i), the amount of sales (q), and the corresponding unit price (p). Then, the program should print IDs of employees whose total sales proceeds (i.e. sum of p * q) is greater than or equal to 1,000,000 in the order of inputting. If there are no such employees, the program should print "NA". You can suppose that n < 4000, and each employee has a unique ID. The unit price (p) is less than or equal to 1,000,000, and the amount of sales (q) is less than or equal to 100,000.

Input:
The input consists of several datasets. The input ends with a line including a single 0. Each dataset consists of:
n (the number of data in the list)
i p q
i p q
...
i p q

Output:
For each dataset, print a list of employee IDs or "NA".

Sample Input:
4
1001 2000 520
1002 1800 450
1003 1600 625
1001 200 1220
2
1001 100 3
1005 1000 100
2
2013 5000 100
2013 5000 100
0

Output for the Sample Input:
1001
1003
NA
2013

# Buggy version:
while 1:
  n=int(input())
  if not n:break
  f=1
  L={}
  for a,b,c in [input().split() for i in range(n)]:
    if a in L:
      if L[a]>=1e6:continue
      L[a]+=d
    else:L[a]=d
    if L[a]>=1e6:
      print(a)
      f=0
  if f:print('NA')

# Fixed version:
while 1:
  n=int(input())
  if not n:break
  f=1
  L={}
  for a,b,c in [input().split() for i in range(n)]:
    d=int(b)*int(c)
    if a in L:
      if L[a]>=1e6:continue
      L[a]+=d
    else:L[a]=d
    if L[a]>=1e6:print(a);f=0
  if f:print('NA')
Title: Book Index

Books are indexed. Create a program that reads a list of word-page number pairs and prints each word along with a list of corresponding page numbers. Each word has a maximum length of 30 characters, and the page number is less than or equal to 1000. There are at most 100 pairs of word-page number. Each word appears only once on a page.

The words should be printed in alphabetical order, and the page numbers should be printed in ascending order.

Input:
word page_number
...

Output:
word
a_list_of_the_page_number
word
a_list_of_the_Page_number
...

Sample Input:
style 12
even 25
introduction 3
easy 9
style 7
document 13
style 21
even 18

Output for the Sample Input:
document
13
easy
9
even
18 25
introduction
3
style
7 12 21

# Buggy version:
book_index = {}
    while True:
        try:
            word, page = input().split(' ')
            page = int(page)
            page_list = book_index.get(word)
            if page_list:
                page_list.append(page)
            else:
                book_index[word] = [page]
        except Exception:
            break

    for k in sorted(book_index.keys()):
        print(k)
        print(' '.join(map(str, (sorted(book_index.get(k))))))

# Fixed version:
book_index = {}
while True:
    try:
        word, page = input().split(' ')
        page = int(page)
        page_list = book_index.get(word)
        if page_list:
            page_list.append(page)
        else:
            book_index[word] = [page]
    except Exception:
        break

for k in sorted(book_index.keys()):
    print(k)
    print(' '.join(map(str, (sorted(book_index.get(k))))))

# Buggy version:
dic = {}
while True:
    try:
        word, pgn = input().split()

        if word in dic.keys():
            dic[word].append(int(pgn))
        else:
            dic[word] = [int(pgn)]
    except:
        break

for k, v in dic.items():
    print(k)
    print(' '.join(map(str, sorted(v))))

# Fixed version:
dic = {}
while True:
    try:
        word, pgn = input().split()

        if word in dic.keys():
            dic[word].append(int(pgn))
        else:
            dic[word] = [int(pgn)]
    except:
        break

for k, v in sorted(dic.items()):
    print(k)
    print(' '.join(map(str, sorted(v))))

# Buggy version:
import sys

dic = {}
while True:
	try:
		a,b = map(str,input(),split())
		page = int(b)

		if a not in dic:
			dic[a] = [page]
		else:
			dic[a].append(page)
			
	except EOFError:
		sorted(dic.keys())
		names = list(dic.keys())
		for i in range(len(names)):
			print(names[i])
			for j in range(len(dic[i])):
				if j == len(dic[i])-1:
					print(dic[i][j])
				else:
					sys.stdout.write(dic[i][j])
		break

# Fixed version:
import sys

dic = {}
while True:
	try:
		a,b = map(str,input().split())
		page = int(b)

		if a not in dic:
			dic[a] = [page]
		else:
			dic[a].append(page)

	except EOFError:
		names = sorted(dic.keys())
		for i in range(len(names)):
			print(names[i])
			pages = sorted(dic[names[i]])
			for j in range(len(pages)):
				if j == len(pages)-1:
					print(pages[j])
				else:
					sys.stdout.write(str('{:} '.format(pages[j])))
		break
Title: Carry a Cheese

Jerry, a small mouse, is trying to survive from the cat Tom. He is carrying a parallelepiped-like piece of cheese with dimensions A x B x C. Jerry needs to trail this cheese to his house, which has several entrances, each with its own radius R. Your task is to create a program to determine if Jerry can trail the cheese via each hole. If he can trail the cheese without touching the hole, the program should print "OK"; otherwise, it should print "NA". The input consists of datasets, each containing the dimensions of the cheese (A, B, C), the number of holes (n), and the radius of each hole (R1, R2, ..., Rn). The output should provide the result of the estimation for each hole. The input ends with a line containing three zeros. The number of holes is assumed to be less than 10000.

# Buggy version:
while True:
    d, w, h = [int(x) for x in input().split()]
    minrad = min(d*d+w*w,w*w+h*h,h*h+d*d)
    if minrad == 0:
        break
    n = int(input())
    for i in range(n):
        r = int(input())
        if 2*r*r > minrad:
            print('OK')
        else:
            print('NA')

# Fixed version:
while True:
    d, w, h = [int(x) for x in input().split()]
    minrad = min(d*d+w*w,w*w+h*h,h*h+d*d)
    if minrad == 0:
        break
    n = int(input())
    for i in range(n):
        r = int(input())
        if 4*r*r > minrad:
            print('OK')
        else:
            print('NA')

# Buggy version:
import math
while True:
	d,w,h = map(int,input().split())
	if d == 0:
		break
	n = int(input())
	dist = [math.sqrt(d**2+w**2), math.sqrt(d**2+h**2), math.sqrt(w**2+h**2)]
	leng = min(dist)
	for i in range(n):
		if int(input())-leng > 0:
			print('OK')
		else:
			print('NA')

# Fixed version:
import math
while True:
	d,w,h = map(int,input().split())
	if d == 0:
		break
	n = int(input())
	dist = [math.sqrt(d**2+w**2), math.sqrt(d**2+h**2), math.sqrt(w**2+h**2)]
	leng = min(dist)
	for i in range(n):
		if 2*int(input())-leng > 0:
			print('OK')
		else:
			print('NA')
There are N piles of candies on the table, each initially containing a certain number of candies. Snuke and Ciel take alternating turns, with Snuke going first. On each turn, the player must choose to either eat all the candies from the pile with the most remaining candies or eat one candy from each pile with at least one candy. The player who eats the last candy loses. Determine which player will win if both play optimally.

Constraints:
1 ≤ N ≤ 10^5
1 ≤ a_i ≤ 10^9

Input:
The input is given in the format:
N
a_1 a_2 ... a_N

Output:
If Snuke will win, print "First". If Ciel will win, print "Second".

Sample Input 1:
2
1 3

Sample Output 1:
First
Explanation: Snuke can eat all candies from pile 2, forcing Ciel to eat the last candy.

Sample Input 2:
3
1 2 1

Sample Output 2:
First
Explanation: If Snuke eats one candy from each pile, Ciel is left with the last candy.

Sample Input 3:
3
1 2 3

Sample Output 3:
Second

# Buggy version:
n=int(input())
a=sorted(map(int,input().split()))[::-1]
j=i=x=0
while x<n:i+=a[i]>i;j+=a[j]>=i,x+=1
print('SFeicrosntd'[(a[i-1]^i|j^i)&1::2])


# Fixed version:
n=int(input())
a=sorted(map(int,input().split()))[::-1]
j=i=0
while i<n and a[i]>i:i+=1
while j<n and a[j]>=i:j+=1
print('SFeicrosntd'[(a[i-1]^i)&1|(j^i)&1::2])
You are given a permutation of numbers from 1 to n. The "oddness" of a permutation is defined as the sum of the absolute differences between each number and its position in the permutation. Find the number of permutations with a given oddness, modulo 10^9+7. Constraints: 1 ≤ n ≤ 50, 0 ≤ k ≤ n^2. Input format: n k. Output the number of permutations with oddness k.

# Buggy version:
MOD = 10**9 + 7
n, oddness = [int(item) for item in input().split()]
# Oddness must be even
if oddness % 2 ==  1:
    print(0)
    exit()
oddness //= 2
max_oddness = 1300 + n
max_pending = n//2 + 2

dp = [[[0] * (max_oddness) for _ in range(max_pending)] for _ in range(n)]
dp[0][0][0] = 1
dp[0][1][1] = 1
k_itr = [item for item in range(1300)]
for i in range(1, n):
    for j in range(min(i+1, n//2)):
        for k in range(min(n*n, oddness+1)):
            dp_ijk = dp[i-1][j][k]
            # Oddness increase by num of pending item
            # Connect in line or Choose 1 from pending items
            dp[i][j][k+j] += dp_ijk * (1 + j*2)
            # dp[i][j][k+j] %= MOD
            # Choose 2 from pending items
            if j > 0:
                dp[i][j-1][k+j-1] += dp_ijk * j*j
                dp[i][j-1][k+j-1] %= MOD 
            # Do nothing 
            dp[i][j+1][k+j+1] += dp_ijk 
            # dp[i][j+1][k+j+1] %= MOD 

print(dp[n-1][0][oddness] % MOD)

# Fixed version:
MOD = 10**9 + 7
n, oddness = [int(item) for item in input().split()]
# Oddness must be even
if oddness % 2 ==  1:
    print(0)
    exit()
oddness //= 2
max_oddness = 1300 + n
max_pending = n//2 + 2

dp = [[[0] * (max_oddness) for _ in range(max_pending)] for _ in range(n)]
dp[0][0][0] = 1
dp[0][1][1] = 1
for i in range(1, n):
    for j in range(min(i+1, max_pending-1)):
        for k in range(oddness+1):
            dp_ijk = dp[i-1][j][k]
            # Oddness increase by num of pending item
            # Connect in line or Choose 1 from pending items
            dp[i][j][k+j] += dp_ijk * (1 + j*2)
            dp[i][j][k+j] %= MOD
            # Choose 2 from pending items
            if j > 0:
                dp[i][j-1][k+j-1] += dp_ijk * j*j
            # Do nothing 
            dp[i][j+1][k+j+1] += dp_ijk 

print(dp[n-1][0][oddness] % MOD)
Takahashi and Aoki will take N exams numbered 1 to N and compete. Takahashi decides the importance c_i for each exam i, within the range l_i to u_i. The winner is determined by comparing the total scores A and B, where A is Takahashi's score and B is Aoki's score. Takahashi knows Aoki's scores b_i and can increase his own score by 1 for each hour of study, up to a maximum score of X. Find the minimum study hours for Takahashi to win. Constraints: 1 ≤ N ≤ 10^5, 1 ≤ X ≤ 10^5, 0 ≤ b_i ≤ X, 1 ≤ l_i ≤ u_i ≤ 10^5. Input format: N X, followed by N lines of b_i, l_i, and u_i. Output the minimum study hours. Example input and output are provided.

# Buggy version:
n, x = list(map(int, input().split()))
B = 0
blu = []
s = [0 for i in range(n)]

for i in range(n):
  b, l, u = list(map(int, input().split()))
  blu.append((b, l, u, x*u-b*u+b*l))
  B += b*l
blu.sort(key=lambda x: x[3], reverse=True)

for i in range(n):
  if i==0:
    s[i] = blu[i][3]
  else:
    s[i] = s[i-1] + blu[i][3]

ans = n*x
for i in range(n):
  ok = n*x
  ng = -1
  while ok-ng>1:
    A = 0
    mid = (ok+ng)//2
    k = mid//x
    t = mid%x
    if t==0:
      A += s[k-1]
    else:
      if i<k:
        A += s[k]
        A -= blu[i][3]
      else:
        A += s[k-1]
      if t<=blu[i][0]:
        A += t*blu[i][1]
      else:
        A += t*blu[i][2] - blu[i][0]*(blu[i][2]-blu[i][1])
    if A>=B:
      ok = mid
    else:
      ng = mid
  ans = min(ans, ok)

print(ans)

# Fixed version:
n, x = list(map(int, input().split()))
B = 0
blu = []
s = [0 for i in range(n)]

for i in range(n):
  b, l, u = list(map(int, input().split()))
  blu.append((b, l, u, x*u-b*u+b*l))
  B += b*l
blu.sort(key=lambda x: x[3], reverse=True)

for i in range(n):
  if i==0:
    s[i] = blu[i][3]
  else:
    s[i] = s[i-1] + blu[i][3]

ok = n*x
ng = -1
while ok-ng>1:
  A = 0
  mid = (ok+ng)//2
  k = mid//x
  t = mid%x
  for i in range(n):
    if t<=blu[i][0]:
      rm = t*blu[i][1]
    else:
      rm = t*blu[i][2] - blu[i][0]*(blu[i][2]-blu[i][1])
    if k==0:
      A = max(A, rm)
    elif i<k:
      A = max(A, s[k]-blu[i][3]+rm)
    else:
      A = max(A, s[k-1]+rm)
  if A>=B:
    ok = mid
  else:
    ng = mid

print(ok)
Title: Diameter of a Tree

Given a tree T with non-negative weight, find the diameter of the tree. The diameter of a tree is the maximum distance between two nodes in a tree.

Input:
- n
- s1 t1 w1
- s2 t2 w2
- ...
- sn-1 tn-1 wn-1

The first line consists of an integer n representing the number of nodes in the tree. Every node has a unique ID from 0 to n-1 respectively. In the following n-1 lines, edges of the tree are given. si and ti represent end-points of the i-th edge (undirected) and wi represents the weight (distance) of the i-th edge.

Output:
Print the diameter of the tree in a line.

Constraints:
- 1 ≤ n ≤ 100,000
- 0 ≤ wi ≤ 1,000

Sample Input 1:
4
0 1 2
1 2 1
1 3 3

Sample Output 1:
5

Sample Input 2:
4
0 1 1
1 2 2
2 3 4

Sample Output 2:
7

# Buggy version:
import sys
readline = sys.stdin.readline
from collections import deque
from math import isinf
INF = float("inf")
sys.setrecursionlimit(200000)
n = int(readline())
G = [[] for _ in range(n)]
for _ in [0] * (n - 1):
    s, t, w = map(int, readline().split())
    G[s].append([t, w])
    G[t].append([s, w])
def bfs(s, D):
    dq = deque([s])
    D = [INF] * n
    D[s] = 0
    while dq:
        u = dq.popleft()
        for i in range(len(G[u])):
            e = G[u][i]
            if isinf(D[e[0]]):
                D[e[0]] = D[u] + e[1]
                dq.append(e[0])
    return D
D = bfs(0, D)
D = bfs(max([i for i in range(n) if not isinf(D[i]) and 0 < D[i]]))
print(max(D[i] for i in range(n) if not isinf(D[i])))

# Fixed version:
import sys
readline = sys.stdin.readline
from collections import deque
from math import isinf
INF = float("inf")
sys.setrecursionlimit(200000)
n = int(readline())
G = [[] for _ in range(n)]
D = [INF] * n
for _ in [0] * (n - 1):
    s, t, w = map(int, readline().split())
    G[s].append([t, w])
    G[t].append([s, w])
def bfs(s, D):
    dq = deque([s])
    D = [INF] * n
    D[s] = 0
    while dq:
        u = dq.popleft()
        for i in range(len(G[u])):
            e = G[u][i]
            if isinf(D[e[0]]):
                D[e[0]] = D[u] + e[1]
                dq.append(e[0])
    return D
D = bfs(0, D)
maxv = 0
tgt = 0
for i in range(n):
    if isinf(D[i]): continue
    if maxv < D[i]:
        maxv = D[i]
        tgt = i
D = bfs(tgt, D)
print(max(D[i] for i in range(n) if not isinf(D[i])))
Title: Height of a Tree

Given a tree T with non-negative weight, find the height of each node of the tree. For each node, the height is the distance to the most distant leaf from the node.

Input:
n
s1 t1 w1
s2 t2 w2
...
sn-1 tn-1 wn-1

The first line consists of an integer n which represents the number of nodes in the tree. Every node has a unique ID from 0 to n-1 respectively.

In the following n-1 lines, edges of the tree are given. si and ti represent end-points of the i-th edge (undirected) and wi represents the weight (distance) of the i-th edge.

Output:
The output consists of n lines. Print the height of each node 0, 1, 2, ..., n-1 in order.

Constraints:
- 1 ≤ n ≤ 10,000
- 0 ≤ wi ≤ 1,000

Sample Input 1:
4
0 1 2
1 2 1
1 3 3

Sample Output 1:
5
3
4
5

# Buggy version:
def solve(prev, r, n, dic):
    d = [0] * n
    md = 0
    t = r
    stack = []
    stack += [[prev, r, 0]]
    while stack:
        print(stack)
        prev, r, d1 = stack.pop(-1)
        if r in dic:
            for vtx, cost in dic[r]:
                if vtx == prev:
                    continue
                stack += [[r, vtx, d1 + cost]]
                if d[vtx] < d1 + cost:
                    d[vtx] = d1 + cost
                    if md < d[vtx]:
                        md = d[vtx]
                        t = vtx
    return d, t

dic = {}
line = input()
n = int(line)
for _ in range(1, n):
    line = input()
    s, t, w = list(map(int, line.split()))
    if s not in dic:
        dic[s] = [[t, w]]
    else:
        dic[s] += [[t, w]]
    if t not in dic:
        dic[t] = [[s, w]]
    else:
        dic[t] += [[s, w]]
d1, t1 = solve(-1, 0, n, dic)
d2, t2 = solve(-1, t1, n, dic)
d3, t3 = solve(-1, t2, n, dic)
print("\n".join(map(str, [max(a, b) for a, b in zip(d2, d3)] )))


# Fixed version:
def solve(prev, r, n, dic):
    d = [0] * n
    md = 0
    t = r
    stack = []
    stack += [[prev, r, 0]]
    while stack:
        prev, r, d1 = stack.pop(-1)
        if r in dic:
            for vtx, cost in dic[r]:
                if vtx == prev:
                    continue
                stack += [[r, vtx, d1 + cost]]
                if d[vtx] < d1 + cost:
                    d[vtx] = d1 + cost
                    if md < d[vtx]:
                        md = d[vtx]
                        t = vtx
    return d, t

dic = {}
line = input()
n = int(line)
for _ in range(1, n):
    line = input()
    s, t, w = list(map(int, line.split()))
    if s not in dic:
        dic[s] = [[t, w]]
    else:
        dic[s] += [[t, w]]
    if t not in dic:
        dic[t] = [[s, w]]
    else:
        dic[t] += [[s, w]]
d1, t1 = solve(-1, 0, n, dic)
d2, t2 = solve(-1, t1, n, dic)
d3, t3 = solve(-1, t2, n, dic)
print("\n".join(map(str, [max(a, b) for a, b in zip(d2, d3)] )))
You are given an integer N. Determine if there exists a tuple of subsets of {1,2,...N}, (S_1,S_2,...,S_k), such that each integer 1,2,...,N is contained in exactly two of the sets S_1,S_2,...,S_k, and any two of the sets S_1,S_2,...,S_k have exactly one element in common. If such a tuple exists, construct one such tuple.

Constraints:
1 ≤ N ≤ 10^5
N is an integer.

Input:
Input is given from Standard Input in the following format:
N

Output:
If a tuple of subsets of {1,2,...N} that satisfies the conditions does not exist, print "No". If such a tuple exists, print "Yes" first, then print such subsets in the following format:
k
|S_1| S_{1,1} S_{1,2} ... S_{1,|S_1|}
:
|S_k| S_{k,1} S_{k,2} ... S_{k,|S_k|}
where S_i={S_{i,1},S_{i,2},...,S_{i,|S_i|}}.
If there are multiple such tuples, any of them will be accepted.

Sample Input 1:
3

Sample Output 1:
Yes
3
2 1 2
2 3 1
2 2 3
It can be seen that (S_1,S_2,S_3)=({1,2},{3,1},{2,3}) satisfies the conditions.

Sample Input 2:
4

Sample Output 2:
No

# Buggy version:
#!/usr/bin/env python3
import sys
input = sys.stdin.readline
def INT(): return int(input())
def MAP(): return map(int,input().split())
def LI(): return list(map(int,input().split()))

def main():
    N =INT()
    size = 0
    for i in range(1,10**3):
        if i*(i+1)//2 == N:
            size = i 
            break
    else:
        print("No")
    
    k = size + 1
    answer = [[] for _ in range(k)]

    start = 1
    for i in range(k):
        answer[i] = list(range(start,start+size-i))
        start += size-i
    
    for i in range(k-1):
        for j in range(i+1,k):
            answer[j].append(answer[i][j-i-1])
    
    print("Yes")
    print(k)
    for i in range(k):
        print(size,*answer[i])
    return

if __name__ == '__main__':
    main()


# Fixed version:
#!/usr/bin/env python3
import sys
input = sys.stdin.readline
def INT(): return int(input())
def MAP(): return map(int,input().split())
def LI(): return list(map(int,input().split()))

def main():
    N =INT()
    size = 0
    for i in range(1,10**3):
        if i*(i+1)//2 == N:
            size = i 
            break
    else:
        print("No")
        return
    
    k = size + 1
    answer = [[] for _ in range(k)]

    start = 1
    for i in range(k):
        answer[i] = list(range(start,start+size-i))
        start += size-i
    
    for i in range(k-1):
        for j in range(i+1,k):
            answer[j].append(answer[i][j-i-1])
    
    print("Yes")
    print(k)
    for i in range(k):
        print(size,*answer[i])
    return

if __name__ == '__main__':
    main()
Millennium: A wise king introduced a new calendar with 10 months per year. Each year starts with a big month, followed by small months and alternating thereafter. Big months have 20 days, small months have 19, except for years divisible by three, which consist of 10 big months. To celebrate the millennium day (year 1000, month 1, day 1), a royal lottery will gift people based on their age in days. Write a program to calculate the days lived by individuals until the millennium day.

Input: Positive integer n (≤ 100) followed by n datasets, each containing a person's birth year, month, and day in the king's calendar.

Output: For each dataset, print the number of days from the birthdate (inclusive) to the millennium day (exclusive).

Sample Input:
8
1 1 1
344 3 1
696 5 1
182 9 5
998 8 7
344 2 19
696 4 19
999 10 20

Sample Output:
196470
128976
59710
160715
252
128977
59712
1

# Buggy version:
def day(y, m, d):
    days = 0
    days += (y-1)*195
    days += (y-1)//3*5
    days += (m-1)*19
    if y%3 == 0:
        days += (m-1)
    else:
        days += (m-1)//2
    days += (d-1)
    return days

def main():
    n = int(input())
    for _ in range(n):
        (y, m, d) = [int(x) for x in input().split()]
        print(day(1000,1,1) - day(y,m,d))

if __name__ == '__main__':
    main()

# Fixed version:
def day(y, m, d):
    days = 0
    days += (y-1)*195
    days += (y-1)//3*5
    days += (m-1)*19
    if y%3 == 0:
        days += (m-1)
    else:
        days += m//2
    days += (d-1)
    return days

def main():
    n = int(input())
    for _ in range(n):
        (y, m, d) = [int(x) for x in input().split()]
        print(day(1000,1,1) - day(y,m,d))

if __name__ == '__main__':
    main()

# Buggy version:
M = [20, 19]
Y = sum(M) * 5

for i in range(int(input())):
    res = 0
    y,m,d = list(map(int,input().split()))
    for y_2 in range(1000-1, y, -1):
        res += Y if y_2 % 3 != 0 else 200

    for m_2 in range(10, m, -1):
        res += M[m_2 % 2] if y % 3 != 0 else 20

    res += (M[m%2] if y % 3 != 0 else 20) - d +1

    print(res)

# Fixed version:
M = [19, 20]
Y = sum(M) * 5

for i in range(int(input())):
    res = 0
    y,m,d = list(map(int,input().split()))
    for y_2 in range(1000-1, y, -1):
        res += Y if y_2 % 3 != 0 else 200

    for m_2 in range(10, m, -1):
        res += M[m_2 % 2] if y % 3 != 0 else 20

    res += (M[m%2] if y % 3 != 0 else 20) - d +1

    print(res)

# Buggy version:
import sys
if sys.version_info[0]>=3: raw_input=input

n=int(raw_input())
for i in range(0,n):
	a=[int(e) for e in raw_input().split()]
	a[0]-=1;a[1]-=1
	print(196471-a[0]*195-a[0]/3*5-a[1]*20+(a[1]/2 if a[0]%3!=2 else 0)-a[2])

# Fixed version:
import sys
if sys.version_info[0]>=3: raw_input=input

n=int(raw_input())
for i in range(0,n):
	a=[int(e) for e in raw_input().split()]
	a[0]-=1;a[1]-=1
	print(196471-a[0]*195-a[0]//3*5-a[1]*20+(a[1]//2 if a[0]%3!=2 else 0)-a[2])