Problem:


ICPC Ranking

Your mission in this problem is to write a program
which, given the submission log of an ICPC (International Collegiate Programming Contest),
determines team rankings.

The log is a sequence of records of program submission
in the order of submission.
A record has four fields: elapsed time, team number,
problem number, and judgment.
The elapsed time is the time elapsed from the beginning of the contest
to the submission.
The judgment field tells whether the submitted program was
correct or incorrect, and when incorrect,
what kind of an error was found.

The team ranking is determined according to the following rules.
Note that the rule set shown here is one used in the real ICPC World Finals and Regionals,
with some detail rules omitted for simplification.

Teams that solved more problems are ranked higher.

Among teams that solve the same number of problems, 
ones with smaller total consumed time are ranked higher.

If two or more teams solved the same number of problems, and their
total consumed times are the same, they are ranked the same.

The total consumed time is the sum of the consumed time for each problem solved.
The consumed time for a solved problem is the elapsed time 
of the accepted submission plus 20 penalty minutes for every previously rejected submission for that problem.

If a team did not solve a problem, the consumed time for the problem is zero, and thus even if there are several incorrect submissions, no penalty is given.

You can assume that a team never submits a program for a problem
after the correct submission for the same problem.

Input

The input is a sequence of datasets each in the following format.
The last dataset is followed by a line with four zeros.

M T P R 

m1 t1 p1 j1 

m2 t2 p2 j2 

..... 

mR tR pR jR 

The first line of a dataset contains four integers
M, T, P, and R.
M is the duration of the contest.
T is the number of teams.
P is the number of problems.
R is the number of submission records.
The relations 
120 ≤ M ≤ 300,
1 ≤ T ≤ 50,
1 ≤ P ≤ 10,
and 0 ≤ R ≤ 2000
hold for these values.
Each team is assigned a team number between 1 and T, inclusive.
Each problem is assigned a problem number between 1 and P, inclusive.

Each of the following R lines contains a submission record
with four integers
mk, tk,
pk, and jk
(1 ≤ k ≤ R).
mk is the elapsed time.
tk is the team number.
pk is the problem number.
jk is the judgment
(0 means correct, and other values mean incorrect).
The relations
0 ≤ mk ≤ M&minus;1,
1 ≤ tk ≤ T,
1 ≤ pk ≤ P,
and 0 ≤ jk ≤ 10
hold for these values.

The elapsed time fields are rounded off to the nearest minute.

Submission records are given in the order of submission.
Therefore, if i < j,
the i-th submission is done before the j-th submission
(mi ≤ mj).
In some cases, you can determine the ranking of two teams
with a difference less than a minute, by using this fact.
However, such a fact is never used in the team ranking.
Teams are ranked only using time information in minutes.

Output

For each dataset, your program should output team numbers (from 1 to T),
higher ranked teams first.
The separator between two team numbers should be a comma.
When two teams are ranked the same, the separator between them
should be an equal sign.
Teams ranked the same should be listed
in decreasing order of their team numbers.

Sample Input

300 10 8 5
50 5 2 1
70 5 2 0
75 1 1 0
100 3 1 0
150 3 2 0
240 5 5 7
50 1 1 0
60 2 2 0
70 2 3 0
90 1 3 0
120 3 5 0
140 4 1 0
150 2 4 1
180 3 5 4
15 2 2 1
20 2 2 1
25 2 2 0
60 1 1 0
120 5 5 4
15 5 4 1
20 5 4 0
40 1 1 0
40 2 2 0
120 2 3 4
30 1 1 0
40 2 1 0
50 2 2 0
60 1 2 0
120 3 3 2
0 1 1 0
1 2 2 0
300 5 8 0
0 0 0 0

Output for the Sample Input

3,1,5,10=9=8=7=6=4=2
2,1,3,4,5
1,2,3
5=2=1,4=3
2=1
1,2,3
5=4=3=2=1



