1970E1. Trails (Easy)
dp,1800, https://codeforces.com/problemset/problem/1970/E1
Harry Potter is hiking in the Alps surrounding Lake Geneva. In this area there are m cabins, numbered 1 to m. Each cabin is connected, with one or more trails, to a central meeting point next to the lake. Each trail is either short or long. Cabin i is connected with
Each day, Harry walks a trail from the cabin where he currently is to Lake Geneva, and then from there he walks a trail to any of the m cabins (including the one he started in). However, as he has to finish the hike in a day, at least one of the two trails has to be short.
How many possible combinations of trails can Harry take if he starts in cabin 1 and walks for n days?
Give the answer modulo
Input
The first line contains the integers m and n.
The second line contains m integers,
The third and last line contains m integers,
We have the following constraints:
0≤
1≤m≤
1≤n≤
Output
The number of possible combinations of trails, modulo 109+7.
Example
Input
3 2
1 0 1
0 1 1Output
18【马铉钦25化院】本题虽然难度标1800,但是是一道比较简单的dp问题。 考虑第n天时如果在第i个盆地,想要走到第j个盆地的方法: 令
使用这个公式进行动态规划即可,实现时可以使用两个一维数组代替二维数组。 算法时间复杂度为
二维数组:
m,n=map(int,input().split())
lis=list(map(int,input().split()))
lil=list(map(int,input().split()))
dp=[[1]+[0]*(m-1) for i in range(n+1)]
r=1000000007
for i in range(1,n+1):
for j in range(m):
c=0
for t in range(m):
c+=(dp[i-1][t]*(lis[t]*(lil[j]+lis[j])+lil[t]*lis[j]))%r
dp[i][j]=c%r
print(sum(dp[n])%r)一维数组:
from copy import copy
m,n=map(int,input().split())
lis=list(map(int,input().split()))
lil=list(map(int,input().split()))
dp=[1]+[0]*(m-1)
dpnew=[0]*m
litr=[[0]*m for i in range(m)]
r=1000000007
for j in range(m):
for t in range(m):
litr[j][t]=lis[t]*(lil[j]+lis[j])+lil[t]*lis[j]
for i in range(1,n+1):
for j in range(m):
c=0
for t in range(m):
c+=(dp[t]*litr[j][t])%r
dpnew[j]=c%r
dp=copy(dpnew)
print(sum(dp)%r)