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);
                    }
                   
                }
            }
        }
    }
  • 相关阅读:
    bzoj4849: [Neerc2016]Mole Tunnels
    bzoj 4069~4071 APIO2015
    bzoj 4885: [Lydsy2017年5月月赛]长方体
    bzoj4891: [Tjoi2017]龙舟
    bzoj4892: [Tjoi2017]dna
    bzoj 3159: 决战
    bzoj3672: [Noi2014]购票
    bzoj4738: 汽水
    bzoj 4737: 组合数问题
    bzoj 4872: [Shoi2017]分手是祝愿
  • 原文地址:https://www.cnblogs.com/lihonglin2016/p/4307865.html
Copyright © 2011-2022 走看看