1358. 素数环-深度优先搜索-DFS

1358. 素数环-深度优先搜索-DFS_第1张图片

代码:

#include 
using namespace std;
int n, a[19], c = 0;
bool f[19];
bool prime(int n){
    if(n == 1)
        return false;
    for ( int i = 2 ; i * i <= n ; i++ )
        if(n % i == 0)
            return false;
    return true;
}
void print(){
    c++;
    cout << c << ":";
    for ( int i = 1 ; i <= n ; i++ )
        cout  << a[i]<< " ";
    cout << endl;
}
void dfs(int k){
    for ( int i = 1 ; i <= n ; i++ ){
        if( f[i] == false && (k == 1 || prime(i + a[k-1]) == true) ){
            a[k] = i;
            f[i] = true;
            if( k == n && prime(a[k] + a[1]) ) print();
            else dfs(k+1);
            f[i] = false;
        }
    }
}
int main(){
    cin >> n;
    dfs(1);
    cout << "total:" << c;
    return 0;
}

你可能感兴趣的:(深度优先,算法)