例题9-2 巴比伦塔(The Tower of Babylon, UVa 437)

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define SF(a) scanf("%d", &a)
#define PF(a) printf("%d\n", a)  
#define SFF(a, b) scanf("%d%d", &a, &b)  
#define SFFF(a, b, c) scanf("%d%d%d", &a, &b, &c)
#define SFFFF(a, b, c, d) scanf("%d%d%d%d", &a, &b, &c, &d)
#define CLEAR(a, b) memset(a, b, sizeof(a))
#define IN() freopen("in.txt", "r", stdin)
#define OUT() freopen("out.txt", "w", stdout)
#define FOR(i, a, b) for(int i = a; i < b; ++i)
#define LL long long
#define mod 10007
#define inf 100000007
#define eps 1e-12
using namespace std;
int buf[20] ;
int read() {
	int x = 0; char ch = getchar(); bool f = 0;
	while (ch < '0' || ch > '9') { if (ch == '-') f = 1; ch = getchar(); }
	while (ch >= '0' && ch <= '9') x = (x << 1) + (x << 3) + (ch ^ 48), ch = getchar();
	return f ? -x : x;
}
void write(int x) {
	if (!x) { putchar(48); return; }
	int l = 0; if (x < 0) putchar('-'), x = -x;
	while (x) buf[++l] = x % 10, x = x / 10;
	while (l) putchar(buf[l--] + 48);
}
//-------------------------chc------------------------------//
const int maxn = 35;
int n;
int rec[maxn][3], dp[maxn][3];
bool vis[maxn][3];

void get(int x, int y, int &a, int &b) {
	bool flag = true;
	FOR(i, 0, 3) {
		if (i == y) continue;
		if (flag) flag = false, a = rec[x][i];
		else b = rec[x][i];
	}
	if (a < b) swap(a, b);
}

int solve(int x, int y) {
	if (vis[x][y]) return dp[x][y];
	vis[x][y] = true;
	int &ret = dp[x][y];
	ret = rec[x][y];
	int a, b;
	get(x, y, a, b);
	int ans = 0;
	FOR(i, 0, n) {
		FOR(j, 0, 3) {
			int na, nb;
			get(i, j, na, nb);
			if (a > na && b > nb) ans = max(ans, solve(i, j));
		}
	}
	return ret += ans;
}

int main() {
	int kase = 1;
	while (SF(n) && n) {
		CLEAR(vis, 0);
		int ans = 0;
		FOR(i, 0, n) FOR(j, 0, 3) SF(rec[i][j]);
		FOR(i, 0, n) FOR(j, 0, 3) {
			ans = max(ans, solve(i, j));
		}
		printf("Case %d: maximum height = %d\n", kase++, ans);
	}
	return 0;
}

你可能感兴趣的:(紫书,第九章,例题,DAG动态规划)