Sample input:
300 10 8 5
50 5 2 1
70 5 2 0
75 1 1 0
100 3 1 0
150 3 2 0
240 5 5 7
50 1 1 0
60 2 2 0
70 2 3 0
90 1 3 0
120 3 5 0
140 4 1 0
150 2 4 1
180 3 5 4
15 2 2 1
20 2 2 1
25 2 2 0
60 1 1 0
120 5 5 4
15 5 4 1
20 5 4 0
40 1 1 0
40 2 2 0
120 2 3 4
30 1 1 0
40 2 1 0
50 2 2 0
60 1 2 0
120 3 3 2
0 1 1 0
1 2 2 0
300 5 8 0
0 0 0 0


Sample output:
3,1,5,10=9=8=7=6=4=2
2,1,3,4,5
1,2,3
5=2=1,4=3
2=1
1,2,3
5=4=3=2=1

Submission status: Accepted

Solution code:
while 1:
	M,T,P,R = map(int,raw_input().split())
	if M == 0: break
	S = [[-1]*P for i in range(T)]
	PN = [[0]*P for i in range(T)]
	for i in range(R):
		m,t,p,j = map(int,raw_input().split())
		if j == 0:
			S[t-1][p-1] = m + PN[t-1][p-1]
		else:
			PN[t-1][p-1] += 20
	A = [[t+1,P-S[t].count(-1),sum(S[t])] for t in range(T)]
	A = sorted(sorted(sorted(A, reverse = True), key = lambda x:x[2]), key = lambda x:x[1], reverse = True)
	ans = str(A[0][0])
	for i in range(1,T):
		if A[i-1][1] == A[i][1] and A[i-1][2] == A[i][2]:
			ans += "=" + str(A[i][0])
		else:
			ans += "," + str(A[i][0])
	print ans

Submission status: Accepted

Solution code:
while 1:
	M,T,P,R = map(int,raw_input().split())
	if M == 0: break
	S = [[-1]*P for i in range(T)]
	PN = [[0]*P for i in range(T)]
	for i in range(R):
		m,t,p,j = map(int,raw_input().split())
		if j == 0:
			S[t-1][p-1] = m + PN[t-1][p-1]
		else:
			PN[t-1][p-1] += 20
	A = [[t+1,P-S[t].count(-1),sum(S[t])] for t in range(T)]
	A = sorted(sorted(A[::-1], key = lambda x:x[2]), key = lambda x:x[1], reverse = True)
	ans = str(A[0][0])
	for i in range(1,T):
		if A[i-1][1:] == A[i][1:]:
			ans += "=" + str(A[i][0])
		else:
			ans += "," + str(A[i][0])
	print ans

Submission status: Accepted

Solution code:
class Team:
    def __init__(self, num, P):
        self.num = num
        self.times = [ 0 for _ in range(P) ]
        self.solved = [ False for _ in range(P) ]
        self.ps = None
        self.tt = None
    
    def submit(self, m, p, j):
        if j == 0:
            self.solved[p] = True
            self.times[p] += m
        else:
            self.times[p] += 20
    
    def probsSolved(self):
        if self.ps == None:
            self.ps = len(list(filter(lambda x: x, self.solved)))
        return self.ps

    def totalTime(self):
        if self.tt == None:
            total = 0
            for i in range(len(self.solved)):
                if self.solved[i]:
                    total += self.times[i]
            self.tt = total
        return self.tt

if __name__ == '__main__':
    while True:
        M, T, P, R = [ int(x) for x in list(filter(lambda x: x != '', \
            input().strip().split(' '))) ]

        if M == 0 and T == 0 and P == 0 and R == 0:
            break

        teams = [ Team(n + 1, P) for n in range(T) ]

        for _ in range(R):
            m, t, p, j = [ int(x) for x in list(filter(lambda x: x != '', \
                input().strip().split(' '))) ]
            teams[t-1].submit(m, p - 1, j)

        teams.sort(key=lambda t: (-t.probsSolved(), t.totalTime(), -t.num))

        print(teams[0].num, end='')
        for i in range(1, T):
            team = teams[i]
            prevTeam = teams[i - 1]
            if team.probsSolved() == prevTeam.probsSolved() and \
                team.totalTime() == prevTeam.totalTime():
                print("={}".format(team.num), end='')
            else:
                print(",{}".format(team.num), end='')
        print()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

