-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy path2.py
153 lines (132 loc) · 5.57 KB
/
2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
# 68459084
# Сортировка происходит с использованием метода двух указателей с определённой
# логикой смещения, кроме того используется рекурсия для дробления массива на
# части. Для данной реализации нужно выбрать опорный элемент, а затем выполнить
# сортировку, так что бы элементы, которые больше опорного элемента, были
# справа, а те что меньше слева (в нашем случае, наоборот, участник с лучшим
# решением должен быть слева, а с худшим справа), для сравнения участников,
# используется функция comparator. А для реализации смещения указателей и
# перестановки элементов, использовался подход при котором левый указатель
# будет смещаться до тех пор, пока он не будет указывать на элемент больше
# опорного, затем таким же способом необходимо смещать правый указатель,
# пока он не будет указывать на элемент, меньше опорного,
# после того как эти два элемента будут найдены, нужно их переставить.
# Опорный элемент будет находиться рандомно(для оптимизации сортировки
# отсортированного массива), так же можно было бы всегда брать первый элемент
# как опорный, экономя производительность на получение рандомного элемента.
# Временная сложность 0(n*log(n)). Худший случай O(n^2).
# Пространственная сложность O(1). Требуется дополнительная память для хранения
# стека вызовов.
import sys
from abc import (
abstractmethod,
ABC,
)
from dataclasses import dataclass
from random import randint
from typing import (
List,
Optional,
Callable,
TypeVar,
Generic,
Tuple,
Any,
)
class Comparable(ABC):
@abstractmethod
def __lt__(self, other: Any) -> bool:
...
@abstractmethod
def __gt__(self, other: Any) -> bool:
...
Item = TypeVar("Item", bound=Comparable)
class InPlaceQuickSort(Generic[Item]):
__slots__ = ()
@staticmethod
def _compare_items(
first: Item,
second: Item,
comparator: Optional[Callable[[Item, Item], bool]],
) -> bool:
if comparator:
return comparator(first, second)
return first > second
@classmethod
def _partition(
cls,
array: List[Item],
low: int,
high: int,
comparator: Optional[Callable[[Item, Item], bool]] = None,
) -> Tuple[int, int]:
pivot: Item = array[randint(low, high)]
while low <= high:
while low <= high and cls._compare_items(
first=array[high], second=pivot, comparator=comparator
):
high -= 1
while low <= high and cls._compare_items(
first=pivot, second=array[low], comparator=comparator
):
low += 1
if low <= high:
array[low], array[high] = array[high], array[low]
low += 1
high -= 1
return low, high
@classmethod
def sort(
cls,
array: List[Item],
comparator: Optional[Callable[[Item, Item], bool]] = None,
start: Optional[int] = None,
end: Optional[int] = None,
) -> None:
if start is None:
start = 0
if end is None:
end = len(array) - 1
if start >= end:
return
low, high = cls._partition(array, start, end, comparator)
cls.sort(array, comparator, start, high)
cls.sort(array, comparator, low, end)
@dataclass
class Participant(Comparable):
name: str
solved_task_count: int
fine: int
def __gt__(self, other: Any) -> bool:
if not isinstance(other, Participant):
raise AssertionError("Incorrect type for comparison")
if (
self.solved_task_count == other.solved_task_count
and self.fine == other.fine
):
return self.name > other.name
if self.solved_task_count == other.solved_task_count:
return self.fine > other.fine
return self.solved_task_count < other.solved_task_count
def __lt__(self, other: Any) -> bool:
if not isinstance(other, Participant):
raise AssertionError("Incorrect type for comparison")
return other > self
def get_data() -> List[Participant]:
length: int = int(input())
result: List[Participant] = []
for _ in range(length):
data: List[str] = sys.stdin.readline().rstrip().split()
result.append(
Participant(
name=data[0], solved_task_count=int(data[1]), fine=int(data[2])
)
)
return result
def main() -> None:
data: List[Participant] = get_data()
InPlaceQuickSort[Participant].sort(array=data)
for i in data:
print(i.name)
if __name__ == "__main__":
main()