很容易超时的一道题目。有两种优化方法:奇偶优化或者二分
1:奇偶优化,在填数字的时候,我们不是要枚举吗?可以先看一下它周围的数是奇数还是偶数,如果是奇数我们只需要枚举偶数就行了,如果是偶数我们只需要枚举奇数,因为这样才能保证他们的和是质数,也就是和是奇数。这样循环的代价就减少了一半。
2.二分。在给一个空位填数字的时候,我们先看它周围的数字是x,然后再二分找到第一个比x大的质数y。然后从y开始枚举质数。那么我们可以尝试填的数字就是y - x。
给出第二种的代码:
#include <set>
#include <map>
#include <queue>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#define INF 0x3f3f3f3f
#pragma warning(disable:4996)
#define up(i, low, high) for (int i = low; i < high; i++)
#define down(i, high, low) for (int i = high; i >= low; i--)
using namespace std;
const int maxn = 200;
int answer[15][15][15], n;
int prime[maxn], isprime[maxn], vis[maxn], cnt = 0;
void get_prime ()
{
memset (isprime, 0, sizeof (isprime));
up(i, 2, 200)
{
if (!isprime[i])
{
prime[cnt++] = i;
for (int j = 2 * i; j <= 200; j += i) isprime[j] = 1;
}
}
}
inline bool dfs (int x, int y)
{
if (x > n) return true;
int adjacent;
if (y == 1) adjacent = answer[n][x - 1][y];
else adjacent = answer[n][x][y - 1];
up(i, upper_bound (prime, prime + cnt, adjacent) - prime, cnt)
{
int num = prime[i] - adjacent;
if (num > n * n) break;//剪枝
if (!vis[num])
{
if (x != 1 && isprime[num + answer[n][x - 1][y]]) continue;
if (y != 1 && isprime[num + answer[n][x][y - 1]]) continue;
answer[n][x][y] = num;
vis[num] = 1;
if (y == n)
{
if (dfs (x + 1, 1)) return true;
}
else
{
if (dfs (x, y + 1)) return true;
}
vis[num] = 0;
}
}
return false;
}
int main ()
{
//freopen ("D:\Test_in.txt", "r", stdin);
//freopen ("D:\Test_out.txt", "w", stdout);
get_prime ();
answer[1][1][1] = 1;
for (n = 2; n <= 10; n++)//预处理出所有的答案
{
memset (vis, 0, sizeof (vis));
answer[n][1][1] = 1;//第一位肯定是1,这样直接确定了第一位的数字同样有剪枝的效果
vis[1] = 1;
if (!dfs (1, 2)) answer[n][1][1] = -1;
}
int m;
while (~scanf ("%d", &m))
{
if (answer[m][1][1] == -1) printf ("no answer\n");
else
{
up(i, 1, m + 1)
up(j, 1, m + 1)
printf ("%d%c", answer[m][i][j], j < m ? ' ' : '\n');
}
}
}