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   m 1  t 1  p 1  j 1   m 2  t 2  p 2  j 2  .....  m R  t R  p R  j R   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 m k , t k , p k , and j k (1 ≤ k ≤ R ). m k is the elapsed time. t k is the team number. p k is the problem number. j k is the judgment
(0 means correct, and other values mean incorrect).
The relations
0 ≤ m k ≤ M −1,
1 ≤ t k ≤ T ,
1 ≤ p k ≤ P ,
and 0 ≤ j k ≤ 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
( m i ≤ m j ).
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

Solution (Python):
ans_list = []

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

    team = [[[0, 1] for i in range(p)] for j in range(t)]

    for i in range(r):
        M, T, P, J = map(int, input().split())
        if J:
            team[T - 1][P - 1][0] += 20
        else:
            team[T - 1][P - 1][0] += M
        team[T - 1][P - 1][1] = J
    

    team_point = []
    for i in range(t):
        point = [0, 0, i]
        for j in range(p):
            if team[i][j][1] == 0:
                point[0] += 1
                point[1] += team[i][j][0]
        point[1] *= -1
        team_point.append(point)

    team_point.sort()
    team_point = team_point[::-1]
    ans = []
    same_point = [str(team_point[0][2] + 1)]
    for i in range(1, len(team_point)):
        if team_point[i][0] == team_point[i - 1][0]:
            if team_point[i][1] == team_point[i - 1][1]:
                same_point = [same_point[0] + "=" + str(team_point[i][2] + 1)]
            else:
                ans.append(same_point)
                same_point = [str(team_point[i][2] + 1)]
        else:
            ans.append(same_point)
            same_point = [str(team_point[i][2] + 1)]

    ans.append(same_point)
    ans_list.append(ans)
  

 


for I in range(len(ans_list)):
    i = ans_list[I]
    for j in range(len(i)):
        print(i[j][0], end = "")
        if j != len(i) - 1:
            print(",", end = "")
    print()

Solution (Python):
from functools import cmp_to_key

def f(a, b):
    if a[0] == b[0]:
        ap = a[1] + a[2] * 20
        bp = b[1] + b[2] * 20
        if ap == bp:
            return a[3] > b[3]
        return ap < bp
    return a[0] > b[0]


while True:
    M, T, P, R = map(int, input().split())
    if not M:
        break
    fail = [[0 for i in range(P)] for j in range(T)]
    
    res = [[0, 0, -i] for i in range(T)]
    
    for r in range(R):
        m, t, p, j = map(int, input().split())
        t -= 1
        p -= 1
        if j:
            fail[t][p] += 1
        else:
            res[t][0] -= 1
            res[t][1] += fail[t][p] * 20 + m
    res = sorted(res)
    for i, r in enumerate(res[:-1]):
        if r[0] == res[i + 1][0] and r[1] == res[i + 1][1]:
            print(-r[2] + 1, end='=')
        else:
            print(-r[2] + 1, end=',')
    print(-res[-1][2] + 1)

Solution (Python):



import os
import sys
import itertools
import math
from collections import Counter, defaultdict

class Main(object):
    
    def __init__(self):
        pass

    def solve(self):
        '''
        insert your code
        '''
        while True:
            M, T, P, R = map(int, raw_input().split())
            if (M, T, P, R) == (0, 0, 0, 0):
                break
            record = [[[], [], 0, i] for i in range(T+1)]
            for i in range(R):
                m, t, p, j = map(int, raw_input().split())
                if j == 0:
                    record[t][0].append(p)
                    record[t][2] += m + 20 * record[t][1].count(p)
                else:
                    record[t][1].append(p)
            record = [(len(correct), time, team) for correct, wrong, time, team in record[1:]]
            record.sort(key=lambda x: (x[0], -x[1], x[2]), reverse=True)
            ans = str(record[0][2])
            prev = (record[0][0], record[0][1])

            for elem in record[1:]:
                if (elem[0], elem[1]) == prev:
                    ans += '='
                else:
                    ans += ','
                ans += str(elem[2])
                prev = (elem[0], elem[1])
            print ans
        return None

if __name__ == '__main__':
    m = Main()
    m.solve()

