2nd Algorithm Practical Test Solve past questions with python (unfinished)

The second algorithm practical test problem is solved with python. We will update it as soon as it is solved.

A Replace B with-and be careful when comparing the basement and ground floors (e.g. 1F --B1 $ = $ 1 $ \ neq $ 2).

# A

def f(i):
    num = int(i.replace('B', '-').replace('F', ''))
    return num if 'B' not in i else num + 1

inp = input().split()
arr = list(map(f, inp))
ans = arr[0] - arr[1]
print(ans if ans >= 0 else -ans)

B Just count.

# B

S = input()

import collections
d = dict(collections.Counter(S))
print(max(d.keys(), key=lambda k: d[k]))

C The maximum number of elements is about $ 50 ^ 2 = 2500 $ (the number actually processed is smaller), so it is enough to honestly examine all the elements.

# C

N = int(input())
Ss = list(input() for i in range(N))

for i in range(N-2, -1, -1):
    for j in range(2*N-1):
        if Ss[i][j] == '#':
            if j != 0 and Ss[i+1][j-1] == 'X':
                Ss[i] = Ss[i][:j] + 'X' + Ss[i][j+1:]
            if j != 2 * N - 1 and Ss[i+1][j+1] == 'X':
                Ss[i] = Ss[i][:j] + 'X' + Ss[i][j+1:]
            if Ss[i+1][j] == 'X':
                Ss[i] = Ss[i][:j] + 'X' + Ss[i][j+1:]

for s in Ss:
    print(s)

D This also has a small number of patterns, so it is enough to investigate all the patterns.

# D
 
S = input()
N = len(S)

# N = 0
if N == 0:
    print(0)
    exit()

# lenth = 1
ans = set([S[i] for i in range(N)]) | {'.'}
if N == 1:
    print(len(ans))
    exit()

# lenth = 2
for i in range(1, N):
    ans |= {'{}{}'.format(S[i-1], S[i]), '.{}'.format(S[i]), '{}.'.format(S[i-1])}
ans |= {'..'}
if N == 2:
    print(len(ans))
    exit()

for i in range(2, N):
    ans |= {'{}{}{}'.format(S[i-2], S[i-1], S[i]), '.{}{}'.format(S[i-1], S[i]), '{}.{}'.format(S[i-2], S[i]), \
            '{}{}.'.format(S[i-2], S[i-1]), '..{}'.format(S[i-2]), '.{}.'.format(S[i-1]), '{}..'.format(S[i])}
ans |= {'...'}
print(len(ans))

E This also requires a small number of calculations, so all the elements should be investigated.

# E

N = int(input())
As = list(map(int, input().split()))

def replace_and_recursion(x, target, iter):
    x = As[x-1]
    if x-1 == target:
        return str(iter)
    else:
        return replace_and_recursion(x, target, iter+1)

print(' '.join([replace_and_recursion(i+1, i, 1) for i in range(N)]))

F From the first day, you can process the tasks with the highest points. Sorting every day doesn't have enough time, so adding it to an element with bisect will give you enough processing time.

# F
 
N = int(input())
ABs = [list(map(int, input().split())) for i in range(N)] + [[N, 0]]
import itertools
ABs = sorted(ABs, key=lambda ab: ab[0])
groups = {k:list(g) for k, g in itertools.groupby(ABs, key=lambda ab: ab[0])}
 
