#if 1
#include<stdio.h>
#define SIZE (101)
#define DEBUG (1)
int arr[SIZE];
bool flag[SIZE];
bool isOver;
int count;
bool isPrime(int num)
{
bool ret = true;
for(int i = 2; i <= num/2; i++)
{
if(num % i == 0)
{
ret = false;
break;
}
}
return ret;
}
bool isSumPrime(int N,int pos)
{
bool ret = false;
if(pos == 0)
{
ret = true;
}
else if((pos - N) < 0)
{
ret = flag[arr[pos] + arr[pos - 1]];
}
else if((pos - N) >= 0)
{
if(pos % N == 0)
{
ret = flag[arr[pos] + arr[pos-N]];
}
else
{
ret = (flag[arr[pos] + arr[pos-N]] && flag[arr[pos] + arr[pos-1]]);
}
}
return ret;
}
void DFS(int N, int index, bool vis[])
{
if(isOver == true)
{
return;
}
if(index == N*N)
{
isOver = true;
printf("#%d\n", count);
for(int i = 0; i < N; i++)
{
for(int j = 0; j < N; j++)
{
printf("%d ", arr[i * N + j]);
}
printf("\n");
}
return;
}
for(int i = 2; i <= N*N; i++)
{
if(!vis[i])
{
vis[i] = 1;
arr[index] = i;
if(isSumPrime(N, index))
{
DFS(N, index + 1, vis);
}
vis[i] = 0;
arr[index] = 0;
}
}
}
int main()
{
flag[1] = 0;
count = 0;
for(int i = 2; i < SIZE; i++)
{
flag[i] = isPrime(i);
}
for(;;)
{
bool vis[SIZE] = {0};
int N;
isOver = false;
arr[0] = 1;
scanf("%d", &N);
if(N == 0)
{
break;
}
count++;
DFS(N, 1, vis);
if(isOver == false)
{
printf("#%d\n", count);
printf("No Solution!\n");
}
}
while(1);
return 0;
}
#endif
/
参考
/
#if 0
#include<stdio.h>
#include<stdlib.h>
int a[110];
int v[110];
int OK;
int SU[220];
void output_result(int n)
{
int i;
for(i=1;i<=n*n;i++)
{
printf("%d",a[i]);
if(i%n==0)
printf("\n");
else
printf(" ");
}
OK=1;
return;
}
int is_susu(int n)
{
return SU[n];
}
int is_ok(int i,int j,int n)
{
if(v[j]==1)return 0;
if(i-1>0&&((i%n)!=1)&&!is_susu(j+a[i-1]))return 0;
if(i-n>0&&!is_susu(j+a[i-n]))return 0;
return 1;
}
void DFS(int i,int n)
{
int j;
if(i>n*n)
{
OK = 1;
output_result(n);
return;
}
for(j=1;j<=n*n&&OK==0;j++)
{
if(is_ok(i,j,n))
{
a[i] = j;
v[a[i]] = 1;
DFS(i+1,n);
v[a[i]] = 0;
}
}
}
void test_main(int n)
{
int i;
int level;
for(i=1;i<=n*n;i++)
{
a[i]=1;
v[i]=0;
}
level=1;
OK=0;
DFS(1,n);
if(OK==0)
printf("No solution\n");
return;
}
int main()
{
int n;
int i,j,k;
i = 1;
SU[2] = 1;
SU[3] = 1;
SU[4] = 0;
for(j=5;j<=220;j++)
{
for(k=2;k<j/2;k++)
if(j%k==0){
SU[j]=0;
break;
}
if(k==j/2)SU[j]=1;
}
scanf("%d",&n);
while(n!=0)
{
printf("#%d\n",i++);
test_main(n);
scanf("%d",&n);
}
return 0;
}
#endif
1017
最新推荐文章于 2021-03-08 20:08:07 发布