Solution (Python):
while True:
    M, T, P, R = map(int, input().split())
    if M == 0: break
    teams = [[0, 0, i+1] for i in range(T)]
    miss = [[0 for _ in range(P)] for _ in range(T)]
    solved, time = 0, 1
    logs = [map(int, input().split()) for _ in range(R)]
    for m, t, p, r in logs:
        t -= 1
        p -= 1
        if r == 0:
            teams[t][solved] += 1
            teams[t][time] -= (m + miss[t][p] * 20)
        else:
            miss[t][p] += 1
    teams = sorted(teams, reverse=True)
    before_s, before_t = 0, 0
    for i in range(T):
        s, t, n = teams[i]
        if i != 0:
            print('=' if (s == before_s and t == before_t) else ',', end='')
        before_s, before_t = s, t
        print(n, end='')
    print('')

Solution (Python):



while True:
    M,T,P,R = map(int,input().split(" "))
    if M == 0 and T == 0 and P == 0 and R == 0:
        break
    
    teams = [[j,0,[0 for i in range(P+1)],0] for j in range(T+1)]

    for i in range(R):
        m,t,p,j = map(int,input().split(" "))
        if j == 0:
            if teams[t][2][p] != -1:
                teams[t][1] += 1
                teams[t][3] += teams[t][2][p] * 20 + m
                teams[t][2][p] = -1
        else:
            teams[t][2][p] += 1
    prev = None
    for t in sorted(teams[1:],key=lambda t:(t[1],-t[3],t[0]),reverse=True):
        if prev is not None:
            if prev[1] == t[1] and prev[3] == t[3]:
                print('=',end="")
            else:
                print(',',end="")
        print(t[0],end="")
        prev = t
    print()

Solution (Python):
def islower (t_a,t_b):
	if t_a[1] != t_b[1]:
		return t_a[1] < t_b[1]
	elif t_a[2] != t_b[2]:
		return t_a[2] > t_b[2]
	else :
		return t_a[0] < t_b[0]

import sys
while 1:
	M, T, P, R = map(int,raw_input().split())
	if (T,P,R) == (0,0,0):
		break
	score = [[i,0,0] for i in xrange(1,T+1)]
	wrong = [[0 for i in xrange(P)] for j in xrange(T)]
	for x in xrange(R):
		m, t, p, j = map(int,raw_input().split())
		if j != 0 :
			wrong[t-1][p-1] += 1
		else :
			score[t-1][1] += 1
			score[t-1][2] += 20 * wrong[t-1][p-1] + m

	for j in xrange(T - 1):
		for i in xrange(T - 1 - j):
			t_l = score[i]
			t_r = score[i+1]
			if islower(t_l, t_r):
				score[i] = t_r
				score[i+1] = t_l

	for i in xrange(T):
		if i != 0:
			if (score[i-1][1], score[i-1][2]) == (score[i][1], score[i][2]):
				sys.stdout.write("=")
			else :
				sys.stdout.write(",")
		sys.stdout.write(str(score[i][0]))
	print ""

Solution (Python):
from collections import defaultdict

while True:
  time = [ [0 for _ in range(16)] for __ in range(64) ]
  accepted = [ [0 for _ in range(16)] for __ in range(64) ]

  M,T,P,R = map(int, input().split())
  if M==0 and T==0: break

  for i in range(R):
    m,t,p,j = map(int, input().split())
    if j==0:
      accepted[t][p] = 1
      time[t][p] = time[t][p] + m
    else:
      time[t][p] += 20

  score = defaultdict(int)
  for t in range(1,T+1):
    for p in range(1,P+1):
      score[t] +=  accepted[t][p] * 1<<16
      if accepted[t][p]:
        score[t] -= time[t][p]

  mp = defaultdict(list)
  prev = -1
  for k,v in score.items():
    mp[v].append(k)

  output = ""
  for sc,ts in sorted(mp.items(), key=lambda x: x[0], reverse=True):
    output += '='.join(map(str, sorted(ts, reverse=True)))
    output += ','
  else:
    print(output[:-1])

Solution (Python):
while 1:
    M, T, P, R = map(int, raw_input().split())
    if M+T+P+R==0:
        break
    score = [0]*T; cnt = [0]*T; failed = {}
    for i in xrange(R):
        m, t, p, j = map(int, raw_input().split())
        if j == 0:
            score[t-1] += m + failed.get((t, p), 0)
            cnt[t-1] += 1
        else:
            failed[t, p] = failed.get((t, p), 0) + 20
    result = {}
    for i in xrange(T):
        key = (cnt[i], -score[i])
        result.setdefault(key, []).append(i+1)
    ans = []
    for key in sorted(result, reverse=1):
        ans.append("=".join(map(str, reversed(result[key]))))
    print ",".join(ans)

Solution (Python):