def main():
    while True:
        M, T, P, R = map(int, input().split())
        if M == 0:
            break
        results = [[i,0,0] for i in range(T)]
        if R > 0:
            logs = [list(map(int, input().split())) for i in range(R)]
            logs = sorted(logs, key=lambda x:(x[1], x[2], x[0]))
            penalty = 0
            problem = logs[0][2]
            team = logs[0][1] - 1
            penalty = 0
            i = 0
            while i < len(logs):
                m, t, p, j = logs[i]
                t -= 1
                if team == t:
                    if problem == p:
                        if j != 0:
                            penalty += 1
                        else:
                            results[team][1] += 1
                            results[team][2] += m + penalty*20
                        i += 1
                    else:
                        penalty = 0
                        problem = p
                else:
                    team = t
                    penalty = 0
                    problem = p
        results = sorted(results, key=lambda x:(-x[1], x[2], -x[0]))
        print(results[0][0]+1, end="")
        for i in range(1, T):
            if results[i][1] == results[i-1][1] and results[i][2] == results[i-1][2]:
                print("=",end="")
            else:
                print(",",end="")
            print(results[i][0]+1,end="")
        print()




if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from inspect import currentframe


def debug_print(s):
    # print(s)
    return


def debug_key(*args):
    names = {id(v): k for k, v in currentframe().f_back.f_locals.items()}
    debug_print(', '.join(names.get(id(arg), '???')+' = '+repr(arg) for arg in args))


def solve(M, T, P, R, m, t, p, j):
    debug_print("\n-----solve-----")
    AC_COUNT = 0
    TEAM_NUMBER = 2
    SUM_TIME = 1
    QUE_NUMBER = 3


    record = [[0, 0, i + 1] + [0] * P for i in range(T)]
    debug_print(record)

    for i in range(R):
        if j[i] == 0:
            record[t[i] - 1][AC_COUNT] += 1
            record[t[i] - 1][SUM_TIME] -= m[i] + record[t[i] - 1][QUE_NUMBER + p[i] - 1] * 20
        else:
            record[t[i] - 1][QUE_NUMBER + p[i] - 1] += 1

    record.sort()
    record.reverse()
    debug_print(record)

    ans = str(record[0][TEAM_NUMBER])

    for i in range(1, T):
        if record[i][SUM_TIME] == record[i-1][SUM_TIME] and record[i][AC_COUNT] == record[i-1][AC_COUNT]:
            ans += "=" + str(record[i][TEAM_NUMBER])
        else:
            ans += "," + str(record[i][TEAM_NUMBER])

    print(ans)


    return


if __name__ == '__main__':

    while True:
        M_input, T_imput, P_imput, R_imput = map(int, input().split())
        if M_input == T_imput == P_imput == R_imput == 0:
            break
        m_input = [0 for _ in range(R_imput)]
        t_input = [0 for _ in range(R_imput)]
        p_input = [0 for _ in range(R_imput)]
        j_input = [0 for _ in range(R_imput)]

        for i in range(R_imput):
            m_input[i], t_input[i], p_input[i], j_input[i] = map(int, input().split())

        solve(M_input, T_imput, P_imput, R_imput, m_input, t_input, p_input, j_input)

Submission status: Accepted

Solution code:
def main(M, T, P, R):
    team = [[0, 0, i + 1] for i in range(T)]
    teamprob = [[0] * P for i in range(T)]
    for _ in range(R):
        m, t, p, r = map(int, input().split())
        if r == 0:
            team[t - 1][0] += 1
            team[t - 1][1] -= m
            team[t - 1][1] -= teamprob[t - 1][p - 1]
        else:
            teamprob[t - 1][p - 1] += 20
    team.sort(reverse=True)
    ans = "{0}".format(team[0][2])
    for i in range(1,T):
        if team[i - 1][0] == team[i][0]:
            if team[i - 1][1] == team[i][1]:
                ans += "="
            else:
                ans += ","
        else:
            ans += ","
        ans += "{0}".format(team[i][2])
    print(ans)

