[Python] I tried to solve 100 past questions that beginners and intermediates should solve [Part 6/22]

** Aim for a light blue coder! !! !! !! !! !! ** **

So [Guidelines for improving AtCoder, a competition pro taught by Red Coder [Intermediate Edition: Aim for Light Blue Coder! ]]( https://qiita.com/e869120/items/eb50fdaece12be418faa#2-3-%E5%88%86%E9%87%8E%E5%88%A5%E5%88%9D%E4%B8%AD%E7 % B4% 9A% E8% 80% 85% E3% 81% 8C% E8% A7% A3% E3% 81% 8F% E3% 81% B9% E3% 81% 8D% E9% 81% 8E% E5% 8E % BB% E5% 95% 8F% E7% B2% BE% E9% 81% B8-100-% E5% 95% 8F) (@ e869120)

AtCoder has collected 100 good educational questions that are appropriate for brown and green coders to achieve a light blue coder, or rating 1200, with a small number of questions.

100 past questions that beginners and intermediates should solve in this article` Will be solved with ** Python **! Thanks to @ e869120! !! !! !! !! !!

Past article link

** Search all: List all ** [Python] I tried to solve 100 past questions that beginners and intermediates should solve [Part1 / 22] ** Full search: All enumeration to reduce the number of streets by devising ** [Python] I tried to solve 100 past questions that beginners and intermediates should solve [Part2 / 22] ** Full search: Bit full search ** [[Python] I tried to solve 100 past questions that beginners and intermediates should solve [Part3 / 22]] (https://qiita.com/rudorufu1981/items/74d5f37c26c62fc7a27f) ** Full search: Permutation full search ** [Python] I tried to solve 100 past questions that beginners and intermediates should solve [Part4 / 22] ** Binary search ** [Python] I tried to solve 100 past questions that beginners and intermediates should solve [Part5 / 22] ** Depth-first search ** [Python] I tried to solve 100 past questions that beginners and intermediates should solve [Part6 / 22] ** Breadth-first search ** [Python] I tried to solve 100 past questions that beginners and intermediates should solve [Part7 / 22]

"Part 6" -Depth-first search (DFS)-

We will solve the following 4 questions!

Depth-first search

24 ALDS_11_B --Depth-first search This is a basic problem. 25 AOJ 1160-How many islands are there? The number of connected components in the graph can be calculated by depth-first search. 26 AtCoder Beginner Contest 138 D --Ki Many tree structure problems use depth-first search. 27 JOI 2009 Qualifying 4-Thin ice migration Depth-first search is not just a tree structure, it is a problem that tells us. It can be solved using a recursive function.

DFS prerequisites

・ I will write an article based on the following three points! ** ① About stacks and queues ** First of all, Kencho's article Master stacks and cues! ~ Special feature on ideas and uses ~ Read about ** Atmosphere About Stacks and Queues! ** **

** ② About DFS and graph ** Another article by Kencho DFS (Depth-first Search) Super Introduction! ~ Entrance to the world of graph algorithms ~ [Part 1] DFS (Depth-first Search) Super Introduction! ~ Entrance to the world of graph algorithms ~ [Part 2] Read about DFS and Graphs ** Understand the Atmosphere! ** **

** ③ After that, how to implement DFS in Python ** As The following sites were easy to understand, so these two sites ** ◆ For ordinary graphs or trees ** Algorithm in Python (depth-first search, dfs) ** ◆ For grid graph ** Implementing Depth-First Search (DFS) in Python-ATC001 ** Carefully ** Read about DFS and Graphs ** Deeply! ** **

If you have the premise of ①②③, you can learn it by actually moving your hands! !! !!

24 ALDS_11_B --Depth-first search

Typical graph problem!

graph = {i:collections.deque() for i in range(1,N+1)} Or graph = {i:[] for i in range(1,N+1)} ** This is the graph template! ** **

It was my first time implementing DFS, I tried to implement it according to the above site ** I managed to implement it! ** ** The code is long, but ** the difficulty isn't that great! !! !! ** **

The point is these two lines! !! !!

seen[j] = 1
stack.append(j)
seen[g_NO] = 1
stack.append(g_NO)

~ How to remember ~ ① ** I saw the housekeeper! ** (drama), so Change seen to0 (False)1 (True)! ② If you see the housekeeper, put it in stock! !! !! ** (The housekeeper saw the trash, so I put it in the trash can !!!) **

If you have this image in mind, you can write code with brain death at the time of implementation!

test.py


import collections,sys
def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))
n = I()
ukv = [LI() for _ in range(n)]
graph = {i:collections.deque() for i in range(1,n+1)} #1_indexed
for x in ukv:
    u,k,*v = x
    for y in v:
        graph[u].append(y)
seen = [0]*(n+1) #1_indexed
stack = []
time = 0
seentime = [0]*(n+1) #1_indexed
donetime = [0]*(n+1) #1_indexed
def dfs(j):
    global time
    seen[j] = 1
    stack.append(j)
    time += 1
    seentime[j] = time
    while stack:
        s = stack[-1]
        if not graph[s]:
            stack.pop()
            time += 1
            donetime[s] = time
            continue
        g_NO = graph[s].popleft()
        if seen[g_NO]:
            continue
        seen[g_NO] = 1
        stack.append(g_NO)
        time += 1
        seentime[g_NO] = time
for j in range(1,n+1):
    if seen[j]:
        continue
    dfs(j)
for k,a,b in zip(range(1,n+1),seentime[1:],donetime[1:]):
    print(k,a,b)

I don't need to write def dfs (), but I tried to make it def so that it is easy to understand with the DFS description!

Also, the graph problem I think most of the time it starts with "1" instead of "0" Unify the entire code with 1_indexed!

I also tried using global for the first time, but I see! It feels like!

Another thing I was aware of when writing the code was ** I used continue as much as possible to prevent running code below the conditions to improve readability! ** ** DFS tends to be particularly nestled! (= Tends to be complicated = Bugs are more likely to occur!)

** The housekeeper saw! (Second time)**

25 AOJ 1160-How many islands are there?

Typical grid graph problem! The problem and the way of thinking of a normal graph are the same! I referred to the above site, but ** I was surprised! ** ** ** The housekeeper saw! (Third time)**

test.py


import collections,itertools,sys
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))
while 1:
    w,h = LI()
    if w==h==0:
        break
    ans = 0
    c = [LI() for _ in range(h)]
    seen = [[0]*w for _ in range(h)]
    stack = []
    dhdw = [[-1,-1],[-1,0],[-1,1],[0,-1],[0,1],[1,-1],[1,0],[1,1]]
    def dfs(H,W):
        seen[H][W] = 1
        stack.append([H,W])
        while stack:
            sh,sw = stack.pop()
            for dh,dw in dhdw:
                nh,nw = sh+dh,sw+dw
                if not(0<=nh<=h-1) or not(0<=nw<=w-1) or seen[nh][nw] or c[nh][nw]==0:
                    continue
                seen[nh][nw] = 1
                stack.append([nh,nw])
    for H,W in itertools.product(range(h),range(w)):
        if seen[H][W] or c[H][W]==0:
            continue
        ans += 1
        dfs(H,W)
    print(ans)

26 AtCoder Beginner Contest 138 D - Ki Difficulty:923 ** I couldn't solve it at first sight! !! !! ** ** I stumbled on the amount of calculation and stumbled on the idea of roots! However, from now on, there will be a ** "tree" ** that can solve similar problems! !! !!

These two points are the points!

--Think of trees as undirected graphs --From the problem statement, the root of this whole tree is apex 1

All the vertices below the root feel like adding reference root points ~ If you didn't become AC, please refer to this article! !! !! AtCoder Beginner Contest 138 D --Ki test cases are increasing after the contest (modified version)

** The housekeeper saw! (4th)**

test.py


import collections,sys
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))
N,Q = LI()
ab = [LI() for _ in [None]*(N-1)]
px = [LI() for _ in [None]*(Q)]
ans = [0]*(N+1) #1_indexed
graph = {i:collections.deque() for i in range(1,N+1)} #1_indexed
for a,b in ab:
        graph[a].append(b)
        graph[b].append(a)
for p,x in px:
    ans[p] += x
seen = [0]*(N+1) #1_indexed
stack = []
def dfs():
    seen[1] = 1
    stack.append(1)
    while stack:
        s = stack.pop()
        if not graph[s]:
            continue
        for j in range(len(graph[s])):
            g_NO = graph[s].popleft()
            if seen[g_NO]:
                continue
            seen[g_NO] = 1
            stack.append(g_NO)
            ans[g_NO] += ans[s]
dfs()
print(*ans[1:])

By the way, Described in Supplement 2 at the beginning

Input from this article (** Part 6 **) input()sys.stdin.readline().rstrip() I'm changing to!

The cause of this is this problem w

I was struggling with TLE, but when I saw the code of someone who could do it, sys.stdin.readline() I'm using ... When I tried using it for the time being, I was surprised that it became an AC! Upon examination, it turns out that ** ʻinput ()` is extremely slow! !! !! ** ** Reference article 8 small differences in processing speed that Python should know

There is room for improvement in the code regarding the amount of calculation, (For example, where you receive ʻab and px`) It's AC, so no ~

27 JOI 2009 Qualifying 4-Thin Ice Crossing

** I couldn't solve this at first sight either! !! !! ** **

No way ** I saw the housekeeper! The problem that (seen) ** cannot be used! !! !! Past articles [Python] I tried to solve 100 past questions that beginners and intermediates should solve [Part3 / 22] The subset sum problem is also a problem that can be solved by DFS. ** The housekeeper saw! If (seen) ** isn't available, ** the housekeeper saw! The difficulty level is higher because you have to think about what will change to (seen) **!

--Part3 subsum problem: ** index and sum ** --This issue: ** Position at stack, past history **

** You have to solve a lot of difficult problems and get used to it! ** **

test.py


import itertools,sys
def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))
m = I()
n = I()
area = [LI() for _ in range(n)]
ans = 0
dndm = [[1,0],[-1,0],[0,1],[0,-1]]
stack = [] #Stacked position, past history
def dfs(i,j):
    global ans
    stack.append([[i,j],set()])
    while stack:
        [sn,sm],history = stack.pop()
        ans = max(ans,len(history))
        for dn,dm in dndm:
            nn,nm = sn+dn,sm+dm
            if not(0<=nn<=n-1) or not(0<=nm<=m-1) or area[nn][nm]==0 or ((nn,nm) in history):
                continue
            stack.append([[nn,nm],history | {(nn,nm)}])
for i,j in itertools.product(range(n),range(m)):
    if area[i][j]==1:
        dfs(i,j)
print(ans)
history | {(nn,nm)}

of | is a union! (Also a bitwise OR) Also, & is the intersection! (Also a bitwise AND) ^ Is a set of either `! (Also a bitwise XOR)

Next time, I will solve the following 6 questions!

Breadth-first search

28 ALDS_11_C --Breadth-first search This is a basic problem. 29 AtCoder Beginner Contest 007 C --Breadth-first search The shortest path problem of a weightless graph can be solved by breadth-first search. 30 JOI 2011 Qualifying 5-Cheese 31 JOI 2012 Qualifying 5-Illuminations The implementation is a little heavy, but if you do your best, you can solve it. 32 AOJ 1166 --Maze and order The implementation is a little heavy. 33 AtCoder Beginner Contest 088 D --Grid Repainting If this is solved, you can think that you are accustomed to breadth-first search.

Part6/22 end!

Next (Part 7/22)

Recommended Posts

[Python] I tried to solve 100 past questions that beginners and intermediates should solve [Part 5/22]
[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]
Solve with Python [100 past questions that beginners and intermediates should solve] (028 --033 breadth-first search)
Solve with Python [100 past questions that beginners and intermediates should solve] (053 --055 Dynamic programming: Others)
Solve with Python [100 selected past questions that beginners and intermediates should solve] (024 --027 Depth-first 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)
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 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)
Solve with Python [100 selected past questions that beginners and intermediates should solve] (005 --- 009 All search: All enumeration to reduce the number of streets by devising)
[For beginners in competition professionals] I tried to solve 40 AOJ "ITP I" questions with python
I tried to solve the ant book beginner's edition with python
I tried to solve the soma cube with python
I tried to solve the problem with Python Vol.1
I tried to solve AOJ's number theory with Python
I tried to enumerate the differences between java and python
I tried to make GUI tic-tac-toe with Python and Tkinter
I tried to summarize the languages that beginners should learn from now on by purpose
Tohoku University 2020 First semester math exam (science) I tried to solve major questions 1 to 3 with Python
I tried to touch Python (installation)
python beginners tried to find out
[Python] A memo that I tried to get started with asyncio
[Pandas] I tried to analyze sales data with Python [For beginners]
I tried to make a periodical process with Selenium and Python
I tried to easily detect facial landmarks with python and dlib
[Python] I tried to explain words that are difficult for beginners to understand in an easy-to-understand manner.
I tried to summarize Python exception handling
I tried to implement PLSA in Python
I tried to implement permutation in Python
A super introduction to Django by Python beginners! Part 3 I tried using the template file inheritance function
How to write offline real time I tried to solve E11 with python
I tried to implement PLSA in Python 2
Python3 standard input I tried to summarize
I wanted to solve ABC160 with Python
I tried using PyEZ and JSNAPy. Part 2: I tried using PyEZ
I tried to implement ADALINE in Python
I tried to let optuna solve Sudoku
I tried to develop a Formatter that outputs Python logs in JSON
A super introduction to Django by Python beginners! Part 2 I tried using the convenient functions of the template
I tried to make Kana's handwriting recognition Part 2/3 Data creation and learning
I wanted to solve ABC159 in Python
I tried to implement PPO in Python
10 Python errors that are common to beginners
I tried to verify and analyze the acceleration of Python by Cython
I tried to solve AtCoder's depth-first search (DFS) in Python (result: TLE ...)
I tried to solve TSP with QAOA
[Python] I tried to calculate TF-IDF steadily
[Markov chain] I tried to read quotes and negative emotions into Python.
I tried to touch Python (basic syntax)
I tried to create a sample to access Salesforce using Python and Bottle
I wanted to solve ABC172 with Python
I refactored "I tried to make Othello AI when programming beginners studied python"
How to write offline real time I tried to solve E12 with python
I tried to make a periodical process with CentOS7, Selenium, Python and Chrome
I tried to create a class that can easily serialize Json in Python
I tried using the Python library "pykakasi" that can convert kanji to romaji.