"""
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=1187&lang=jp

"""
import sys
from sys import stdin
input = stdin.readline


class Team(object):
    def __init__(self, id):
        self.id = id
        self.correct = 0        
        self.time = 0           
        self.penalty = 0        
        self.status = {}        

    def judge(self, m, p, j):
        if j == 0:
            self.correct += 1
            self.time += m
            if p in self.status:
                self.penalty += 20 * self.status[p]
                del self.status[p]
        else:
            if p in self.status:
                self.status[p] += 1
            else:
                self.status[p] = 1


def calc_result(scores):
    
    result = []                 
    for i, s in enumerate(scores[1:], start=1):
        if s is not None:
            result.append([-s.correct, s.time+s.penalty, s.id*-1]) 
        else:
            result.append([0, 0, -i])
    result.sort()
    return result


def main(args):
    
    

    while True:
        M, T, P, R = map(int, input().split())
        if M == 0 and T == 0 and P == 0 and R == 0:
            break
        data = [[int(i) for i in input().split()]  for x in range(R)]

        scores = [None] * (T+1)
        for d in data:
            m, t, p, j = d
            if scores[t] == None:
                team = Team(t)
                scores[t] = team
            scores[t].judge(m, p, j)

        
        result = calc_result(scores)

        
        prev_corrent = result[0][0]
        prev_time = result[0][1]
        final_output = str(result[0][2]*-1)
        for r in result[1:]:
            if r[0] == prev_corrent and r[1] == prev_time:
                final_output += '='
                final_output += str(r[2]*-1)
            else:
                final_output += ','
                final_output += str(r[2]*-1)
                prev_corrent = r[0]
                prev_time = r[1]
        print(final_output)


if __name__ == '__main__':
    main(sys.argv[1:])

Solution (Python):

"""
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=1187&lang=jp
AC
"""
import sys
from sys import stdin
input = stdin.readline


class Team(object):
    def __init__(self, id):
        self.id = id
        self.correct = 0        
        self.time = 0           
        self.penalty = 0        
        self.status = {}        

    def judge(self, m, p, j):
        if j == 0:
            self.correct += 1
            self.time += m      
            self.penalty += 20 * self.status.pop(p, 0)
        else:
            if p in self.status:
                self.status[p] += 1
            else:
                self.status[p] = 1


def calc_result(scores):
    
    result = []                 
    for i, s in enumerate(scores[1:], start=1):
        if s is not None:
            result.append([-s.correct, s.time+s.penalty, s.id*-1]) 
        else:
            result.append([0, 0, -i])
    result.sort()
    return result


def main(args):
    
    

    while True:
        M, T, P, R = map(int, input().split())
        if M == 0 and T == 0 and P == 0 and R == 0:
            break
        data = [[int(i) for i in input().split()]  for x in range(R)]

        scores = [None] * (T+1)
        for d in data:
            m, t, p, j = d
            if scores[t] == None:
                team = Team(t)
                scores[t] = team
            scores[t].judge(m, p, j)

        
        result = calc_result(scores)

        
        prev_correct = result[0][0]
        prev_time = result[0][1]
        final_output = str(result[0][2]*-1)
        for r in result[1:]:
            if r[0] == prev_correct and r[1] == prev_time:
                final_output += '='
                final_output += str(r[2]*-1)
            else:
                final_output += ','
                final_output += str(r[2]*-1)
                prev_correct = r[0]
                prev_time = r[1]
        print(final_output)


if __name__ == '__main__':
    main(sys.argv[1:])

Solution (Python):
import sys

file_input = sys.stdin

for line in file_input:
    M, T, P, R = map(int, line.split())
    if M == 0:
        break
    
    
    
    result = [[0, M, i] + [0] * P for i in range(T+1)]
    
    for i in range(R):
        m, t, p, j = map(int, file_input.readline().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)

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

Solution (Python):
while True:
    M,T,P,R = map(int,input().split())
    if T == 0: break
    wrong = [[0 for i in range(P)] for j in range(T)]
    right = [0 for i in range(T)]
    pena = [0 for i in range(T)]
    for i in range(R):
        m,t,p,j = map(int,input().split())
        t,p = t-1,p-1
        if j == 0:
            right[t] += 1
            pena[t] += wrong[t][p] * 20 + m
        else:
            wrong[t][p] += 1
    result = []
    for t in range(T):
        result.append((-right[t], pena[t], -(t+1)))
    result.sort()
    ans = str(-result[0][2])
    for (r1,p1,t1),(r2,p2,t2) in zip(result, result[1:]):
        if r1 == r2 and p1 == p2:
            ans += '='
        else:
            ans += ','
        ans += str(-t2)
    print(ans)