while 1:
    m, t, p, r = map(int, input().split())
    if m == t == p == r == 0:
        break
    main(m, t, p, r)

Submission status: Accepted

Solution code:
import sys

def main():
    while True:
        M,T,P,R = map(int,input().split())
        if not M and not T and not P and not R:
            return
        prob = [[0]*(P+1) for _ in range(T+1)]
        result = dict([(t,[0,sys.maxsize]) for t in range(1,T+1)]) # (t,m,p)
        for _ in range(R):
            m,t,p,j = map(int,input().split())
            if j == 0:
                result[t][0] += prob[t][p] + m
                result[t][1] += 1
            else:
                prob[t][p] += 20
        result = list(result.items())
        result = sorted(result, key=lambda x: (-1*x[1][1], x[1][0], -1*x[0]))

        print(result[0][0], end="")
        for i in range(1,T):
            if result[i][1][0] == result[i-1][1][0] and result[i][1][1] == result[i-1][1][1]:
                print("={}".format(result[i][0]), end="")
            else:
                print(",{}".format(result[i][0]), end="")
        print()

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import re

while True:
    Time,Team,Quiz,n = map(int,input().split())
    if Time+Team == 0:break
    score = {}
    accept = {}
    ans = ""
    for i in range(Team-1,-1,-1):
        score[i] = 0
        accept[i] = 0
    miss = [[0 for _ in range(Quiz)] for _ in range(Team)]
    for _ in range(n):
        h,t,q,j = map(int,input().split())
        if j == 0:
           accept[t-1] += 1
           score[t-1] += (h + miss[t-1][q-1])
        else:
            miss[t-1][q-1] += 20
    for i in range(max(accept.values()),-1,-1):
        stack = {}
        for t,sc in accept.items():
            if sc == i:
                stack[t] = score[t]
        stack = sorted(stack.items(), key=lambda x:x[1])
        for i,a in enumerate(stack):
            if ans != "":
                if i == 0 or a[1] != stack[i-1][1]:
                    ans += "," + str(a[0]+1)
                else:
                    ans += "=" + str(a[0]+1)
            else:
                ans += str(a[0]+1)
    print(ans)

Submission status: Accepted

Solution code:
"ICPCの順位づけ"
while True:
    M, T, P, R = map(int, input().split())
    if M == 0:
        break
    submits = []  # ログを管理する配列
    for i in range(R):
        submits.append(list(map(int, input().split())))

    team_scores = {}
    for i in range(1, T+1):
        team_scores[i] = [0, 0]  # 正解数, 時間の合計

    for i in range(R):
        if submits[i][3] == 0:
            add_time = 0
            for j in range(0, i):
                if submits[j][1] == submits[i][1] and submits[j][2] == submits[i][2]:
                    add_time += 20
            team_scores[submits[i][1]][0] += 1
            team_scores[submits[i][1]][1] += (submits[i][0] + add_time)

    team_scores = sorted(team_scores.items(), key=lambda x: (x[1][0], -x[1][1], x[0]), reverse=True)

    ans = ''
    for i in range(len(team_scores)):
        if i == 0:
            ans += str(team_scores[i][0])
        else:
            if team_scores[i][1] == team_scores[i-1][1]:
                ans += '='+str(team_scores[i][0])
            else:
                ans += ','+str(team_scores[i][0])

    print(ans)

Submission status: Accepted

