Problem Description
A ring is compose of n circles as shown in diagram. Put natural number 1, 2, ..., n into each circle separately, and the sum of numbers in two adjacent circles should be a prime.
Note: the number of first circle should always be 1.
Note: the number of first circle should always be 1.
Input
n (0 < n < 20).
Output
The output format is shown as sample below. Each row represents a series of circle numbers in the ring beginning from 1 clockwisely and anticlockwisely. The order of numbers must satisfy the above requirements. Print solutions in lexicographical order.
You are to write a program that completes above process.
Print a blank line after each case.
You are to write a program that completes above process.
Print a blank line after each case.
Sample Input
68
Sample Output
Case 1:1 4 3 2 5 61 6 5 2 3 4Case 2:1 2 3 8 5 6 7 41 2 5 8 3 4 7 61 4 7 6 5 8 3 21 6 7 4 3 8 5 2
这道题一直找不到错误,因为刚开始把i,k定义全局变量了,而且没把vector容器清空
刚开始还纠结于在主函数的for循环中 要不要每次都初始化v数组;后来发现,每次回溯都会把上一个数的标记清空,最后只剩下v[1]=1;具体见图当N=4时,
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<vector>
#include<cstring>
using namespace std;
int n,v[25];
vector<int>vec;
vector<int>::iterator p;
int check(int n)
{
int i;
for(i=2;i<=sqrt(n);i++)
{
if(n%i==0)
break;
}
if(i>sqrt(n)&&n!=1)
return 1;
else
return 0;
}
void dfs(int x,int y,int cn)
{
if(cn==n)
{
if(check(y+1)==1&&check(x+y)==1)
{
for(int j=0;j<n;j++)
{
printf("%d",vec[j]);
if(j!=n-1)printf(" ");
else printf("\n");
}
}else
{
return ;
}
}else
{
if(check(x+y)==0)
{
return ;
}else
{
for(int k=2;k<=n;k++)
{
if(v[k]==0)
{
v[k]=1;
vec.push_back(k);
dfs(y,k,cn+1);
v[k]=0;
vec.erase(vec.begin()+cn);
}
}
}
}
return ;
}
int main()
{
int TT=0;
while(~scanf("%d",&n))
{
TT++;
memset(v,0,sizeof(v));
printf("Case %d:\n",TT);
vec.clear();
int i;
v[1]=1;
vec.push_back(1);
for(i=2;i<=n;i++)
{
/*memset(v,0,sizeof(v);
v[1]=1;*/
v[i]=1;
vec.push_back(i);
dfs(1,i,2);
v[i]=0;
vec.erase(vec.begin()+1);
}
printf("\n");
}
return 0;
}
代码简化一下
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
using namespace std;
int v[22],n,a[22],cn;
int check(int n)
{
int i;
for(i=2;i<=sqrt(n);i++)
{
if(n%i==0)
break;
}
if(i>sqrt(n)&&n!=1)
return 1;
else
return 0;
}
void dfs(int x,int cn)
{
int i,j;
if(cn==n&&check(x+1)==1)
{
for(j=1;j<=n;j++)
{
printf("%d",a[j]);
if(j!=n)printf(" ");
else printf("\n");
}
return;
}
for(i=2;i<=n;i++)
{
if(v[i]==0&&check(i+x)==1)
{
v[i]=1;
a[cn+1]=i;
dfs(i,cn+1);
v[i]=0;
}
}
return;
}
int main()
{
int TT=0;
while(~scanf("%d",&n))
{
cn=1;
printf("Case %d:\n",++TT);
memset(v,0,sizeof(v));
a[1]=1;
v[1]=1;
dfs(1,1);
printf("\n");
}
return 0;
}