uva524

题目链接:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=19667

/*
solution:
    直接使用回朔法即可解决

note:
    回朔法

date:
    2016/5/7
*/
#include 
#include 
#include 
#include 

using namespace std;
int p[20], n, vis[20];

int isPrime(int x) {
    for(int i = 2; i * i <= x; i++)
        if(x % i == 0)  return 0;
    return 1;
}

void solve(int cur) {
    if(cur == n && isPrime(p[0] + p[n - 1])) {
        for(int i = 0; i < n; i++) {
            if(i)   printf(" ");
            printf("%d", p[i]);
        }

        printf("\n");
    } else {
        for(int i = 2; i <= n; i++) {
            if(!vis[i] && isPrime(i + p[cur - 1])) {
                p[cur] = i;
                vis[i] = 1;
                solve(cur + 1);
                vis[i] = 0;
            }
        }
    }
}

int main()
{
    //freopen("input.txt", "r", stdin);
    int kase = 0;
    while(~scanf("%d", &n)) {
        memset(vis, 0, sizeof(vis));
        memset(p, 0, sizeof(p));

        if(kase)    printf("\n");
        printf("Case %d:\n", ++kase);
        p[0] = 1;
        solve(1);
    }
    return 0;
}

你可能感兴趣的:(uva,OJ)