Solution code:
"""
300 10 8 5
50 5 2 1
70 5 2 0
75 1 1 0
100 3 1 0
150 3 2 0
"""
while True:
  M,T,P,R = map(int,input().split())
  if M+T+P+R == 0:
    break
  #### [TeamNumber, Solved, Time, WA]
  Tm = [[i+1,0,0,[0 for j in range(P)]]for i in range(T)]
  ####
  for i in range(R):
    m,t,p,j = map(int,input().split())
    if j==0:
      Tm[t-1][1] += 1
      Tm[t-1][2] += m+Tm[t-1][3][p-1]*20
      Tm[t-1][3][p-1] = 0
    else:
      Tm[t-1][3][p-1] += 1
  Tm.sort(key=lambda x:(x[1],-x[2],x[0]), reverse=True)
  ans = []
  for i in range(T):
    ans.append(str(Tm[i][0]))
    if i<T-1:
      if Tm[i][1]==Tm[i+1][1] and Tm[i][2]==Tm[i+1][2]:
        ans.append("=")
      else:
        ans.append(",")
  print("".join(ans))

Submission status: Accepted

Solution code:
import sys
while(True):
    M,T,P,R=map(int,input().split())
    if (M,T,P,R)==(0,0,0,0):
        break
    points=[0 for i in range(T)]
    time=[0 for i in range(T)]
    penalty=[[0 for i in range(T)] for i in range(P)]
    for i in range(R):
        m,t,p,j=map(int,input().split())
        #正解したものをもう一度出すかどうかは考慮しない
        if j!=0:
            penalty[p-1][t-1]+=1
            continue
        points[t-1]+=1
        time[t-1]+=m+penalty[p-1][t-1]*20
    teams=[(points[i],time[i],i+1) for i in range(T)]
    teams.sort(key=lambda x:(-x[0],x[1],-x[2]))
    st=str(teams[0][2])
    for i in range(1,T):
        if (teams[i-1][0],teams[i-1][1])==(teams[i][0],teams[i][1]):
            st=st+"="
        else:
            st=st+","
        st=st+str(teams[i][2])
    print(st)

Submission status: Accepted

Solution code:
def main():
    while True:
        # minute,team,problem,record
        M,T,P,R = map(int, input().split(" "))
        if M == 0: break

        # [チーム1→[問題1,問題2...],チーム2→[...]...]
        data = [[0 for i in range(P)] for j in range(T)]
        # [正答数,所要合計時間]
        res = [[0, 0] for j in range(T)]
        for item in range(T):
            res[item].insert(0, item + 1)
        
        for i in range(R):
            # minute,team,problem,judge
            m,t,p,j = map(int, input().split(" "))

            # 0秒での正解を見分けるための端数1
            if j == 0: data[t - 1][p - 1] = -(data[t - 1][p - 1]) * 20 + m + 1
            else: data[t - 1][p - 1] -= 1
            
        for i in range(len(data)):
            for item in data[i]:
                if item < 0: continue
                if item != 0:
                    res[i][1] += 1
                    res[i][2] -= (item - 1)

        res = sorted(res, key = lambda x:(x[1], x[2], x[0]), reverse = True)
        
        output(res)

def output(listt):
    print(str(listt[0][0]), end = "")
    for i in range(1, len(listt)):
        if listt[i][1] == listt[i - 1][1] and listt[i][2] == listt[i - 1][2]:
            print("=" + str(listt[i][0]), end = "")
        else: print("," + str(listt[i][0]), end = "")
    print("")
main()

Submission status: Accepted

Solution code:
from collections import defaultdict


class Team:
    def __init__(self, num):
        self.num = num
        self.score = 0
        self.time = 0
        self.penalty = defaultdict(int)


while True:
    _, T, _, R = map(int, input().split())
    if T == 0:break
    teams = [Team(i + 1) for i in range(T)]
    for _ in range(R):
        m, t, p, j = map(int, input().split())
        if j != 0:
            teams[t - 1].penalty[p] += 20
        if j == 0:
            teams[t - 1].score += 1
            teams[t - 1].time += m + teams[t - 1].penalty[p]

    teams.sort(key=lambda team: (-team.score, team.time, -team.num))
    ans = str(teams[0].num)
    pre_score = teams[0].score
    pre_time = teams[0].time
    for i in range(1, T):
        team = teams[i]
        ans += "=" if team.score == pre_score and team.time == pre_time else ","
        ans += str(team.num)
        pre_score = team.score
        pre_time = team.time
    print(ans)

