zoukankan      html  css  js  c++  java
  • 状态压缩动态规划 -- 棋盘问题 POJ 1321


    一个 N * N 的棋盘上面,有些格子不能放,放置 M 的棋子,

    每两个棋子不能在同一行或者同一列,问有多少种放法

    DFS太慢,用SCR好点点

    Python 仅仅有 22 行,事实上能够更短。可是得排成非常长非常长的一行


    while True:
        table = [ [ 0 for j in range( 300 ) ] for i in range( 12 ) ]
        table[0][0] = 1
        boardsize, chessnum = map( int, raw_input().split() ) 
        if boardsize == chessnum == -1: break
        states = range( 1 << boardsize )
        cols = raws = range( 1, boardsize + 1 )
        chessboard = dict( zip( raws, [ ' ' + raw_input() for i in raws ] ) )
        ones = dict( zip( states, map( lambda s: str( bin( s ) ).count( '1' ), states ) ) )
        
        for raw in raws:
            for state in states:
                if ones[state] <= chessnum:
                    table[raw][state] += table[raw - 1][state]
                    for col in cols:
                        s = 1 << ( col - 1 )
                        if chessboard[raw][col] == '#' and state & s == 0:
                            nextstate = state | s
                            table[raw][nextstate] += table[raw - 1][state]
                            
        print sum( [ table[boardsize][state] for state in states if ones[state] == chessnum ] )
    


  • 相关阅读:
    Anniversary party
    1358. 分割树
    我在 impress.js 中学到的小套路
    我对 impress.js 源码的理解
    CSS transition 过渡 详解
    CSS 2D转换 matrix() 详解
    JS 动画基础
    JS 瀑布流布局
    JS 下拉菜单
    JS Resizable Panel 练习
  • 原文地址:https://www.cnblogs.com/lcchuguo/p/5132589.html
Copyright © 2011-2022 走看看