FatMouse and Cheese HDU - 1078(记忆化搜索入门模板)
題意:
n * n的正方形格子(每個(gè)格子均放了奶酪),老鼠從(0,0)開(kāi)始,每次最多移動(dòng)k步,可以選擇上下左右四個(gè)方向移動(dòng),下一個(gè)移動(dòng)點(diǎn)奶酪塊數(shù)量必須要大于當(dāng)前點(diǎn)。
整理模板ing…
題目:
FatMouse has stored some cheese in a city. The city can be considered as a square grid of dimension n: each grid location is labelled (p,q) where 0 <= p < n and 0 <= q < n. At each grid location Fatmouse has hid between 0 and 100 blocks of cheese in a hole. Now he’s going to enjoy his favorite food.
FatMouse begins by standing at location (0,0). He eats up the cheese where he stands and then runs either horizontally or vertically to another location. The problem is that there is a super Cat named Top Killer sitting near his hole, so each time he can run at most k locations to get into the hole before being caught by Top Killer. What is worse – after eating up the cheese at one location, FatMouse gets fatter. So in order to gain enough energy for his next run, he has to run to a location which have more blocks of cheese than those that were at the current hole.
Given n, k, and the number of blocks of cheese at each grid location, compute the maximum amount of cheese FatMouse can eat before being unable to move.
Input
There are several test cases. Each test case consists of
a line containing two integers between 1 and 100: n and k
n lines, each with n numbers: the first line contains the number of blocks of cheese at locations (0,0) (0,1) … (0,n-1); the next line contains the number of blocks of cheese at locations (1,0), (1,1), … (1,n-1), and so on.
The input ends with a pair of -1’s.
Output
For each test case output in a line the single integer giving the number of blocks of cheese collected.
Sample Input
3 1
1 2 5
10 11 6
12 12 7
-1 -1
Sample Output
37
分析:
記憶化搜索入門(mén),當(dāng)采用記憶化搜索時(shí),不必事先確定各狀態(tài)的計(jì)算順序,但需要記錄每個(gè)狀態(tài)“是否已經(jīng)計(jì)算過(guò)”。
總結(jié)一下記憶化搜索是啥:
1.不依賴任何 外部變量(調(diào)用函數(shù)內(nèi)的變量也沒(méi)有變化)
2.答案以返回值的形式存在, 而不能以參數(shù)的形式存在(就是不能將 dfs 定義成 dfs(pos ,tleft , nowans ) , 這里面的 nowans 不符合要求).
3.對(duì)于相同一組參數(shù), dfs 返回值總是相同的(參見(jiàn)第一條)
就這道題復(fù)雜度為:O(n2n^{2}n2):每個(gè)點(diǎn)只遍歷了一次,從O(2n2^{n}2n)~O(n2n^{2}n2)這是記憶化搜索算法在時(shí)間復(fù)雜度上的優(yōu)越性
AC代碼
#include<stdio.h> #include<string.h> #include<algorithm> using namespace std; int n,m; int dp[110][110],a[110][110]; int c[4][2]= {0,1,0,-1,1,0,-1,0}; int dfs(int u,int v) {if(dp[u][v]!=-1)return dp[u][v];dp[u][v]=a[u][v];for(int i=0; i<4; i++)for(int j=1; j<=m; j++){int x=u+c[i][0]*j;int y=v+c[i][1]*j;if(x<0||y<0||x>=n||y>=n||a[u][v]>=a[x][y])continue;dp[u][v]=max(dp[u][v],dfs(x,y)+a[u][v]);}return dp[u][v]; } int main() {while(~scanf("%d%d",&n,&m)){if(n==-1&&m==-1)break;for(int i=0; i<n; i++)for(int j=0; j<n; j++)scanf("%d",&a[i][j]);memset(dp,-1,sizeof(dp));printf("%d\n",dfs(0,0));}return 0; }總結(jié)
以上是生活随笔為你收集整理的FatMouse and Cheese HDU - 1078(记忆化搜索入门模板)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 自媒体账号个人和企业的注册步骤个人如何注
- 下一篇: 内存频率不达标的一种解决办法内存频率达不