zoukankan      html  css  js  c++  java
  • 回溯算法之素数环

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace SeqListSort
    {
        /// <summary>
        /// <ather>
        /// lihonglin
        /// </ather>
        /// <content>
        /// 把从1到20这20个数摆成一个环,要求相邻的两个数的和是一个素数。
        ///分析:用回溯算法,考察所有可能的排列
        /// </content>
        /// </summary>
        class PrimeFor
        {
            static int n = 14;
            static int[] a = new int[20];//a数组存放素数环
    
            public static void InitPrimeFor()
            {
                for (int i = 0; i < 20; ++i )
                {
                    a[i] = i + 1;
                }
            }
    
            public static void Swap( int i,  int j)
            {
                a[i] = a[i] + a[j] - (a[j] = a[i]);
            }
    
            static void PrintResult()
            {
                for (int i = 0; i < n; ++i)
                {
                    Console.Write("{0,-4}" , a[i]);
                }
                Console.WriteLine();
            }
    
            static bool IsOK(int num)
            {
                for ( int i = 2; i <= (int)Math.Sqrt(num); ++i )
                {
                    if (0 == num % i)
                    {
                        return false;
                    }
                }
                return true;
            }
    
            public static void Search(int k)
            {
                int i = 0;
                if ( k > n - 1 )//判断结束条件
                {
                    if ( IsOK(a[0] + a[n - 1]) )
                        PrintResult();
                    return;
                }
                else
                {
                    for (i = k; i < n; ++i )
                    {
                        Swap(k, i);
                        if(IsOK(a[k - 1] + a[k]))
                        {
                            Search(k + 1);//继续探索
                        }
                        //回溯
                        Swap(k, i);
                    }
                   
                }
            }
        }
    }
  • 相关阅读:
    隔离级别 && SNAPSHOT
    多态性&& 虚函数 && 抽象类
    socket编程
    [APIO2015]巴邻旁之桥
    LuoguP3701 「伪模板」主席树
    线段树标记永久化
    [HNOI2015]开店
    NOIP2017划水记
    FFTNTT总结
    [THUWC 2017]在美妙的数学王国中畅游
  • 原文地址:https://www.cnblogs.com/lihonglin2016/p/4307865.html
Copyright © 2011-2022 走看看