分别利用STL中的next_permutation和它的实现原理来写:
next_permutation:
<span style="font-family:Courier New;font-size:18px;">#include<stdio.h> #include<stdlib.h> #include<string.h> #include<algorithm> using namespace std; int main() { char a[55]; char b[55]; while(scanf("%s",a),a[0]!='#') { strcpy(b,a); int len = strlen(b); //qsort(b,len,sizeof(b[0]),cmp); if(next_permutation(a,a+len)) { puts(a); } else { puts("No Successor"); } } return 0; }</span>
实现原理:
<span style="font-family:Courier New;font-size:18px;">#include<stdio.h> #include<stdlib.h> #include<string.h> #include<algorithm> using namespace std; int main() { char a[55]; char ch; int ans,s,i; while(scanf("%s",a),a[0]!='#') { int len = strlen(a); int flag = 0; for(i=len-1; i>0; i--) { if(a[i]>a[i-1]) { s = i-1; flag = 1; break; } } if(flag == 0) { puts("No Successor"); continue; } else { for(i=len-1; i>s; i--) { if(a[i]>a[s]) { ans = i; break; } } ch = a[ans]; a[ans] = a[s]; a[s] = ch; for(i=0; i<=s; i++) { printf("%c",a[i]); } for(i=len-1; i>s; i--) { printf("%c",a[i]); } puts(""); } } return 0; }</span>
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-19 11:04:40