资源限制
时间限制:1.0s 内存限制:256.0MB
问题描述
刷微博,编程序。如下图所示,@北京发布 提出了如下“头脑震荡”问题。对此问题做一般化描述:
有n阶方阵,从矩阵的左下角元素为起点,从行或列(水平或垂直)两个方向上移动,直到右上角。求出有多少条路径可以使得经过的元素累加值最大,最大值是多少。
输入格式
共有n+1行。
第一行整数n,表示矩阵的阶数,2<=n<=10。
第二行起,每行n个整数,以空格分隔,共n行。。
输出格式
一行,两个空格分隔的数,第一个表示最大值路径的条数,第二个表示最大值。
样例输入
5
4 5 4 5 6
2 6 5 4 6
2 6 6 5 2
4 5 2 2 5
5 2 5 6 4
样例输出
3 47
思路
两边dfs,第一遍找出最大值,第二遍记录此最大值出现次数,因为深搜的本质是一种暴力枚举,所以每次找到最大值的路径都是不一样的。
Code
#define _CRT_SECURE_NO_WARNINGS
#include<bits/stdc++.h>
using namespace std;
const int N = 1e8;
int n,cnt,maxt;
int a[15][15];
int wk[2][2] = { {-1,0},{0,1} };//向上和向右
int vis[15][15];
void dfs(int x, int y, int now) {
if (x == 1 && y == n) {
maxt = max(now, maxt);
return;
}
for (int i = 0; i < 2; i++) {
int tx = x + wk[i][0], ty = y + wk[i][1];
if (vis[tx][ty] || tx<1 || tx>n || ty<1 || ty>n)continue;
vis[tx][ty] = 1;
dfs(tx, ty, now + a[tx][ty]);
vis[tx][ty] = 0;
}
return;
}
void dfs1(int x, int y, int now) {
if (x == 1 && y == n) {
if (now == maxt)
++cnt;
return;
}
for (int i = 0; i < 2; i++) {
int tx = x + wk[i][0], ty = y + wk[i][1];
if (vis[tx][ty] || tx<1 || tx>n || ty<1 || ty>n)continue;
vis[tx][ty] = 1;
dfs1(tx, ty, now + a[tx][ty]);
vis[tx][ty] = 0;
}
return;
}
int main(){
scanf("%d", &n);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
scanf("%d", a[i] + j);
dfs(n,1,a[n][1]);
dfs1(n, 1, a[n][1]);
printf("%d %d", cnt,maxt);//最后出现的maxt是最大的
return 0;
}