Skip to content

Commit 9ed708e

Browse files
committed
solved(python): baekjoon 7578
1 parent 5cc5e15 commit 9ed708e

File tree

4 files changed

+88
-0
lines changed

4 files changed

+88
-0
lines changed

baekjoon/python/7578/__init__.py

Whitespace-only changes.

baekjoon/python/7578/main.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import sys
2+
3+
read = lambda: sys.stdin.readline().rstrip()
4+
5+
6+
class Problem:
7+
def __init__(self):
8+
self.n = int(read())
9+
self.a, self.b = list(map(int, read().split())), list(map(int, read().split()))
10+
11+
self.tree = [0] * (self.n + 1)
12+
13+
def solve(self) -> None:
14+
pos_b, crossings = {machine_id: idx for idx, machine_id in enumerate(self.b)}, 0
15+
16+
for idx in range(self.n):
17+
b_index = pos_b[self.a[idx]]
18+
crossings += self.query(self.n - 1) - self.query(b_index)
19+
20+
self.update(b_index, 1)
21+
22+
print(crossings)
23+
24+
def update(self, idx: int, value: int) -> None:
25+
idx += 1
26+
while idx <= self.n:
27+
self.tree[idx] += value
28+
idx += idx & -idx
29+
30+
def query(self, idx: int) -> int:
31+
idx, value = idx + 1, 0
32+
while idx > 0:
33+
value += self.tree[idx]
34+
idx -= idx & -idx
35+
36+
return value
37+
38+
39+
if __name__ == "__main__":
40+
Problem().solve()

baekjoon/python/7578/sample.json

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
[
2+
{
3+
"input": [
4+
"5",
5+
"132 392 311 351 231",
6+
"392 351 132 311 231"
7+
],
8+
"expected": [
9+
"3"
10+
]
11+
}
12+
]

baekjoon/python/7578/test_main.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import json
2+
import os.path
3+
import unittest
4+
from io import StringIO
5+
from unittest.mock import patch
6+
7+
from parameterized import parameterized
8+
9+
from main import Problem
10+
11+
12+
def load_sample(filename: str):
13+
path = os.path.join(os.path.dirname(os.path.abspath(__file__)), filename)
14+
15+
with open(path, "r") as file:
16+
return [(case["input"], case["expected"]) for case in json.load(file)]
17+
18+
19+
class TestCase(unittest.TestCase):
20+
@parameterized.expand(load_sample("sample.json"))
21+
def test_case(self, case: str, expected: list[str]):
22+
# When
23+
with (
24+
patch("sys.stdin.readline", side_effect=case),
25+
patch("sys.stdout", new_callable=StringIO) as output,
26+
):
27+
Problem().solve()
28+
29+
result = output.getvalue().rstrip()
30+
31+
# Then
32+
self.assertEqual("\n".join(expected), result)
33+
34+
35+
if __name__ == "__main__":
36+
unittest.main()

0 commit comments

Comments
 (0)