uva 146 ID Codes

求给出字符串的下一序列。


法一:直接利用c++中next_permutation函数,(算法竞赛经典入门P187)


#include "stdio.h"
#include "algorithm"
#include "string.h"
using namespace std;
int main(){
	char str[1000];
	int len;
	bool flag;
	while(scanf("%s",str))
	{
		len=strlen(str);
		flag=0;
		if(str[0]=='#') break;
		while(next_permutation(str,str+len))//next_permutation布尔型
		{
			flag=1;break;
		}
		if(flag) printf("%s
",str);
        else printf("No Successor
");

	}
	return 0;
}



法二:


#include "stdio.h"
#include "algorithm"
#include "string.h"
using namespace std;
int main()
{
    int i,s;
    char str[1024],t;
    while(gets(str))
    {
        if(str[0]=='#') break;
        int len=strlen(str);
        for(i=len-1; i>0; i--)//从后向前找第一个后面字母比前面字母大的字母M
        {
            if(str[i-1]<str[i]) break;
        }
        if(i==0)//字典序最大
        {
            printf("No Successor
");
            continue;
        }
        s=i;
        for(i=len-1; i>=s; i--)//M之后找比它大的字母中最小的
        {
            if(str[i]>str[s-1])

            {
                t=str[i];
                str[i]=str[s-1];
                str[s-1]=t;
                break;
            }
        }
        sort(str+s,str+len);//M字母后面的字母按升序排列
        printf("%s
",str);
    }
return 0;
}




版权声明:本文为博主原创文章,未经博主允许不得转载。http://xiang578.top/

原文地址:https://www.cnblogs.com/xryz/p/4848116.html