import bisect
sorted_arr = []
last = 0
for k in range(1, N+1):
    if k in groups.keys():
        group = groups[k]
        for g in group:
            index = bisect.bisect_right(sorted_arr, g[1])
            sorted_arr.insert(index, g[1])
 
    task = sorted_arr.pop(-1)
    print(last + task)
    last += task```

G

Create a string and delete it from it. .. .. If you do, you will not have enough time, so you can store the query information in a queue and process it in time.

 G
 
Q = int(input())
Qs = [input().split() for i in range(Q)]
 
from collections import Counter, deque
deq = deque()
for q in Qs:
    if q[0] == '1':
        deq.append({'char': q[1], 'size': int(q[2])})
    if q[0] == '2':
        size = int(q[1])
        dic = {}
        while deq and size > 0:
            data = deq[0]
            if data['size'] >= size:
                dic[data['char']] = dic.get(data['char'], 0) + size
                deq[0]['size'] -= size
                size = 0
            else:
                dic[data['char']] = dic.get(data['char'], 0) + data['size']
                size -= data['size']
                deq.popleft()
 
        print(sum([dic[moji]**2 for moji in dic.keys()]))

H

S -> {1} -> {2} ... ->The state transition to G should be performed.

 H

N, M = list(map(int, input().split()))
A_matrix = [input() for i in range(N)]

max_cost = 10**9
number_loc_cost = {}
 rec
for i in range(N):
    A_row = A_matrix[i]
    for j in range(M):
        val = A_row[j]
        if val not in number_loc_cost.keys():
            number_loc_cost[val] = {}
        number_loc_cost[val][i * M + j] = max_cost

S_loc = number_loc_cost['S'].keys()
for s_loc in S_loc:
    number_loc_cost['S'][s_loc] = 0

targets = ['S'] + list(range(1, 9+1)) + ['G']
try:
    for i in range(len(targets)-1):
        frm = str(targets[i])
        to = str(targets[i+1])

        for f_loc in number_loc_cost[frm].keys():
            f_x, f_y = f_loc % M, f_loc // M
            for t_loc in number_loc_cost[to].keys():
                t_x, t_y = t_loc % M, t_loc // M
                cost = abs(f_x - t_x) + abs(f_y - t_y)
                number_loc_cost[to][t_loc] = min(number_loc_cost[to][t_loc], number_loc_cost[frm][f_loc] + cost)
    G_loc = list(number_loc_cost['G'].keys())[0]
    print(number_loc_cost['G'][G_loc])
except:
    print(-1)

I

Divide the list of participants into even and odd numbers and compare them. Only the participants who have won the comparison can update the participant list, and then repeat the same comparison.

 I

N = int(input())
As = tuple(map(int, input().split()))

results = {}
id_to_power = {i: As[i] for i in range(2 ** N)}
ids = list(id_to_power.keys())


n = 1
while len(ids) > 1:
    size = len(ids)
    res = [id_to_power[ids[2*i]] > id_to_power[ids[2*i+1]] for i in range(size // 2)]

    for i in range(size // 2): results[ids[2*i+1] if res[i] else ids[2*i]] = n
    ids = [ids[2*i] if res[i] else ids[2*i+1] for i in range(size // 2)]
    n += 1

results[ids[0]] = n-1

for i in range(len(id_to_power)):
    print(results[i])

J

Data is stored for each depth of parentheses, and information is applied to the next higher hierarchy when the parentheses are closed.(d[depth-1] += d[depth] + d[depth][::-1])Just do.

 J

S = input()

res = ''
depth = 0
bracket_depth_to_str = {depth: ''}
for s in S:
    if s == '(':
        depth += 1
        bracket_depth_to_str[depth] = ''
    elif s == ')':
        bracket_depth_to_str[depth-1] += bracket_depth_to_str[depth] + bracket_depth_to_str[depth][::-1]
        depth -= 1
    else:
        bracket_depth_to_str[depth] += s

print(bracket_depth_to_str[0])

K

Not yet after K.

L

M

N

O

Recommended Posts

2nd Algorithm Practical Test Solve past questions with python (unfinished)
1st Algorithm Practical Test Solve past questions with python
The 3rd Algorithm Practical Test (PAST) Explanation (Python)
Algorithm learned with Python 2nd: Vending machine
Solve with Python [100 selected past questions that beginners and intermediates should solve] (056 --059 Shortest path problem: Dijkstra's algorithm)
Solve with Python [100 past questions that beginners and intermediates should solve] (053 --055 Dynamic programming: Others)
Primality test with Python
Solve AtCoder 167 with python
Primality test with python
Solve Sudoku with Python
Solve POJ 2386 with python
Solve with Python [100 selected past questions that beginners and intermediates should solve] (015 --017 Full search: Permutation full search)
Solve with Python [100 selected past questions that beginners and intermediates should solve] (010 --014 Full search: Bit full search)
Solve with Python [100 selected past questions that beginners and intermediates should solve] (001 --004 All search: All enumeration)
[Python] Solve equations with sympy
Solve AtCoder ABC166 with python
[Python3] Dijkstra's algorithm with 14 lines
Solve AtCoder ABC 186 with Python
solver> Link> Solve Excel Solver with python
Solve ABC163 A ~ C with Python
Solve AtCoder Problems Recommendation with python (20200517-0523)
Solve ABC168 A ~ C with Python
Unit test log output with python
Solve ABC162 A ~ C with Python
Solve ABC167 A ~ C with Python
Solve ABC158 A ~ C with Python
Implementation of Dijkstra's algorithm with python
Solve with Python [100 selections of past questions that beginners and intermediates should solve] (034-038 Dynamic programming: Knapsack DP basic)
Solve with Python [100 selections of past questions that beginners and intermediates should solve] (039 --045 Dynamic programming: Knapsack DP variant)
Algorithm learned with Python 10th: Binary search
[Python] Super easy test with assert statement
Stress Test with Locust written in Python
Algorithm learned with Python 5th: Fibonacci sequence
Algorithm learned with Python 9th: Linear search
WebUI test with Python2.6 + Selenium 2.44.0 --profile setting
Algorithm learned with Python 7th: Year conversion
Algorithm learned with Python 8th: Evaluation of algorithm
Search the maze with the python A * algorithm
Post Test 3 (Working with PosgreSQL in Python)
How to do portmanteau test with python
[Python] Solve 10 past elite problems of Atcoder
[AtCoder] Solve ABC1 ~ 100 A problem with Python
Integrating with setuptools / python setup.py test / pytest-runner
Algorithm learned with Python 6th: Leap year
Solve AtCoder ABC168 with python (A ~ D)
Algorithm learned with Python 3rd: Radix conversion
Solve Lake Counting (POJ NO.2386) with Python3
I wanted to solve ABC172 with Python
Let's develop an investment algorithm with Python 1
Algorithm learned with Python 12th: Maze search
Algorithm learned with Python 11th: Tree structure
AtCoder 3rd Algorithm Practical Test Participation Report
Try to solve the traveling salesman problem with a genetic algorithm (Python code)
[Python] I tried to solve 100 past questions that beginners and intermediates should solve [Part7 / 22]
[Python] I tried to solve 100 past questions that beginners and intermediates should solve [Part 4/22]
[Python] I tried to solve 100 past questions that beginners and intermediates should solve [Part3 / 22]
[Python] I tried to solve 100 past questions that beginners and intermediates should solve [Part 1/22]
[Python] I tried to solve 100 past questions that beginners and intermediates should solve [Part 6/22]