uva 146 ID Codes(求下一个排列)水水水

分别利用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>


posted on 2017-04-21 15:45  ljbguanli  阅读(94)  评论(0编辑  收藏  举报