杭電素數環(Dfs加回溯)

題目鏈接

很有紀念意義的一個題目,紀念,複試加油

#include <iostream>
#include <vector>
#include <stdio.h>
#include <math.h>
using namespace std;
vector<bool> vis(21, false);
vector<int> res(21, 0);
bool isPrime(int n)
{
    int mid = int(sqrtf(n)) + 1;
    bool flag = true;
    for (int i = 2; i <= mid; i++)
    {
        if (n % i == 0)
        {
            flag = false;
            break;
        }
    }
    return flag;
}
void Dfs(int size, int n)
{
    if (size == n)
    {
        cout << res[1];
        for (int i = 2; i <= n; i++)
        {
            cout << " " << res[i];
        }
        cout << endl;
    }
    for (int i = 1; i <= n; i++)
    {
        if (vis[i] == false)
        {
            if (size == (n - 1))
            {
                int after = res[1];
                int pre = res[size];
                if (isPrime(i + after) && isPrime(i + pre))
                {
                    size++;
                    res[size] = i;
                    vis[i] = true;
                    Dfs(size, n);
                    size--;
                    vis[i] = false;
                }
            }
            else
            {
                int pre = res[size];
                if (isPrime(i + pre))
                {
                    size++;
                    res[size] = i;
                    vis[i] = true;
                    Dfs(size, n);
                    size--;
                    vis[i] = false;
                }
            }
        }
    }
}
int main()
{
    int n;
    int index = 1;
    while (cin >> n)
    {
        printf("Case %d:\n", index);
        res[1] = 1;
        vis[1] = true;
        for (int i = 2; i <= n; i++)
        {
            res[i] = 0;
            vis[i] = false;
        }
        Dfs(1, n);
        index++;
        cout<<endl;
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章