数组全排列生成

今天在网上看到了那个排列组合生成函数,原来还有这个函数的,以前只是听说过好像有这个的。用了一下,有时还真的很有用的。
例:POJ1256

#include <iostream>
using namespace std;
#include <algorithm>
struct node
{
	char	ch;
	int	num;
} s[100];
bool cmp( node a, node b )
{
	return(a.num < b.num);
}


int main()
{
	int	cas, len, i;
	char	str[15];
	cin >> cas;
	while ( cas-- )
	{
		scanf( "%s", str );
		len = strlen( str );
		for ( i = 0; i < len; i++ )
		{
			s[i].ch = str[i];
			if ( str[i] <= 'Z' )
				s[i].num = (str[i] - 'A') * 2;
			else s[i].num = (str[i] - 'a') * 2 + 1;
		}
		sort( s, s + len, cmp );
		for ( i = 0; i < len; i++ )
			printf( "%c", s[i].ch );
		printf( "\n" );
		while ( next_permutation( s, s + len, cmp ) )
		{
			for ( i = 0; i < len; i++ )
				printf( "%c", s[i].ch );
			printf( "\n" );
		}
	}
	return(0);
}

还有一个

#include <iostream>
using namespace std;
int main()
{
	char	str[6]	= { '2', '3', '1', 0 };
	int	i	= 0;
	while ( prev_permutation( str, str + 3 ) )      /* 产生当前排列的前一个排列 */
	{
		printf( " % s \n ", str );
		if ( i == 2 )
			break;
		i++;
	}
	while ( next_permutation( str, str + 3 ) )      /* 产生当前排列的后一个排列 */
		printf( " % s \n ", str );
	return(0);
}
# acm 

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×