Ant book in python: Sec. 2-5 Graph

page93: Bipartite graph judgment


from Graph import join_dic  #See the preparation article for the contents
from Graph import d_to_ud  #See the preparation article for the contents

#############Make a directed graph###########
N = int(input())
graph = {}
while 1:
    edge = input()
    if edge == "":
        break

    edge = list(map(int, edge.split()))
    dic = {edge[0]: edge[1]}
    graph = join_dic(graph, dic)
##########################################

graph = d_to_ud(graph)   ###I want to process it recursively, so make it an undirected graph

for i in graph:
    if isinstance(graph[i], list):
        continue
    else:
        graph[i] = [graph[i]]   #### for i in graph[hoge]So that the processing can be unified with, 

#Postscript) if not isinstance(graph[i],list)I should have done it.

color = (N) * [0]

def coloring(start, col):  ##Can you paint the connected component to which node start belongs?

    color[start] = col

    for i in graph[start]:
        if color[i] == col:  ##Out if adjacent sites are the same color
            return False
        if color[i] == 0 and (not coloring(i, -col)):  ##If the adjacent site is colorless, start painting from there with the opposite color to start
            return False

    return True


def solve():
    for i in graph:
        if color[i] == 0:
            if not coloring(i, 1):    ##Can you start from i and apply the connecting component?
                print("No")
                return 0

    print("Yes")
    return 0


solve()


input:

4  
0 1
1 2
2 3
0 3

output:

Yes

input:

3
0 1
1 2
2 0

output:

No

Since the graph is not always concatenated, we need to look at all nodes.

page95: Bellman-Ford method

input:


3

0 1 1
1 2 1
0 2 3

0

2

output:


2


import mygraph

print("number of nodes")
N = int(input())

print("input graph")
graph = mygraph.WeightedGraph()

while 1:

    inputline = input()

    if inputline == "":
        break

    inputline = list(map(int, inputline.split()))

    graph.join(inputline[0], inputline[1], inputline[2])

graph = graph.undirected()


for node in graph:
    if not isinstance(graph[node][0], list):
        graph[node] = [graph[node]]

print("Start?")
startpos = int(input())
print("Goal?")
goalpos = int(input())


dp = N * [float("INF")]


while 1:

    update = False

    dp[startpos] = 0

    for from_node in graph:

        neighbors = graph[from_node]

        for [to_node, weight] in neighbors:

            if dp[from_node] != float("INF") and dp[to_node] > dp[from_node] + weight:

                dp[to_node] = dp[from_node] + weight

                update = True

    if not update:
        break

print(dp[goalpos])

mygraph.py is a classized version written by @sishiracamus in the comments of the preparation article.

Recommended Posts

Ant book in python: Sec. 2-5 Graph
Ant book in python: Sec. 2-5 Graph (preparation)
Ant book in python: Sec. 2-4, data structures
Ant book in python: Sec.2-5 Dijkstra's algorithm
Ant book in python: Sec. 2-3, Dynamic Programming (DP)
Ant book in python: Priority queue self-implementation
Ant book in python: page 43 Interval scheduling
Ant book in python: page 49 Fence Repair
Draw graph in python
Ant book in python: page 47 Saruman's Army (POJ 3069)
Spiral book in Python! Python with a spiral book! (Chapter 14 ~)
Ant book with python (chapter3 intermediate edition ~)
Easily graph data in shell and Python
Quadtree in Python --2
Python in optimization
CURL in python
Metaprogramming in Python
Python 3.3 in Anaconda
Geocoding in python
SendKeys in Python
Meta-analysis in Python
Unittest in python
Epoch in Python
Discord in Python
Sudoku in Python
DCI in Python
quicksort in python
N-Gram in Python
Programming in python
Plink in Python
Constant in python
Lifegame in Python.
FizzBuzz in Python
Sqlite in python
StepAIC in Python
LINE-Bot [0] in Python
Csv in python
Disassemble in Python
Reflection in Python
nCr in Python.
format in python
Scons in Python3
Puyo Puyo in python
python in virtualenv
PPAP in Python
Quad-tree in Python
Reflection in Python
Chemistry in Python
Hashable in python
DirectLiNGAM in Python
LiNGAM in Python
Flatten in python
flatten in python
Draw a graph of a quadratic function in Python
Create a standard normal distribution graph in Python
From file to graph drawing in Python. Elementary elementary
Solve "AtCoder version! Ant book (beginner)" with Python!
Sorted list in Python
Daily AtCoder # 36 in Python
Clustering text in Python
Daily AtCoder # 2 in Python