【USACO2021 Walking Home 】題解


題目

Bessie the cow is trying to walk from her favorite pasture back to her barn.

The pasture and farm are on an N×N
grid (2≤N≤50

), with her pasture in the top-left corner and the barn in the bottom-right corner. Bessie wants to get home as soon as possible, so she will only walk down and to the right. There are haybales in some locations that Bessie cannot walk through; she must walk around them.

Bessie is feeling a little tired today, so she wants to change the direction she walks at most K
times (1≤K≤3

) .

How many distinct paths can Bessie walk from her favorite pasture to the barn? Two paths are distinct if Bessie walks in a square in one path but not in the other

奶牛 Bessie 正准備從她最喜愛的草地回到她的牛棚。

農場位於一個 N×N
的方陣上(2≤N≤50

),其中她的草地在左上角,牛棚在右下角。Bessie 想要盡快回家,所以她只會向下或向右走。有些地方有草堆(haybale),Bessie 無法穿過;她必須繞過它們。

Bessie 今天感到有些疲倦,所以她希望改變她的行走方向至多 K
次(1≤K≤3

)。

Bessie 有多少條不同的從她最愛的草地回到牛棚的路線?如果一條路線中 Bessie 經過了某個方格而另一條路線中沒有,則認為這兩條路線不同。

思路

\(dp(x, y, k, 0/1)\) 代表此時在格子 \((x,y)\),已轉彎 \(k\) 次,現在朝着方向下/右(\(0/1\))的方案數。

然后就可以從左邊和上邊轉移過來,轉移的時候需要考慮是否轉彎。

總結

對於棋盤上年統計方案的題目,如果棋盤不是很大,可以考慮dp,把限制條件寫入轉態即可。

Code

#include<bits/stdc++.h>
using namespace std;
#define int long long
int n, m, i, j, k, t, kx, p; 
int dp[55][55][5][2], ans; 
char s[55][55]; 

signed main()
{
	scanf("%lld", &t); 
	while(t--)
	{
		memset(dp, 0, sizeof(dp)); ans=0; 
		scanf("%lld%lld", &n, &k); 
		for(i=1; i<=n; ++i) scanf("%s", s[i]+1); 
		if(s[1][1]=='H'){ printf("0\n"); continue; }
		dp[1][1][0][0]=dp[1][1][0][1]=1; 
		for(i=1; i<=n; ++i)
			for(j=1; j<=n; ++j)
				if(s[i][j]=='.')
					for(kx=0; kx<=k; ++kx)
					{
						dp[i][j][kx][0]+=dp[i-1][j][kx][0]; 
						if(kx) dp[i][j][kx][0]+=dp[i][j-1][kx-1][1]; 
						dp[i][j][kx][1]+=dp[i][j-1][kx][1]; 
						if(kx) dp[i][j][kx][1]+=dp[i-1][j][kx-1][0]; 
					}
		for(kx=0; kx<=k; ++kx)
			ans+=(dp[n-1][n][kx][0]+dp[n][n-1][kx][1]); 
		printf("%lld\n", ans); 
	}
	return 0;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM