hugo

 avatar
quoc14
c_cpp
5 months ago
3.1 kB
1
Indexable
caidat
#include <iostream>

using namespace std;
int oo = 1000000;
int n, m, sr, sc;
int k, x, y;
int a[100][100];

int dx[4] = {1, -1, 0, 0};
int dy[4] = {0, 0, 1, - 1};
int queueX[1000000], queueY[1000000];
int start, last;
int lua[100][100];
int ans = -1;

int visit[100][100];
int cong[100][100];
int ho[100][100];

void reset() {
	for (int i = 0; i < 20; i++) {
		for (int j = 0; j < 20; j++) {
			lua[i][j] = oo;
			cong[i][j] = 0;
			ho[i][j] = 0;
			visit[i][j] = 0;

		}
	}
}

void bfs() {
	while (start != last) {
		int x_cur = queueX[start];
		int y_cur = queueY[start++];
		for (int i = 0; i < 4; i++) {
			int x_next = x_cur + dx[i];
			int y_next = y_cur + dy[i];
			if (x_next >= 1 && x_next <= n && y_next >= 1 && y_next <= m) {
				if (ho[x_next][y_next] == 1) {
					lua[x_next][y_next] = oo;
				}
				else {
					if (lua[x_next][y_next] == oo || lua[x_next][y_next] > lua[x_cur][y_cur] + 1) {
						lua[x_next][y_next] = lua[x_cur][y_cur] + 1;
						queueX[last] = x_next;
						queueY[last++] = y_next;
					}
				}
			}
		}
	}
}

void backtrack(int x, int y, int time, int total) {
	
	if (cong[x][y] == 1) {
		if (total > ans) ans = total;
	}

	for (int i = 0; i < 4; i++) {
		int x_next = x + dx[i];
		int y_next = y + dy[i];
		if (x_next >= 1 && x_next <= n && y_next >= 1 && y_next <= m) {
			if (lua[x_next][y_next] > time + 1 && visit[x_next][y_next] == 0) {
				//cout << x_next << " " << y_next << endl;
				visit[x_next][y_next] = 1;
				if (ho[x_next][y_next] == 1) {
					backtrack(x_next, y_next, time + 2, total + a[x_next][y_next]);
				}
				else {
					backtrack(x_next, y_next, time + 1, total + a[x_next][y_next]);
				}
				visit[x_next][y_next] = 0;
			}
		}
	}

}

void solve(int testcase) {
	start = 0;
	last = 0;
	reset();
	ans = -1;
	cin >> n >> m >> sr >> sc;
	
	for (int i = 1; i <= 3; i++) {
		cin >> k;
		for (int j = 1; j <= k; j++) {
			cin >> x >> y;
			if (i == 1) {
				queueX[last] = x;
				queueY[last++] = y;
				lua[x][y] = 1;
			}
			else if (i == 2) {
				ho[x][y] = 1;
			}
			else if (i == 3) {
				cong[x][y] = 1;
			}
		}
	}

	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= m; j++) {
			cin >> a[i][j];
		}
	}

	
	bfs();
	/*
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= m; j++) {
			cout << lua[i][j] << " ";
		}
		cout << endl;
	}
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= m; j++) {
			cout << ho[i][j] << " ";
		}
		cout << endl;
	}
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= m; j++) {
			cout << cong[i][j] << " ";
		}
		cout << endl;
	}
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= m; j++) {
			cout << a[i][j] << " ";
		}
		cout << endl;
	}
	*/
	visit[sr][sc] = 1;
	backtrack(sr, sc, 1, a[sr][sc]);

	cout << "Case #" << testcase << endl;
	cout << ans << endl;

}

int main() {
	freopen("Text.txt", "r", stdin);
	int t; cin >> t;

	for (int i = 1; i <= t; i++) {
		solve(i);
	}
	return 0;
}
Leave a Comment