您的位置:首页 > 其它

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: