Tsinsen A1111 填数字

http://www.tsinsen.com/A1111

分析:瞎搜一波就过了..胆战心惊的。虽然显示的是0ms,但瞎搜老觉得不舒服。对了有个坑爹的地方,讲道理1不是素数,输入1应该输出NO,但答案是1

代码:

#include "bits/stdc++.h"
using namespace std;

bool Prime[205], Used[205], Can;
int n, Maps[15][15], sup;

void Dfs(int Solved, int r, int c) {
    if (Solved >= sup) {
        Can = true;
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < n; ++j) {
                if (j > 0) putchar(' ');
                printf("%d",Maps[i][j]);
            }
            putchar('\n');
        }
        return;
    }
    for (int i = 2; i <= sup; ++i) if (!Used[i] && !Can) {
        if (r > 0 && !Prime[Maps[r - 1][c] + i]) continue;
        if (c > 0 && !Prime[Maps[r][c - 1] + i]) continue;
        Used[i] = true; Maps[r][c] = i;
        if (c + 1 >= n) Dfs(Solved + 1, r + 1, 0);
        else Dfs(Solved + 1, r, c + 1);
        Used[i] = false;
    }
}

int main() {
    for (int i = 2; i < 205; ++i)
        Prime[i] = true;
    for (int i = 2; i < 205; ++i) if (Prime[i])
        for (int k = i + i; k < 205; k += i)
            Prime[k] = false;
    Used[1] = Maps[0][0] = 1;
    scanf("%d", &n); sup = n * n;
    Dfs(1, 0, 1);
    if (!Can) puts("NO");
    return 0;
}

你可能感兴趣的:(ACM-01)