HDU-1016 Prime Ring Problem

来源:互联网 发布:exe一机一码加密软件 编辑:程序博客网 时间:2024/06/01 08:46

Problem Description
A ring is compose of n circles as shown in diagram. Put natural number 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 < 20).

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. Print solutions in lexicographical order.

You are to write a program that completes above process.

Print a blank line after each case.

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

主要思路:回溯法

C++代码:

#include<iostream>using namespace std;int prime(int num){    if(num==1)        return 0;    if(num==2)        return 1;    for(int i=2;i<=num-1;i++)        if(num%i==0)            return 0;    return 1;}int different(int k,int *x){    for(int i=1;i<k;i++)        if(x[k]==x[i])            return 0;    return 1;}int place(int k,int n,int *x){    for(int i=1;i<k;i++)        if(!prime(x[k]+x[k-1])||!different(k,x))            return 0;    return 1;}void traceback(int k,int n,int *x){    if(k>n){        if(prime(x[n]+x[1])){            cout<<x[1];            for(int i=2;i<=n;i++)                cout<<" "<<x[i];            cout<<endl;        }    }    else{        for(int i=1;i<=n;i++){            x[k]=i;            if(place(k,n,x))                traceback(k+1,n,x);        }    }}int main(){    int n=1,*x;    int count=0;    while(cin>>n){        count++;        cout<<"Case "<<count<<":"<<endl;        x=new int[n+1];        for(int i=0;i<=n;i++)            x[i]=0;        x[1]=1;        traceback(2,n,x);        cout<<endl;    }    return 0;}

注意:输出格式很重要,Presentation Error很扎心!

原创粉丝点击