SGU125 Shtirlits
2015-06-04 19:22
281 查看
SGU125 Shtirlits
题目大意
有一个N*N的矩阵,每个格子里有一个值已知对于每个格子,四周有多少个格子的值大于它
构造这个矩阵
算法思路
DFS+剪枝,按照从上到下、从左到右的顺序,枚举每个格子的值后有如下剪枝判断上方和左边两个格子中大于它的个数,超过则非法,加上右边和下面的不够也非法
对于非第一行,判断上方的格子是否符合,不符合则非法
对于最后一行,判断左边的格子是否符合,不符合则非法
时间复杂度: 稍低于O(10N×N)O(10^{N \times N})
代码
/** * Copyright © 2015 Authors. All rights reserved. * * FileName: 125.cpp * Author: Beiyu Li <sysulby@gmail.com> * Date: 2015-06-04 */ #include <bits/stdc++.h> using namespace std; #define rep(i,n) for (int i = 0; i < (n); ++i) #define For(i,s,t) for (int i = (s); i <= (t); ++i) #define foreach(i,c) for (__typeof(c.begin()) i = c.begin(); i != c.end(); ++i) typedef long long LL; typedef pair<int, int> Pii; const int inf = 0x3f3f3f3f; const LL infLL = 0x3f3f3f3f3f3f3f3fLL; const int maxn = 3 + 5; int n; int a[maxn][maxn], b[maxn][maxn]; int dx[] = {-1, 1, 0, 0}, dy[] = {0, 0, -1, 1}; bool inside(int x, int y) { return 0 <= x && x < n && 0 <= y && y < n; } int calc(int x, int y) { int c = 0; rep(i,4) { int nx = x + dx[i], ny = y + dy[i]; if (inside(nx, ny) && a[nx][ny] > a[x][y]) ++c; } return c; } bool dfs(int i, int j) { if (i == n && calc(n - 1, n - 1) == b[n-1][n-1]) return true; for (a[i][j] = 0; a[i][j] < 10; ++a[i][j]) { int c = 0; if (i && a[i-1][j] > a[i][j]) ++c; if (j && a[i][j-1] > a[i][j]) ++c; if (c > b[i][j]) continue; if (c + (i < n - 1? 2: 1) < b[i][j]) return false; if (i) { c = calc(i - 1, j); if (c < b[i-1][j]) continue; if (c > b[i-1][j]) return false; } if (i == n - 1 && j) { c = calc(i, j - 1); if (c < b[i][j-1]) continue; if (c > b[i][j-1]) return false; } if (dfs(i + (j + 1) / n, (j + 1) % n)) return true; } return false; } int main() { scanf("%d", &n); rep(i,n) rep(j,n) scanf("%d", &b[i][j]); bool ok = true; rep(i,n) rep(j,n) { a[i][j] = -1; if (calc(i, j) < b[i][j]) ok = false; a[i][j] = 0; } if (ok && dfs(0, 0)) { rep(i,n) rep(j,n) printf("%d%c", a[i][j], " \n"[j==n-1]); } else { puts("NO SOLUTION"); } return 0; }
相关文章推荐
- Eclipse 4.4.2 取消空格键代码上屏
- php之thinkphp部署Linux
- js去除空格
- 第十二周项目2-教师兼干部类
- 智力题 开灯问题
- arcgis for android apk太大
- 【Linux 工作经常使用命令 】
- Unix传奇
- arcgis for android apk太大
- 第二阶段冲刺第一天
- Ubuntu下用visualBox 安装的XP虚拟机,设置共享文件夹
- Android中Gson解析json
- Javascript模块化编程(三):require.js的用法
- uboot使用之心得体会
- win7下删除ubuntu
- PHP类的继承和接口
- Lua5.2 请求 luasocket 相关模块时的 multiple-lua-vms-detected
- Oracle基础(九):数据备份与恢复、死锁等
- mac 下subline text 3最新版本激活码
- C通过JNI调用JAVA