1114. 素数环

lovelynewlife
#include <iostream>
#include <vector>
#include <cmath>

#define MAX_SUM 40

using namespace std;

bool prime_table[MAX_SUM+1];

bool is_prime(int num)
{
    if(num==1)
        return false;

    int limit = sqrt(num);
    bool is_prime = true;
    for(int i = 1; i <= limit; i++)
    {
        if(i==1)
            continue;

        if(num%i==0)
        {
            is_prime = false;
            break;
        }
    }

    return is_prime;
}

bool *visited;
vector<int> result;
int n=0;

void DFS(int pre)
{
    int all_visited = true;

    for(int i = 1; i<=n;i++)
    {
        int now = 0;
        if(!visited[i])
        {
            now = i;
            all_visited = false;
            if(prime_table[now+pre])
            {
                result.push_back(now);
                visited[i] = true;
                DFS(now);
                result.pop_back();
                visited[i] = false;
            }
        }
    }
    if(all_visited)
    {
        if(prime_table[pre+1])
        {
            for(int i = 0;i<result.size();i++)
            {
                if(i!=0)
                    cout<<" ";
                cout<<result[i];
            }
            cout<<endl;
        }
    }
}

int main()
{
    for(int i = 1; i <=MAX_SUM;i++)
    {
        prime_table[i] = is_prime(i);
    }

    while(cin>>n)
    {
        visited = new bool[n+1];
        result.clear();
        result.push_back(1);
        fill_n(visited,n+1,false);
        visited[1] = true;
        DFS(1);
        delete[] visited;
    }

    return 0;
}

DFS

NBC++

include < cstdio>

include < iostream>

include < cmath>

using namespace std;
void circle (int i,int T);
bool isprime (int a,int b);

int a[21] ;
bool b[21] ;
int d [11] = {2,3,5,7,11,13,17,19,23,29,31};
int cnt;
int main (){
int T;
cin >> T;
a [21] = {0};
a [1] = 1 ;
b [21] = {0};
cnt = 1;
circle (2,T);
}

void circle (int i,int T){

int j;
for (j =2;j<=T;j++){
    if (isprime(j,a[i-1]) && !b[j] || i ==1){
        a[i] = j;
        b[j] = 1;
        if (i ==T && isprime(1,a[T])) {
            /*cout << cnt ++ <<" :";*/
            int k ;
            for (k =1;k<=T;k++)
            cout << a[k] << " ";
            cout << endl;
        }
        else circle (i+1,T);
        b [j] = 0;
    } 
}

}

bool isprime (int a,int b){
int c = a+b;
int i ;
bool flag = 0;
for (i =0;c >= d [i] && i < 11;i++)
if ( c == d[i]) flag =1;
return flag ;
}

你当前正在回复 博客/题目
存在问题!