Submission status: Accepted

Solution code:
import sys

input = sys.stdin.readline

for e in iter(input, '0 0 0 0\n'):
    M, T, P, R = map(int, e.split())

    result = [[0, M, i] + [0] * P for i in range(T + 1)]

    for _ in range(R):
        m, t, p, j = map(int, input().split())
        team_data = result[t]
        if j:
            team_data[-p] += 1
        else:
            team_data[0] += 1
            team_data[1] -= m + 20 * team_data[-p]

    result.sort(reverse=True)
    result.pop()

    for td1, td2 in zip(result[:-1], result[1:]):
        if td1[0] == td2[0] and td1[1] == td2[1]:
            print(td1[2], end='=')
        else:
            print(td1[2], end=',')
    print(result[-1][2])

Submission status: Accepted

Solution code:
# coding: utf-8
while 1:
    m,t,p,r=map(int,input().split())
    if m==0:
        break
    teamdata=[[0,0,i+1,set()] for i in range(t)]
    data=[]
    for i in range(r):
        a,b,c,d=map(int,input().split())
        if d==0:
            teamdata[b-1][0]+=1
            teamdata[b-1][1]+=a
            teamdata[b-1][3].add(c)
        data.append([a,b,c,d])
    for a,b,c,d in data:
        if d!=0 and (c in teamdata[b-1][3]):
            teamdata[b-1][1]+=20
    teamdata=sorted(teamdata, key=lambda x:(-x[0],x[1],-x[2]))
    for i in range(t):
        print(teamdata[i][2],end=('\n' if i==t-1 else ',' if teamdata[i][0]>teamdata[i+1][0] or teamdata[i][1]<teamdata[i+1][1] else '='))

Submission status: Accepted

Solution code:
while True:
    M, T, P, R = map(int, input().split())
    if M == T == P == R == 0:
        quit()
    a_list = [[0, 0, i] for i in range(T)]
    wa = [[0 for j in range(P)] for i in range(T)]
    for i in range(R):
        m, t, p, j = map(int, input().split())
        t -= 1
        p -= 1
        if j == 0:
            a_list[t][0] += m + wa[t][p]*20
            a_list[t][1] += 1
        else:
            wa[t][p] += 1
    a_list.sort(key=lambda x: x[2], reverse=True)
    a_list.sort(key=lambda x: x[0])
    a_list.sort(key=lambda x: x[1], reverse=True)
    temp = [-1, -1]
    ans = ''
    for i in range(len(a_list)-1):
        ans += str(a_list[i][2]+1)
        if a_list[i][0] == a_list[i+1][0] and a_list[i][1] == a_list[i+1][1]:
            ans += '='
        else:
            ans += ','
    ans += str(a_list[-1][2]+1)
    print(ans)

Submission status: Runtime Error

Solution code:
while 1:
    M,T,P,R=map(int,input().split())
    if not M and not T and not P and not R:break
    d={i:[0,0] for i in range(1,T+1)}
    wa=[[0 for _ in range(P)] for _ in range(T)]
    for _ in range(R):
        m,t,p,j=map(int,input().split())
        if j:
            wa[t-1][p-1]+=20
        else:
            d[t][0]+=1
            d[t][1]+=(m+wa[t-1][p-1]) 
    rank=sorted(d.items(),key=lambda x:(x[1][0],-x[1][1]),reverse=True)        
    f=lambda x:"=".join(sorted(x,key=lambda y:int(y),reverse=True))
    l=[]
    b=[]
    for (i,j) in enumerate(rank):
        if i>0 and rank[i][1]!=rank[i-1][1]:
            l.append(f(b))
            b=[]
        b.append(str(j[0]))
    if b:l.append(f(b))
    print ",".join(l)