国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 學(xué)院 > 開(kāi)發(fā)設(shè)計(jì) > 正文

藍(lán)橋杯之全排列函數(shù) next_permutation()解析

2019-11-10 23:46:01
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

這是一個(gè)求一個(gè)排序的下一個(gè)排列的函數(shù),可以遍歷全排列,要包含頭文件 下面是以前的筆記 與之完全相反的函數(shù)還有PRev_permutation

(1) int 類型的next_permutation

int main(){ int a[3];a[0]=1;a[1]=2;a[2]=3; do{cout<<a[0]<<" "<<a[1]<<" "<<a[2]<<endl;} while (next_permutation(a,a+3)); //參數(shù)3指的是要進(jìn)行排列的長(zhǎng)度//如果存在a之后的排列,就返回true。如果a是最后一個(gè)排列沒(méi)有后繼,返回false,每執(zhí)行一次,a就變成它的后繼}

輸出:

1 2 3 1 3 2 2 1 3 2 3 1 3 1 2 3 2 1

如果改成 while(next_permutation(a,a+2)); 則輸出: 1 2 3 2 1 3

只對(duì)前兩個(gè)元素進(jìn)行字典排序 顯然,如果改成 while(next_permutation(a,a+1)); 則只輸出:1 2 3

若排列本來(lái)就是最大的了沒(méi)有后繼,則next_permutation執(zhí)行后,會(huì)對(duì)排列進(jìn)行字典升序排序,相當(dāng)于循環(huán)

int list[3]={3,2,1}; next_permutation(list,list+3); cout<

int main(){ char ch[205];cin >> ch;sort(ch, ch + strlen(ch) );//該語(yǔ)句對(duì)輸入的數(shù)組進(jìn)行字典升序排序。如輸入9874563102 cout<<ch; 將輸出0123456789,這樣就能輸出全排列了 char *first = ch; char *last = ch + strlen(ch); do {cout<< ch << endl;}while(next_permutation(first, last)); return 0;}

//這樣就不必事先知道ch的大小了,是把整個(gè)ch字符串全都進(jìn)行排序 //若采用 while(next_permutation(ch,ch+5)); 如果只輸入1562,就會(huì)產(chǎn)生錯(cuò)誤,因?yàn)閏h中第五個(gè)元素指向未知 //若要整個(gè)字符串進(jìn)行排序,參數(shù)5指的是數(shù)組的長(zhǎng)度,不含結(jié)束符

(3) string 類型的next_permutation

int main(){ string line; while(cin>>line&&line!="#"){ if(next_permutation(line.begin(),line.end())) //從當(dāng)前輸入位置開(kāi)始cout<<line<<endl; else cout<<"Nosuccesor/n";}}int main(){ string line; while(cin>>line&&line!="#"){sort(line.begin(),line.end());//全排列cout<<line<<endl; while(next_permutation(line.begin(),line.end()))cout<<line<<endl;}}

next_permutation 自定義比較函數(shù)

#include<iostream>#include<string>#include<algorithm>using namespace std;int cmp(char a,char b) //'A'<'a'<'B'<'b'<...<'Z'<'z'.{ if(tolower(a)!=tolower(b)) return tolower(a)<tolower(b); else return a<b;}int main(){ char ch[20]; int n;cin>>n; while(n--){scanf("%s",ch);sort(ch,ch+strlen(ch),cmp); do{printf("%s/n",ch);}while(next_permutation(ch,ch+strlen(ch),cmp));} return 0;}
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 从江县| 凤山县| 康乐县| 麟游县| 汉中市| 比如县| 石渠县| 铁岭市| 北流市| 即墨市| 孝昌县| 公安县| 长宁区| 庆安县| 宜良县| 绥江县| 莆田市| 永安市| 南陵县| 牟定县| 盐源县| 荃湾区| 宿州市| 乌兰县| 沁源县| 日照市| 荥经县| 赞皇县| 宁城县| 齐齐哈尔市| 蒙城县| 固阳县| 运城市| 建平县| 麻阳| 修文县| 肇州县| 宜春市| 绥化市| 东光县| 台州市|