HDOJ1016(Prime Ring Problem)dfs
#include <iostream>
using namespace std;
const int N = 40;
bool prime[N];
int n;
bool visit[22];
void initPrime()
{
for(int i = 0; i < N; i++)
prime[i] = false;
prime[2] = prime[3] = prime[5]
= prime[7] = prime[11] = prime[13]
= prime[17] = prime[19] = prime[23]
= prime[29] = prime[31] = prime[37] = true;
}
void dfs(int cc[], int kk)
{
if(kk > n)
{
if(prime[cc[1] + cc[n]])
{
cout<<cc[1];
for(int i = 2; i <= n; i++)
cout<<" "<<cc[i];
cout<<endl;
}
}
else
{
for(int i = 2; i <= n; i++)
if(!visit[i] && prime[i + cc[kk - 1]])
{
visit[i] = true;
cc[kk] = i;
dfs(cc,kk + 1);
visit[i] = false;
}
}
}
int main()
{
int t = 1;
int cc[22];
initPrime();
cc[1] = 1;
visit[1] = true;
for(int i = 1; i <= 20; i++)
visit[i] = false;
while(cin>>n)
{
cout<<"Case "<<t++<<":"<<endl;
dfs(cc, 2);
cout<<endl;
}
return 0;
}
using namespace std;
const int N = 40;
bool prime[N];
int n;
bool visit[22];
void initPrime()
{
for(int i = 0; i < N; i++)
prime[i] = false;
prime[2] = prime[3] = prime[5]
= prime[7] = prime[11] = prime[13]
= prime[17] = prime[19] = prime[23]
= prime[29] = prime[31] = prime[37] = true;
}
void dfs(int cc[], int kk)
{
if(kk > n)
{
if(prime[cc[1] + cc[n]])
{
cout<<cc[1];
for(int i = 2; i <= n; i++)
cout<<" "<<cc[i];
cout<<endl;
}
}
else
{
for(int i = 2; i <= n; i++)
if(!visit[i] && prime[i + cc[kk - 1]])
{
visit[i] = true;
cc[kk] = i;
dfs(cc,kk + 1);
visit[i] = false;
}
}
}
int main()
{
int t = 1;
int cc[22];
initPrime();
cc[1] = 1;
visit[1] = true;
for(int i = 1; i <= 20; i++)
visit[i] = false;
while(cin>>n)
{
cout<<"Case "<<t++<<":"<<endl;
dfs(cc, 2);
cout<<endl;
}
return 0;
}