SGU125 Shtirlits

SGU125 Shtirlits

题目大意

有一个N*N的矩阵,每个格子里有一个值
已知对于每个格子,四周有多少个格子的值大于它
构造这个矩阵

算法思路

DFS+剪枝,按照从上到下、从左到右的顺序,枚举每个格子的值后有如下剪枝

  • 判断上方和左边两个格子中大于它的个数,超过则非法,加上右边和下面的不够也非法
  • 对于非第一行,判断上方的格子是否符合,不符合则非法
  • 对于最后一行,判断左边的格子是否符合,不符合则非法

时间复杂度: 稍低于 O(10N×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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值