hash --全排列hash(康托扩展)

这里的哈希函数是用能对许多全排列问题适用的方法。取n!为基数,状态第n位的逆序值为哈希值第n位数。对于空格,取其(9-位置)再乘以8!。例如,1 3 7 2 4 6 8 5 8 的哈希值等于: 
0*0! + 0*1! + 0*2! + 2*3! + 1*4! + 1*5! + 0*6! + 3*7! + (9-8)*8! = 55596 <9! 


        具体的原因可以去查查一些数学书,其中1 2 3 4 5 6 7 8 9 的哈希值是0 最小,8 7 6 5 4 3 2 1 0 的哈希值是(9!-1)最大,而其他值都在0 到(9!-1)中,且均唯一。  

例如三个元素的排列

排列    逆序  Hash 

123    000    0
132    001    2
213    010    1
231    002    4
312    011    3
321    012    5

 

转自:http://blog.csdn.net/tiaotiaoyly/article/details/1720453

八数码问题需要。。。。

c++代码:

 1 //全排列hash
 2 #include <cstdio>
 3 #include <iostream>
 4 using namespace std;
 5 int fac[]={1,1,2,6,24,120,720,5040,40320,362880};//康拖展开判重
 6 int cantor(const int *s){ //康托展开求序列的hash值
 7     int sum=0;
 8     for(int i=0;i<9;i++){
 9         int num=0;
10         for(int j=0;j<i;j++)
11             if(s[j]>s[i])
12                num++;
13         sum+=(num*fac[i]);
14     }
15     return sum+1;
16 }
17 
18 int main()
19 {
20     int a[]={1,2,3,4,5,6,7,8,0};
21     cout<<cantor(a)<<endl;
22     return 0;
23 }

 

posted @ 2012-09-29 23:13  Missa  阅读(844)  评论(0编辑  收藏  举报