Educational DP Contest
Educational DP Contest - AtCoder
AtCoder is a programming contest site for anyone from beginners to experts. We hold weekly programming contests online.
問題
H - Grid 1
AtCoder is a programming contest site for anyone from beginners to experts. We hold weekly programming contests online.
方針
単純な漸化式で良い。\(H\times W\)のDPを作り、マスが”#”のときは\(dp[i+1][j+1] = 0\)として、マスが”.”のときは\(dp[i+1][j+1] = dp[i+1][j] + dp[i][j+1]\)とする。\(10^{9}+7\)で割るのを忘れないようにする。
解答
def main():
import sys
input = sys.stdin.readline
#文字列入力の時は上記はerrorとなる。
#ここにコード
#input
h, w = map(int, input().split())
a = ["" * w for _ in range(h)]
for i in range(h):
a[i] = list(map(str, input().split()))
#output
mod = pow(10, 9) + 7
dp = [[0]*w for _ in range(h)]
dp[0][0] = 1
for j in range(w):
if a[0][0][j] == ".":
dp[0][j] = 1
else:
break
for i in range(h):
if a[i][0][0] == ".":
dp[i][0] = 1
else:
break
for i in range(h-1):
for j in range(w-1):
if a[i+1][0][j+1] == "#":
dp[i+1][j+1] = 0
else:
dp[i+1][j+1] = dp[i+1][j] % mod + dp[i][j+1] % mod
print(dp[h-1][w-1] % mod)
#N = 1のときなどcorner caseを確認!
if __name__ == "__main__":
main()
提出結果
これはPython3で通らないことはないが、PyPy3の方が早い。https://atcoder.jp/contests/dp/submissions/31992295
感想
DPというよりは漸化式というか。
関連問題
A-Frog 1
B-Frog 2
C-Vacation
D-Knapsack 1
E-Knapsack 2
F-LCS
G-Longest Path
関連リンク
AtCoder
AtCoder is a programming contest site for anyone from beginners to experts. We hold weekly programming contests online.
コメント