这是90分TLE代码
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 10;
int score[10][10] = {
{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}
};
int a[N][N];
bool row[N][N], col[N][N], blo[N][N];
int ans = 0;
struct st {
int a, x, y;
} arr[90];
int cnt = 0;
bool cmp(st x, st y) {
return x.a < y.a;
}
inline int find(int x, int y) {
return (x - 1) / 3 * 3 + (y + 2) / 3;
}
void dfs(int id, int s) {
if(id > cnt) {
ans = max(ans, s);
return;
}
int x = arr[id].x, y = arr[id].y, z = find(x, y);
for(int i = 1; i <= 9; i++) {
if(row[x][i] || col[y][i] || blo[z][i]) continue;
row[x][i] = col[y][i] = blo[z][i] = 1;
dfs(id + 1, s + score[x][y] * i);
row[x][i] = col[y][i] = blo[z][i] = 0;
}
return;
}
int main() {
int num = 0;
for(int i = 1; i < 10; i++) {
for(int j = 1; j < 10; j++) {
int x;
cin >> x;
a[i][j] = x;
row[i][x] = col[j][x] = blo[find(i, j)][x] = 1;
num += x * score[i][j];
}
}
for(int i = 1; i <= 9; i++) {
for(int j = 1; j <= 9; j++) {
if(a[i][j] != 0) continue;
int aa = 0;
for(int k = 1; k <= 9; k++) {
// if(!row[i][k] && !col[j][k] && !blo[find(i, j)][k]) aa++;
if(!row[i][k]) aa++;
}
arr[++cnt] = {aa, i, j};
}
}
sort(arr + 1, arr + cnt + 1, cmp);
dfs(1, num);
if(!ans) ans = -1;
cout << ans << endl;
return 0;
}
其中的sort代码(arr用于记录所有待决策的点)
sort(arr + 1, arr + cnt + 1, cmp);
改为
stable_sort(arr + 1, arr + cnt + 1, cmp);
后,
90 -> 100
3.24s -> 1.26s
?
附记录