习题9-1 最长的滑雪路径 UVa10285

1.题目描述:点击打开链接

2.解题思路:本题利用DAG上最长路模型解决,将所有符合高度严格减小的相邻点保存,由于最多只有四个,用稀疏图的存储方法即可。

3.代码:

#define _CRT_SECURE_NO_WARNINGS 
#include<iostream>
#include<algorithm>
#include<string>
#include<sstream>
#include<set>
#include<vector>
#include<stack>
#include<map>
#include<queue>
#include<deque>
#include<cstdlib>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<ctime>
#include<functional>
using namespace std;

#define maxn 100+10
#define N 110*110
int d[N];
int h[maxn][maxn];
int G[N][5];
int ans;
string s;
int r, c;
int dx[] = { -1, 1, 0, 0 };
int dy[] = { 0, 0, -1, 1 };
bool inside(int i, int j)
{
	if (i < 0 || i >= r || j < 0 || j >= c)return false;
	return true;
}
int dp(int pos)
{
	int&ans = d[pos];
	if (ans>0)return ans;
	ans = 0;
	for (int i = 1; i <= G[pos][0]; i++)
	{
		int p = G[pos][i];
		ans = max(ans, dp(p) + 1);
	}
	return ans;
}
int main()
{
	//freopen("test.txt", "r", stdin);
	int T;
	cin >> T;
	while (T--)
	{
		cin >> s >> r >> c;
		memset(d, 0, sizeof(d));
		memset(G, 0, sizeof(G));
		for (int i = 0; i < r;i++)
		for (int j = 0; j < c; j++)
		{
			scanf("%d", &h[i][j]);
		}
		for (int i = 0; i < r; i++)
		for (int j = 0; j < c; j++)
		{
			int pos = i*c + j;
			for (int k = 0; k < 4; k++)
			{
				int nx = i + dx[k];
				int ny = j + dy[k];
				if (inside(nx, ny) && h[nx][ny] < h[i][j])
				{
					int p2 = nx*c + ny;
					G[pos][++G[pos][0]] = p2;
				}
			}
		}
		int max_p = r*c;
		ans = -maxn;
		for (int p = 0; p < max_p; p++)
		{
			int tmp = dp(p);
			ans = max(ans, tmp);
		}
		ans++;
		cout << s << ": " << ans << endl;
	}
	return 0;
}

你可能感兴趣的:(动态规划,uva)