CSP2020-j2 T4 方格取数
题目链接:https://www.luogu.com.cn/problem/P7074
一、dfs(25分)没有任何优化,时间复杂度约(O(3^(n*m)))
1 #include<bits/stdc++.h> 2 using namespace std; 3 int n, m; 4 int a[1005][1005], vis[1005][1005]; 5 int nex[3][2]={{-1,0},{1,0},{0,1}}; 6 int sum; 7 int ans=-0x7fffffff; 8 void dfs(int x, int y){ 9 if(x==1 && y==1){ 10 vis[x][y]=1; 11 sum=a[x][y]; 12 } 13 if(x==n && y==m){ 14 ans=max(ans, sum); 15 return; 16 } 17 for(int i=0; i<3; i++){ 18 int nx=x+nex[i][0], ny=y+nex[i][1]; 19 if(nx<1 || nx>n || ny<1 || ny>m)continue; 20 if(vis[nx][ny])continue; 21 vis[nx][ny]=1; 22 sum+=a[nx][ny]; 23 dfs(nx, ny); 24 sum-=a[nx][ny]; 25 vis[nx][ny]=0; 26 } 27 } 28 int main() 29 { 30 cin>>n>>m; 31 for(int i=1; i<=n; i++) 32 for(int j=1; j<=m; j++) 33 cin>>a[i][j]; 34 dfs(1,1); 35 cout<<ans; 36 return 0; 37 }
同名题:P1004 [NOIP2000 提高组] 方格取数
https://www.luogu.com.cn/problem/P1004
1 #include<bits/stdc++.h> 2 using namespace std; 3 int n, a[15][15]; 4 int f[15][15][15][15]; 5 int dfs(int x1, int y1, int x2, int y2){ 6 if(f[x1][y1][x2][y2]!=-1)return f[x1][y1][x2][y2]; 7 if(x1==n && y1==n && x2==n && y2==n)return 0; 8 int ret=0; 9 if(x1 < n && x2 < n) 10 ret = max(ret, dfs(x1+1, y1, x2+1, y2) + a[x1+1][y1] + a[x2+1][y2] - a[x1+1][y1] * (x1+1 == x2+1 && y1 == y2)); 11 if(x1 < n && y2 < n) 12 ret = max(ret, dfs(x1+1, y1, x2, y2+1) + a[x1+1][y1] + a[x2][y2+1] - a[x1+1][y1] * (x1+1 == x2 && y1 == y2+1)); 13 if(y1 < n && x2 < n) 14 ret = max(ret, dfs(x1, y1+1, x2+1, y2) + a[x1][y1+1] + a[x2+1][y2] - a[x1][y1+1] * (x1 == x2+1 && y1+1 == y2)); 15 if(y1 < n && y2 < n) 16 ret = max(ret, dfs(x1, y1+1, x2, y2+1) + a[x1][y1+1] + a[x2][y2+1] - a[x1][y1+1] * (x1 == x2 && y1+1 == y2+1)); 17 return f[x1][y1][x2][y2]=ret; 18 19 } 20 int main() 21 { 22 scanf("%d", &n); 23 int x, y, z; 24 while(1){ 25 scanf("%d%d%d", &x, &y, &z); 26 if(x==0 && y==0 && z==0)break; 27 a[x][y]=z; 28 } 29 memset(f, -1, sizeof(f)); 30 printf("%d", dfs(1, 1, 1, 1)+ a[1][1]); 31 return 0; 32 }