全排列的編碼與解碼

來源:互聯網
上載者:User

標籤:

看《演算法競賽入門經典》 第七章, 隱式圖的遍曆,八數位一題。

學到了全排列的編碼與解碼。

用處: 每一個排列代表一個圖的狀態, 比如 8,3,2,4,5,6,7,0,1

表示成圖就是

8  3  2

4  5  6

7  0  1

我們將0~8的全排列和0~9!一一映射起來。

比如0, 1, 2, 3, 4, 5, 6, 7, 8 對應的就是0, 因為是第一個排列組合

那麼8 7 6 5 4 3 2 1 0 對應的就是9!,因為是最後一種排列組合。

 

演算法實現如下:

int fact[9];   //假設排列組合範圍是0~8  
void init(){
  fact[0] = 1;  for (int i = 1; i < 9; i++) fact[i] = fact[i - 1] * i;}int transfer(int ar[9]) { int code = 0; for (int i = 0; i < 9; i++) { int cnt = 0; for (int j = i + 1; j < 9; j++) if (ar[j] < ar[i]) cnt++; code += fact[8 - i] * cnt; }return code;}

 

全排列的編碼與解碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.