Thursday, June 23, 2016

【UVa】524 - Prime Ring Problem

Problem here

Problem

A ring is composed of n (even number) circles as shown in diagram.
Put natural numbers 1, 2, . . . , n into each circle separately, and the
sum of numbers in two adjacent circles should be a prime.
Note: the number of first circle should always be 1.

INPUT

n (0 < n ≤ 16

OUTPUT

The output format is shown as sample below. Each row represents a series of circle numbers in the
ring beginning from 1 clockwisely and anticlockwisely. The order of numbers must satisfy the above
requirements.
You are to write a program that completes above process

Sample Input

6
8

Sample Output

Case 1:
1 4 3 2 5 6
1 6 5 2 3 4
Case 2:
1 2 3 8 5 6 7 4
1 2 5 8 3 4 7 6
1 4 7 6 5 8 3 2
1 6 7 4 3 8 5 2

Solution

#include <iostream>
#include <vector>
#include <cmath>
using namespace std;

int A[20];
bool vis[20];
int n;
int testcase = 1;

bool is_prime(int n){
    for(int i = 2; i <= sqrt(n); i++)
        if(n % i == 0)
            return false;
        return true;

}

void slove(int cur){
    if(cur == n && is_prime(A[n-1] + A[n])){
        for(int i = 0; i < n; i++){
            if(i == 0)  
                cout << A[i];
            else
                cout << " " << A[i];
        }
        cout << endl;
    }else{
        for(int i = 2; i <= n; i++){
            if(!vis[i] && is_prime(i+A[cur-1])){
                A[cur] = i;
                vis[i] = true;
                slove(cur+1);
                vis[i] = false;
            }
        }
    }
}

int main(){
    while(cin >> n){
        if(testcase > 1)
            cout << endl;
        A[0] = A[n] = 1;
        cout << "Case " << testcase++ << ":" << endl;
        slove(1);
    }

    return 0;
}

No comments:

Post a Comment