30分求助!
  • 板块P1123 取数游戏
  • 楼主shuhao
  • 当前回复0
  • 已保存回复0
  • 发布时间2024/8/8 16:15
  • 上次更新2024/8/8 17:05:25
查看原帖
30分求助!
1097884
shuhao楼主2024/8/8 16:15

3个TLE

#include <bits/stdc++.h>
using namespace std;

const int N = 6, inf = 0x3f3f3f3f;
int T, n, m, a[N+5][N+5], s, tmp, ans;
bool vis[N+5][N+5];
const int dx[8] = { 0, 0,+1,-1,+1,+1,-1,-1};
const int dy[8] = {+1,-1, 0, 0,+1,-1,+1,-1};

bool dfs(int x, int y) {
	for(int i = 0; i < 8; i++) {
		int cx = x+dx[i], cy = y+dy[i];
		if(cx >= 1 && cx <= n && cy >= 1 && cy <= m)
			if(vis[cx][cy] == true)
				return true;
	}
	s += a[x][y];
	
	tmp = 0;
	for(int i = 1; i <= n; i++)
		for(int j = 1; j <= m; j++) {
			if(vis[i][j] == false) {
				vis[i][j] = true;
				if(dfs(i, j) == true) tmp++;
				vis[i][j] = false;
			} else tmp++;
		}
	if(tmp == n*m) ans = max(ans, s);
	s -= a[x][y];
	return false;
}

int main() {
	cin >> T;
	while(T--) {
		cin >> n >> m;
		for(int i = 1; i <= n; i++)
			for(int j = 1; j <= m; j++)
				cin >> a[i][j];
		memset(vis, false, sizeof(vis)); s = 0; ans = -inf;
		for(int i = 1; i <= n; i++) {
			for(int j = 1; j <= m; j++) {
				if(vis[i][j] == false) {
					vis[i][j] = true;
					dfs(i, j);
					vis[i][j] = false;
				}
			}
		}
		cout << ans << endl;
	}
	
	return 0;
}
2024/8/8 16:15
加载中...