生活随笔
收集整理的這篇文章主要介紹了
牛客 - 降维打击(dp)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接:點擊查看
題目大意:給出一個 n * m 的迷宮,0 表示道路,1表示障礙物,初始時在點 ( x , y ) 到達邊界即逃離迷宮,問在時間 k 內逃離迷宮的概率有多大
題目分析:因為涉及到概率問題,不難看出可以用分層圖 bfs 求出 ans1 代表可行方案數,ans2 代表不可行方案數,那么答案就是 ans1 / ans2 了,但如果直接實現的話,會 MLE ,這個題專門卡了分層 bfs ,一共有 128 * 128 * 256 個狀態,因為分層 bfs 每次只能轉移一個狀態,所以同時會存在 128 * 128 * 256 * 4 個狀態,計算之后會發現爆內存了
所以需要將分層 bfs 轉換為分層 dp ,dp[ t ][ x ][ y ] 代表時間為 t 時,到達點 ( x , y ) 的概率,最后的答案顯然就是周圍一圈的邊界的答案之和了
其實還可以優化,這里提一下,不難發現?dp[ t ][ x ][ y ] 的轉移只與相鄰兩維有關,所以可以將時間那一維滾動起來,這樣空間上就能再優化掉一維了,但在這個題目中沒有必要,顯然三維dp寫起來更加直觀
代碼:
?
#include<iostream>
#include<cstdio>
#include<string>
#include<ctime>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<stack>
#include<climits>
#include<queue>
#include<map>
#include<set>
#include<sstream>
#include<cassert>
#include<unordered_map>
using namespace std;typedef long long LL;typedef unsigned long long ull;const int inf=0x3f3f3f3f;const int N=130;const int mod=1e9+7;const int b[4][2]={0,1,0,-1,1,0,-1,0};LL q_pow(LL a,LL b)
{LL ans=1;while(b){if(b&1)ans=ans*a%mod;a=a*a%mod;b>>=1;}return ans;
}int inv_4=q_pow(4,mod-2);bool maze[N][N];LL dp[N<<1][N][N];int main()
{
#ifndef ONLINE_JUDGE
// freopen("input.txt","r",stdin);
// freopen("output.txt","w",stdout);
#endif
// ios::sync_with_stdio(false);int n,m,x,y,k;scanf("%d%d%d%d%d",&n,&m,&x,&y,&k);for(int i=1;i<=n;i++)for(int j=1;j<=m;j++)scanf("%d",&maze[i][j]);dp[0][x][y]=1;for(int t=0;t<k;t++)for(int i=1;i<=n;i++)for(int j=1;j<=m;j++){int x=i,y=j;if(dp[t][x][y]==0)continue;for(int kk=0;kk<4;kk++){int xx=x+b[kk][0];int yy=y+b[kk][1];if(!maze[xx][yy])dp[t+1][xx][yy]=(dp[t+1][xx][yy]+dp[t][x][y]*inv_4)%mod;}}LL ans=0;for(int t=1;t<=k;t++){for(int x=1;x<=n;x++){ans=(ans+dp[t][x][0])%mod;ans=(ans+dp[t][x][m+1])%mod;}for(int y=1;y<=m;y++){ans=(ans+dp[t][0][y])%mod;ans=(ans+dp[t][n+1][y])%mod;}}printf("%lld\n",ans);return 0;
}
?
總結
以上是生活随笔為你收集整理的牛客 - 降维打击(dp)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。