Solution (Python):
def juni(tp):
    s = str(tp[0][0])
    for i in range(1, len(tp)):
        if tp[i - 1][1] == tp[i][1] and tp[i - 1][2] == tp[i][2]:
            s += "=" + str(tp[i][0])
        else:
            s += "," + str(tp[i][0])
    return s

while True:
    m, t, p, r = map(int, input().split())
    if m == 0:
        break
    tp = [[i, 0, 0, 0, [0 for j in range(p + 1)]] for i in range(t + 1)]
    for i in range(r):
        time, team, problem, hantei = map(int, input().split())
        if hantei > 0:
            tp[team][4][problem] += 1
        else:
            tp[team][1] += 1
            tp[team][2] += time
            tp[team][3] += tp[team][4][problem]
    tp.pop(0)
    for i in tp:
        i[2] += i[3] * 20
    tp.sort(reverse = True)
    tp.sort(key = lambda x:x[2])
    tp.sort(key = lambda x:x[1], reverse = True)
    print(juni(tp))

Solution (Python):
while True:
    m, t, p, r = map(int, input().split())
    if m == t == p == r == 0:
        break

    score = [[-1 for i in range(p + 1)] for j in range(t + 1)]
    for i in range(r):
        mi, ti, pi, j = map(int, input().split())
        if not j:
            score[ti][pi] = mi - (score[ti][pi] + 1) * 20
        else:
            score[ti][pi] -= 1

    data = list()
    for ti in range(1, t + 1):
        ans = 0
        pen = 0
        for pi in range(1, p + 1):
            if score[ti][pi] >= 0:
                ans += 1
                pen += score[ti][pi]
        data.append((ans, -pen, ti))

    data.sort(reverse = True)
    for i in range(t - 1):
        ans, pen, ti = data[i]
        pen = -pen
        print(ti, end = "")
        if ans > data[i + 1][0] or pen < - data[i + 1][1]:
            print(",", end = "")
        else:
            print("=", end = "")
    print(data[t - 1][2])

Solution (Python):
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 998244353

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    rr = []

    while True:
        M,T,P,R = LI()
        if M == 0 and T == 0 and P == 0 and R == 0:
            break
        a = [LI() for _ in range(R)]
        d = collections.defaultdict(int)
        tt = [[0,0,i] for i in range(1,T+1)]
        for m,t,p,j in a:
            if j != 0:
                d[(t,p)] += 1
                continue
            tt[t-1][0] += 1
            tt[t-1][1] += m + d[(t,p)] * 20
        tt.sort(key=lambda x: [-x[0],x[1],-x[2]])
        r = str(tt[0][2])
        c = (tt[0][0],tt[0][1])
        for p,m,t in tt[1:]:
            if c == (p,m):
                r += '='
            else:
                r += ','
            r += str(t)
            c = (p,m)
        rr.append(r)

    return '\n'.join(map(str, rr))


print(main())

Solution (Python):
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))

Solution (Python):
while True:
    M,T,P,R=map(int,raw_input().split())
    if M==T==P==R==0:break
    PB=[[False]*P for i in range(T+1)]
    PN=[[0]*P for i in range(T+1)]
    TM=[M]*(T+1)
    for i in range(R):
        m,t,p,r=map(int,raw_input().split())
        if r==0:
            PB[t][p-1]=True
            TM[t]+=m
        else:
            PN[t][p-1]+=1
    for i in range(1,T+1):
        for j in range(P):
            if PB[i][j]:
                TM[i]+=PN[i][j]*20
    solved=[sum(i) for i in PB]
    ans=[]
    for i in range(1,T+1):
        ans.append((-solved[i],TM[i],i))
    import operator
    ans=ans[::-1]
    ans.sort(key=operator.itemgetter(1))
    ans.sort(key=operator.itemgetter(0))
    s=str(ans[0][2])
    for i in range(1,T):
        if (ans[i][0]!=ans[i-1][0]) or (ans[i][1]!=ans[i-1][1]):
            s+=","+str(ans[i][2])
            continue
        s+="="+str(ans[i][2])
    print s

Solution (Python):
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

Solution (Python):
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

Solution (Python):
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()

Solution (Python):
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()

Solution (Python):
from inspect import currentframe


def debug_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)

Solution (Python):
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)

Solution (Python):
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)]) 
        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()

Solution (Python):
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)