zoukankan      html  css  js  c++  java
  • java图书排列

    标题:图书排列
    将编号为1~10的10本书排放在书架上,要求编号相邻的书不能放在相邻的位置。
    请计算一共有多少种不同的排列方案。

    注意,需要提交的是一个整数,不要填写任何多余的内容。

    9 9
    10 9
    9 9
    9 9
    9 10
    7 7
    9 7

    package 第三次模拟;
    
    public class Demo3图书排列 {
    	static int res=0;  
        public static boolean check(int a[])  
        {  
            int l=a.length;  
            for(int i=0;i<l-1;i++)  
            {  
    //          两个相邻的元素,如果它们的数字是相邻的,就是两个元素相减的绝对值 == 1;那么就return false;
                if(Math.abs(a[i]-a[i+1])==1)  
                {  
                    return false;  
                }  
            }  
            return true;  
        }  
    //    static int count=0;
    //    将a[]中的a[x] 与   a[y]  的值互换
        public static void swap(int a[],int x,int y)  
        {  
        	//位运算转换节省内存,如果x==y的话,无需转换
        	if(x==y) return; 
        	
        	a[x]^=a[y];  
        	a[y]^=a[x];  
        	a[x]^=a[y]; 
    //        int temp =a[x];  
    //        a[x]=a[y];  
    //        a[y]=temp;  
     
        }  
        public static void dfs(int a[],int begin,int end)  
        {  
            if(begin==end)  
            {  
    //          检查相邻的书是否被放在了相邻的位置  :以数字来代表书;相邻两个数字的差的绝对值要不等于1
                if(check(a))  
    //              如果相邻的两个数字的差的绝对值不等于1,则找到了一种方案。
                res++;  
            }  
    
            for(int i = begin; i <= end; i++)  
            {  
                swap(a,begin,i);  
                dfs(a,begin+1,end);  
                swap(a,begin,i);  
            }  
        }  
        public static void main(String[] args) {  
    
            int a[]={1,2,3,4,5,6,7,8,9,10};  
            dfs(a,0,a.length-1);  
            System.out.println(res);  
        }
    }
    
    
    
  • 相关阅读:
    委托的例子,from C# advanced program
    C#线程通信与异步委托
    进程间通信
    线程间通信
    投影转换(AE)
    FTP多任务下载实现类
    堆内存和栈内存详解(转)
    How threads differ from processes
    实现远程FTP特定时间轨道号MODIS数据的搜索
    委托的例子
  • 原文地址:https://www.cnblogs.com/a1439775520/p/13074390.html
Copyright © 2011-2022 走看看