全排列 next_permutation() 函數的用法


在頭文件<algorithm>里面有如下代碼:

 

int a[]; do { } while(next_permutation(a,a+n));

 

 

可產生1~n的全排列有如下代碼:

 

 1 #include <stdio.h>
 2 #include <algorithm>
 3 using namespace std;  4 int main(){  5     int n;  6     while(scanf("%d",&n)&&n){  7         int a[1000];  8         for(int i=0;i<n;i++){  9             scanf("%d",&a[i]); 10  } 11         sort(a,a+n);
12         do{ 13             for(int i=0;i<n;i++) 14                 printf("%d ",a[i]); 15             printf("\n"); 16         }while(next_permutation(a,a+n)); 17  } 18     return 0; 19 }

 

 

例如輸入

3

1 0 2

如果有sort()

輸出為

0 1 2
0 2 1
1 0 2
1 2 0
2 0 1
2 1 0

若無

則輸出為

1 0 2
1 2 0
2 0 1
2 1 0

發現函數next_permutation()是按照字典序產生排列的,並且是從數組中當前的字典序開始依次增大直至到最大字典序,在ACM International Collegiate Programming Contest, Egyptian Collegiate Programming Contest (2015)  Arab Academy for Science and Technology - Alexandria, November 6th, 2015 A題就可以采用next_permutation()。

 

原博客:https://www.cnblogs.com/My-Sunshine/p/4985366.html

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM