zoukankan      html  css  js  c++  java
  • A

    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. 

     

    Inputn (0 < n < 20). 
    OutputThe 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

    题目分析 :

        1. 1的位置不变,从1开始DFS深搜;
        2. 素数函数的效率决定了代码是否超时;

    错误点 :
      1. 素数的判断有误;
        2. while(true) 的形式有误,无法跳出,时间超时;
    #include <iostream>
    #include <math.h>
    #include <vector>
    #include <cstring>
    using namespace std;
    int n,m,array[25],mark[25],step,k=0;
    
    bool Exame_prime(int x,int y)
    {
        int sum = x+y;
        for(int i=2;i*i<=sum;i++)
            if(sum%i==0)
                return true;
        return false;
    }
    
    void DFS(int x)
    {
        step++;
        array[step] = x;
        if(step==n)
        {
            if(!Exame_prime(array[step],1))
            {
                for(int i=1;i<=step;i++)
                {
                    if(i!=step)
                        cout << array[i] << " ";
                    else
                        cout << array[i];
                }
                cout << endl;
            }
            return;
        }
    
        for(int i=2;i<=n;i++)
        {
            //cout <<"|||| :" <<  x <<"  " <<i << "  " <<mark[i] <<"  "  << ++k <<  "
    ";
            if(!Exame_prime(x,i) && !mark[i])
            {
                mark[i]=1;
                DFS(i);
                mark[i]=0;
                step--;//不可省略,step为常数,不会回溯;
            }
        }
    }
    
    int main()
    {
        int m=0;
        while(cin >> n)
        {
            memset(mark,0,sizeof(mark));
            step=0;
            cout << "Case " << ++m <<":" << "
    ";
            DFS(1);
            cout << endl;
        }
        return 0;
    }
  • 相关阅读:
    JavaCore和HeapDump 规格严格
    日志输出(转) 规格严格
    Assert理解(51cto) 规格严格
    Telnet工具 规格严格
    Java工具应用(转老外) 规格严格
    杂项选用 规格严格
    What means the errormessage 'java.lang.OutOfMemoryError: GC overhead limit exceeded' in Java? 规格严格
    如何才能让你的SQL运行得更快
    如何才能让你的SQL运行得更快
    关于-非法的xml字符
  • 原文地址:https://www.cnblogs.com/7750-13/p/7259062.html
Copyright © 2011-2022 走看看