poj 2111 有序dp走迷宫

#include <iostream>
#include <cstdio>
#include <iomanip>
#include <string>
#include <cstdlib>
#include <cstring>
#include <queue>
#include <set>
#include <vector>
#include <map>
#include <algorithm>
#include <cmath>
#include <stack>

#define INF 0x3f3f3f3f
#define LINF 0x3f3f3f3f3f3f3f3f
#define ll long long
#define ull unsigned long long
#define uint unsigned int

using namespace std;

int dp[411][411];
int mmap[411][411];
int road[411][411];
struct Node {
	int x, y, d;
	bool operator<(const Node &b) const {
		return d > b.d;
	}
}a[411 * 411];

int dx[] = { 2,-2,1,-1,-1,1,-2,2 };
int dy[] = { 1,-1,2,-2,2,-2,1,-1 };
int main() {
	int n;
	while (scanf("%d", &n) != EOF) {
		int cnt = 0;
		for (int i = 0; i < n; i++) 
			for (int j = 0; j < n; j++) {
				scanf("%d", &mmap[i][j]);
				a[cnt].d = mmap[i][j];
				a[cnt].x = i;
				a[cnt++].y = j;
			}
	
		sort(a, a + cnt);
		int x, y,k, f,t,ma,tx, ty,rx, ry,ff = INF,ans = -1;
		memset(dp, 0, sizeof(dp));
		for (int i = 0; i < cnt; i++) {
			x = a[i].x;
			y = a[i].y;
			ma = -1;
			f = INF;
			t = 0;
			for (int j = 0; j < 8; j++) {
				tx = x + dx[j];
				ty = y + dy[j];
				if (tx < 0 || tx >= n || ty < 0 || ty >= n)
					continue;
				if (t < dp[tx][ty] || (t == dp[tx][ty] && mmap[tx][ty] < f)) 
					t = dp[tx][ty], ma = j, f = mmap[tx][ty];
			}
			dp[x][y] = ++t;
			road[x][y] = ma;
			if (dp[x][y] > ans || (dp[x][y] == ans && mmap[x][y] < ff)) 
				ans = dp[x][y], ff = mmap[x][y], rx = x, ry = y;
		}
		printf("%d\n", dp[rx][ry]);
		tx = rx, ty = ry;
		for (int i = 0; i < dp[rx][ry]; i++) {
			printf("%d\n", mmap[tx][ty]);
			k = road[tx][ty];
			tx += dx[k];
			ty += dy[k];
		}
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值