[PYTHON] AtCoder AGC 041 C --I was addicted to the full search of Domino Quality

Overview

--It took a long time to search for how to place dominoes when N = 7 and Quality = 3. -When implementing a search for $ 2 ^ {49} \ fallingdotseq 10 ^ {15} $, you need to prun the branches well --Python is more than 20 times slower than C ++ in some conditions

When searching for how to put N = 7 and Quality = 3 in python

Place dominoes from (0,0) and try. The order to try

  1. Vertical orientation
  2. Sideways
  3. Do not put

It took ** about 740 [s] ** to find one suitable placement.

findPattern.py


import sys
import numpy as np
import datetime

sys.setrecursionlimit(10 ** 7)


def cntQuality(N, grids, num, axis):
    q = 0

    if axis == 0:
        g = grids[num, :]
    else:
        g = grids[:, num]

    last = -1

    for i in range(N):
        d = g[i]

        if last == d or d == 0:
            continue

        q += 1
        last = d

    return q


def dfs(N, grids, pos, num, q):
    x = pos // N
    y = pos % N


    if y == 0 and x != 0:
        qx = cntQuality(N, grids, x-1, 0)
        if qx != q:
            return False

    # end grids
    if x == N and y == 0:
        # valid
        for i in range(N):
            qy = cntQuality(N, grids, i, 1)
            if qy != q:
                return False
        return grids

    # not yet
    pos += 1

    # put vertical
    if y < N-1 and grids[x][y] == 0 and grids[x][y+1] == 0:
        v_num = num + 1
        # v_grids = copy.copy(grids)
        grids[x][y] = v_num
        grids[x][y+1] = v_num
        g = dfs(N, grids, pos, v_num, q)
        if g is not False:
            return g
        grids[x][y] = 0
        grids[x][y+1] = 0

    # put horizontal
    if x < N-1 and grids[x][y] == 0 and grids[x+1][y] == 0:
        h_num = num + 1
        # h_grids = copy.copy(grids)
        grids[x][y] = h_num
        grids[x+1][y] = h_num
        g = dfs(N, grids, pos, h_num, q)
        if g is not False:
            return g
        grids[x][y] = 0
        grids[x+1][y] = 0

    # dont put domino
    g = dfs(N, grids, pos, num, q)
    if g is not False:
        return g

    return False


start = datetime.datetime.now()
print("start", start)


N = 7
q = 3
grids = np.zeros((N, N))
g = dfs(N, grids, 0, 0, q)
end = datetime.datetime.now()
print("end", end)

print(g)

Execution result.txt


start 2020-01-07 18:13:18.477510
end 2020-01-07 18:22:35.768316
[[  1.   1.   2.   2.   3.   3.   0.]
 [  4.   4.   5.   5.   6.   0.   0.]
 [  7.   7.   0.   0.   6.   8.   8.]
 [  0.   0.   9.  10.   0.   0.  11.]
 [  0.   0.   9.  10.   0.   0.  11.]
 [  0.   0.   0.   0.  12.  13.  14.]
 [  0.   0.   0.   0.  12.  13.  14.]]

Why did it cost 740 [s]?

It seems that the order of searching was bad.

  1. Sideways
  2. Vertical orientation
  3. Do not put

When searching with, the arrangement was found within 1 [s]. Perhaps in this search order, there are matching branches nearby.

I tried some patterns in Python and C ++

Search order Python C++
side->Vertical->None 100[ms] 5[ms]
Vertical->side->None 740[s] 17[s]
None->side->Vertical 430[ms] 10[ms]

Conclusion

――If you can't prun well, there will be a considerable time difference depending on the search order. ――It seems better to use C ++ than Python for this order.

Recommended Posts

AtCoder AGC 041 C --I was addicted to the full search of Domino Quality
[Fixed] I was addicted to alphanumeric judgment of Python strings
I was addicted to multiprocessing + psycopg2
The record I was addicted to when putting MeCab on Heroku
[Introduction to Python] I compared the naming conventions of C # and Python.
I wrote AWS Lambda, and I was a little addicted to the default value of Python arguments
I was addicted to Flask on dotCloud
The file name was bad in Python and I was addicted to import
[Python] I was addicted to not saving internal variables of lambda expressions
What I was addicted to Python autorun
P100-PCIE-16GB was added to the GPU of Google Colab before I knew it
Summary of points I was addicted to running Selenium on AWS Lambda (python)
The inaccuracy of Tensorflow was due to log (0)
[Introduction to json] No, I was addicted to it. .. .. ♬
I tried to touch the API of ebay
I tried to correct the keystone of the image
I want to customize the appearance of zabbix
I tried to predict the price of ETF
I tried to vectorize the lyrics of Hinatazaka46!
linux / c> link> Get the execution result of the shell command in the C program> I was taught how to use popen ()
Note that I was addicted to npm script not passing in the verification environment
AtCoder Beginner Contest 177 Problem C I tried to find out why it was wrong
I want to grep the execution result of strace
I tried to summarize the basic form of GPLVM
I was addicted to scraping with Selenium (+ Python) in 2020
I want to fully understand the basics of Bokeh
The performance of PHP was better than I expected
I tried to visualize the spacha information of VTuber
A story that I was addicted to at np.where
I tried to erase the negative part of Meros
I felt that I ported the Python code to C ++ 98.
I was addicted to trying logging.getLogger in Flask 1.1.x
What I was addicted to when using Python tornado
I tried to classify the voices of voice actors
I want to increase the security of ssh connections
I tried to summarize the string operations of Python
I tried to rewrite the WEB server of the normal Linux programming 1st edition with C ++ 14
I was in charge of maintaining the Fabric script, but I don't know.> <To those who
The story I was addicted to when I specified nil as a function argument in Go
The story of when I was addicted to Caused by SSLError ("Can't connect to HTTPS URL because the SSL module is not available.")
I tried to find the entropy of the image with python
[Horse Racing] I tried to quantify the strength of racehorses
I tried to get the location information of Odakyu Bus
[IOS] GIF animation with Pythonista3. I was addicted to it.
What I did to speed up the string search task
I want to use only the normalization process of SudachiPy
I want to get the operation information of yahoo route
I made a function to check the model of DCGAN
I tried to illustrate the time and time in C language
What I was addicted to when migrating Processing users to Python
[Python] I tried to visualize the follow relationship of Twitter
I want to judge the authenticity of the elements of numpy array
[Machine learning] I tried to summarize the theory of Adaboost
I want to know the features of Python and pip
I tried to fight the Local Minimum of Goldstein-Price Function
Keras I want to get the output of any layer !!
I want to know the legend of the IT technology world
I sent the data of Raspberry Pi to GCP (free)
Note that I was addicted to accessing the DB with Python's mysql.connector using a web application.