/*
沐哲是一个拣货员,有m行n列货架,他从任意一个位置开始捡起
每一次挑选的货物都比上一个货物重量小,每捡的一个货物就会获得
1元钱,那么他最多获得多少钱
*/
#include <iostream>
#include <vector>
#include <ctime>
using namespace std;
int maxPick(vector<vector<int>> goods,int row,int col,int x,int y,vector<vector<int>> mark)
{
int maxp = 0;
static const int dx[] = {0,0,1,-1};
static const int dy[] = {1,-1,0,0};
for(int i = 0; i < 4; i++)
{
int newx = x + dx[i];
int newy = y + dy[i];
if(newx >= 0 && newy >= 0 && newx < row && newy < col && goods[x][y] > goods[newx][newy] && mark[newx][newy] == 0)
{
mark[newx][newy] = 1;//标记
maxp = max(maxp,maxPick(goods,row,col,newx,newy,mark));//深搜
mark[newx][newy] = 0;//取消标记
}
}
return maxp + 1;
}
/*
我们发现,每个点在进行深度优先搜索时,会遇到和其他点相同的路径,所以存在优化的空间。
如果当前节点在之前已经搜索过了,这时候就需要判断需不需要继续搜索。两种情况
1、当前计算最大步数值大于之前遍历到该点的最大步数值,说明当前路径要比之前的路径更优,需要更新。
2、反之,不再搜索当前路径。
举个例子: 如data的第一个元素的最大路径为:32-13-12-3,最大步数为4;
当对第二个元素遍历时,假设按照上下左右的顺序,向下34-12-3为一条路径,
此时第二元素的最大步数为3,向左34-32-13-12-3是个可行路径,而32-13-12-3之前已经搜索过,
可以利用之前的32的最大步数值,直接比较4+1 和 3,更新第二元素的最大步数为5.
注意: 要实现这一操作,需要在遍历的过程中使用一个res来存储已遍历节点的最大步数值。
*/
//优化
void maxPick2(vector<vector<int>> goods,int row,int col,vector<vector<int>>& res2,int x,int y)
{
static const int dx[] = {0,0,1,-1};
static const int dy[] = {1,-1,0,0};
for(int i = 0;i < 4;i++)
{
int newx = x + dx[i];
int newy = y + dy[i];
if(newx >= 0 && newy >= 0 && newx < row && newy < col && goods[newx][newy] > goods[x][y])
{
if(res2[x][y] + 1 > res2[newx][newy])
{
res2[newx][newy] = res2[x][y] + 1;//更新
maxPick2(goods,row,col,res2,newx,newy);//深搜
}
}
}
}
int main()
{
int row,col,item;
while(cin >> row >> col)
{
vector<vector<int>> goods(row,vector<int> (col,0));
for(int i = 0; i < row; i++)
{
for(int j = 0; j < col; j++)
{
cin >> item;
goods[i][j] = item;
}
}
vector<vector<int>> res(row,vector<int> (col,0));
vector<vector<int>> mark(row,vector<int> (col,0));
int start = clock();
for(int i = 0; i < row; i++)
{
for(int j = 0; j < col; j++)
{
mark[i][j] = 1;
res[i][j] = maxPick(goods,row,col,i,j,mark);
mark[i][j] = 0;
}
}
for(int i = 0; i < row; i++)
{
for(int j = 0; j < col - 1; j++)
{
cout << res[i][j] << " ";
}
cout << res[i][col - 1] << endl;
}
int end = clock();
double dur = (double)(end - start) / CLOCKS_PER_SEC;
cout << "用时" << dur <<"秒" << endl;
vector<vector<int>> res2(row,vector<int> (col,1));
int start2 = clock();
for(int i = 0; i < row; i++)
{
for(int j = 0; j < col; j++)
{
maxPick2(goods,row,col,res2,i,j);
}
}
for(int i = 0; i < row; i++)
{
for(int j = 0; j < col - 1; j++)
{
cout << res2[i][j] << " ";
}
cout << res2[i][col - 1] << endl;
}
int end2 = clock();
double dur2 = (double)(end2 - start2) / CLOCKS_PER_SEC;
cout << "用时" << dur2 <<"秒" << endl;
}
}
// //test
// 输入行、列、具体值
/*6 6
32 34 7 33 21 2
13 12 3 11 26 36
16 30 22 1 24 14
20 23 25 5 19 29
27 15 9 17 31 4
6 18 8 10 35 28 */
// }
//}
拣货员问题(动态规划C++)
最新推荐文章于 2021-06-17 19:47:33 发布