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: Wrong Answer

Solution code:
while True:
    M, T, P, R = map(int, input().split())
    if M == 0 and T == 0 and P == 0 and R == 0:
        break
    teams = [[0, 0, [0 for _ in range(P)], i+1] for i in range(T)]
    solved, time, miss = 0, 1, 2
    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 + teams[t][miss][p] * 20)
        else:
            teams[t][miss][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('')

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
"""
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 = {}        #  ?????£?§£?????¶??? key: ????????????, value: ????????£????????°

    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):
    # ???????????????????????¢????????§?????????????????£?§£??°?????????????????????????????????????????§???????????????????????????l
    result = []                 #  ??????????????¨??????[??£?§£??°*(-1), ????????????, ???????????????*(-1)] ??????????????§?¨?????????? 
    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]) #  sort()??????????????????????????£????????????????????????????????£?§£??°??¨??????????????????-1???????????????
        else:
            result.append([0, 0, -i])
    result.sort()
    return result


def main(args):
    # M, T, P, R = 300, 10, 8, 5,
    # data = [[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 == 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:])

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
"""
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 = {}        #  ?????£?§£?????¶??? key: ????????????, value: ????????£????????°

    def judge(self, m, p, j):
        if self.id == 30:
            print('hoge')
        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):
    # ???????????????????????¢????????§?????????????????£?§£??°?????????????????????????????????????????§???????????????????????????l
    result = []                 #  ??????????????¨??????[??£?§£??°*(-1), ????????????, ???????????????*(-1)] ??????????????§?¨??????????
    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]) #  sort()??????????????????????????£????????????????????????????????£?§£??°??¨??????????????????-1???????????????
        else:
            result.append([0, 0, -i])
    result.sort()
    return result


def main(args):
    # M, T, P, R = 300, 10, 8, 5,
    # data = [[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 == 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:])

Submission status: Wrong Answer

Solution code:
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

Submission status: Accepted

Solution code:
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
    #    print(1, M, T, P, 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)
  #  print(team_point)
#    print(ans)
 #   print(team_point)

#print(ans_list)
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()

Submission status: Accepted

Solution code:
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)]
    # [-solved, time, -team]
    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)

Submission status: Accepted

Solution code:
#! /usr/bin/env python
# -*- coding: utf-8 -*-

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()

Submission status: Accepted

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

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

while True:
    M,T,P,R = map(int,input().split(" "))
    if M == 0 and T == 0 and P == 0 and R == 0:
        break
    #no, correct, wrong, time
    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()

Submission status: Accepted

Solution code:
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 ""

Submission status: Accepted

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

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
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 = {}        #  ?????£?§£?????¶??? key: ????????????, value: ????????£????????°

    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):
    # ???????????????????????¢????????§?????????????????£?§£??°?????????????????????????????????????????§???????????????????????????l
    result = []                 #  ??????????????¨??????[??£?§£??°*(-1), ????????????, ???????????????*(-1)] ??????????????§?¨??????????
    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]) #  sort()??????????????????????????£????????????????????????????????£?§£??°??¨??????????????????-1???????????????
        else:
            result.append([0, 0, -i])
    result.sort()
    return result


def main(args):
    # M, T, P, R = 300, 10, 8, 5,
    # data = [[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 == 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:])

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
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 = {}        #  ?????£?§£?????¶??? key: ????????????, value: ????????£????????°

    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 = []                 #  ??????????????¨??????[??£?§£??°*(-1), ????????????, ???????????????*(-1)] ??????????????§?¨??????????
    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]) #  sort()??????????????????????????£????????????????????????????????£?§£??°??¨??????????????????-1???????????????
        else:
            result.append([0, 0, -i])
    result.sort()
    return result


def main(args):
    # M, T, P, R = 300, 10, 8, 5,
    # data = [[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 == 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:])

Submission status: Accepted

Solution code:
import sys

file_input = sys.stdin

for line in file_input:
    M, T, P, R = map(int, line.split())
    if M == 0:
        break
    
    # [number of solved probrems, complement of elapsed time, team number] + [rejected times] * P
    # [rejected times] * P will be accessed in reverse order.
    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])

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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))

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
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