uva146-枚举,排列

题意:

输入最多150个小写字母,在字典序增大的方向,求下一个排列是什么.

模拟枚举,最后一个字符是递归的最后一层(n层),那么把它弹出栈(还剩n-1层),如果n-1层的字符比第n层小,说明把n层的字符移到n-1层是一个更大的排列,

同样,对于任意第k层,比较k+1,k+2.......n层

ac代码,一个用了库,一个自己写的

#include<stdio.h>
#include<iostream>
#include<sstream>
#include<queue>
#include<map>
#include<memory.h>
#include <math.h>
#include<time.h>
#include <stdlib.h>
#include <algorithm>
using namespace std;

struct Stack
{
	int s[200];
	int si = -1;
	void push(int c)
	{
		s[++si] = c;
	}
	int pop()
	{
		if(si == -1)
			return -1;
		int c = s[si--];
		return c;
	}
};

int main()
{
	//freopen("d:\1.txt", "r", stdin);
	string no = "No Successor";
	while (cin)
	{
		string str;
		cin >> str;
		if(str == "#")
			return 0;
		if(next_permutation(str.begin(), str.end()))
			cout << str << endl;
		else
			cout << no << endl;
	}
	return 0;
}

  

#include<stdio.h>
#include<iostream>
#include<sstream>
#include<queue>
#include<map>
#include<memory.h>
#include <math.h>
#include<time.h>
#include <stdlib.h>
using namespace std;

struct Stack
{
	int s[200];
	int si=-1;
	void push(int c)
	{
		s[++si] = c;
	}
	int pop()
	{
		if(si == -1)
			return -1;
		int c = s[si--];
		return c;
	}
};


int main()
{
	//freopen("d:\1.txt", "r", stdin);
	string no = "No Successor";
	while (cin)
	{
		string str;
		cin >> str;
		if(str == "#")
			return 0;
		int length = str.length();
		Stack s;
		//26 low letter
		int num[26];
		memset(num, 0, sizeof(num));
		for(int i = 0; i < length; i++)
			s.push(str.at(i));
		int l = 26;
		int j = -1;
		while (true)
		{
			int k = s.pop();
			if(k == -1)
			{
				break;
			}
			num[k - 'a']++;
			for(int i = k - 'a' + 1; i < l; i++)
				if(num[i] != 0)
				{
					j = i;
					break;
				}
			if(j != -1)
				break;
		}
		if(j == -1)
		{
			cout << no << endl;
		}
		else
		{
			s.push(j+'a');
			num[j]--;
			for(int i = 0; i < l; i++)
			{
				while (num[i]--)
				{
					s.push(i + 'a');
				}
			}
			string ss = "";
			while (true)
			{
				j = s.pop();
				if(j==-1)
					break;
				ss += (char)j;
			}
			for(int i = ss.length()-1;i>=0;i--)
				cout<<ss.at(i);
			cout<<endl;

		}
	}
	return 0;
}

  

原文地址:https://www.cnblogs.com/shuiyonglewodezzzzz/p/7624357.html