TLE 40 求优化
查看原帖
TLE 40 求优化
482610
Mortidesperatslav楼主2024/6/19 21:46

感觉剪枝写的还算优美了,为什么寄呢。

#include<bits/stdc++.h>
using namespace std;
int a[11][11], ans = -1;
int sc[11][11]
 = {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
 {0, 6, 6, 6, 6, 6, 6, 6, 6, 6}, {0, 6, 7, 7, 7, 7, 7, 7, 7, 6}, {0, 6, 7, 8, 8, 8, 8, 8, 7, 6},
{0, 6, 7, 8, 9, 9, 9, 8, 7, 6}, {0, 6, 7, 8, 9, 10, 9, 8, 7, 6}, {0, 6, 7, 8, 9, 9, 9, 8, 7, 6},
{0, 6, 7, 8, 8, 8, 8, 8, 7, 6}, {0, 6, 7, 7, 7, 7, 7, 7, 7, 6}, {0, 6, 6, 6, 6, 6, 6, 6, 6, 6}};
void print(int s[11][11]){
	for (int i = 1; i <= 9; i++){
		for (int j = 1; j <= 9; j++)
			cout << s[i][j] << " ";
		cout << "\n";
	}
	cout << "\n";
}
bool check(int s[11][11]){
//	print(s);
	for (int i = 1; i <= 9; i++){
		int cnt[11] = {};
		memset(cnt, 0, sizeof cnt);
		for (int j = 1; j <= 9; j++){
	//		cout << i << " " << j << " " << s[i][j] << " " << cnt[s[i][j]] << "\n";
			if (s[i][j])
				cnt[s[i][j]]++;
			if (cnt[s[i][j]] > 1)
				return 0;
		}
	}
	for (int i = 1; i <= 9; i++){
		int cnt[11] = {};
		memset(cnt, 0, sizeof cnt);
		for (int j = 1; j <= 9; j++){
			if (s[j][i])
				cnt[s[j][i]]++;
			if (cnt[s[j][i]] > 1)
				return 0;
		}
	}
	for (int rg = 1; rg <= 3; rg++)
		for (int cg = 1; cg <= 3; cg++){
			int cnt[11] = {};
			memset(cnt, 0, sizeof cnt);
			for (int i = (rg - 1) * 3 + 1; i <= rg * 3; i++)
				for (int j = (cg - 1) * 3 + 1; j <= cg * 3; j++){
					if (s[i][j])
						cnt[s[i][j]]++;
					if (cnt[s[i][j]] > 1)
						return 0;
				}
		}
//	system("pause");
	return 1;
}
void gen(int s[11][11]){
	if (!check(s))
		return;
	int sum = 0;
	for (int i = 1; i <= 9; i++)
		for (int j = 1; j <= 9; j++)
			sum += s[i][j] * sc[i][j];
	ans = max(ans, sum);
}
void dfs(int x, int y, int s[11][11]){
	if (x > 9 || y > 9){
		gen(s);
		return;
	}
	if (!check(s))
		return;
	if (s[x][y]){
		if (y != 9)
			dfs(x, y + 1, s);
		else
			dfs(x + 1, 1, s);
		return;
	}
	if (y != 9){
		for (int i = 1; i <= 9; i++){
			s[x][y] = i;
			dfs(x, y + 1, s);
		}
		s[x][y] = 0;
	}else{
		for (int i = 1; i <= 9; i++){
			s[x][y] = i;
			dfs(x + 1, 1, s);
		}
		s[x][y] = 0;
	}
}
int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);cout.tie(0);
//	print(sc);
	for (int i = 1; i <= 9; i++)
		for (int j = 1; j <= 9; j++)
			cin >> a[i][j];
	dfs(1, 1, a);
	cout << ans;
}
2024/6/19 21:46
加载中...