NOIP2009 靶型数独
这道题比我想象之中要暴力一些。
自己一开始有一份写9*9数独的代码,自己试了一下直接交上去只有40分。看来这样是肯定不行的。考虑优化,想在中间贪贪心啥的,但是难以保证正确性。最后学了一招,从数字比较多的行开始搜索,这样会使搜索树变得小一些,时间就会减少一些。
然后交上去之后还是只有75分……发现自己数独判断合法的老代码效率太低了,改了一下之后终于成功的过了。
这个题其实虽然有些剪枝但是还是好暴力……
看一下代码。
// luogu-judger-enable-o2 #include<cstdio> #include<algorithm> #include<cstring> #include<iostream> #include<cmath> #include<ctime> #define rep(i,a,n) for(int i = a;i <= n;i++) #define per(i,n,a) for(int i = n;i >= a;i--) #define enter putchar('\n') using namespace std; typedef long long ll; const int M = 1005; int read() { int ans = 0,op = 1; char ch = getchar(); while(ch < '0' || ch > '9') { if(ch == '-') op = -1; ch = getchar(); } while(ch >= '0' && ch <= '9') { ans *= 10; ans += ch - '0'; ch = getchar(); } return ans * op; } bool pd[15][15],flag; int num[15][15],visg[11][11],vish[11][11],visl[11][11]; int curx[15] = {0,1,1,1,4,4,4,7,7,7}; int cury[15] = {0,1,1,1,4,4,4,7,7,7}; int sco[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} }; struct line { int sum,id,loc; bool operator < (const line &g) const { return sum < g.sum; } }a[11]; int m,n,tot,px,py,maxn = -1; bool find(int kx) { rep(i,a[kx].loc,9) { rep(j,1,9) { if(!num[a[i].id][j]) { px = a[i].id,py = j; return 1; } } } return 0; } void write() { rep(i,1,9) { rep(j,1,9) printf("%d ",num[i][j]);enter; } } void calc() { int cur = 0; rep(i,1,9) rep(j,1,9) cur += num[i][j] * sco[i][j]; maxn = max(maxn,cur); } void dfs(int dx,int dy) { int g = (dx - 1) / 3 * 3 + (dy - 1) / 3; rep(k,1,9) { if(vish[dx][k] || visl[dy][k] || visg[g][k]) continue; vish[dx][k] = visl[dy][k] = visg[g][k] = 1,num[dx][dy] = k; if(find(dx)) dfs(px,py); else calc();//write(); vish[dx][k] = visl[dy][k] = visg[g][k] = 0,num[dx][dy] = 0; } } int main() { clock_t start,end; start = clock(); rep(i,1,9) { a[i].id = i; rep(j,1,9) { int g = (i - 1) / 3 * 3 + (j - 1) / 3; num[i][j] = read(); if(!num[i][j]) a[i].sum++; else vish[i][num[i][j]] = visl[j][num[i][j]] = 1,visg[g][num[i][j]] = 1; } } sort(a+1,a+10); rep(i,1,9) a[a[i].id].loc = i; if(find(a[1].id)) dfs(px,py); printf("%d\n",maxn); end = clock(); double seconds = (double)(end - start) / CLOCKS_PER_SEC; //printf("%.8lf\n",seconds); return 0; }
当你意识到,每个上一秒都成为永恒。