洛谷 P1088 火星人 (全排列)

直接调用next_permutation即可,向前的话可以调用prev_permutation

#include<cstdio>
#include<cctype>
#include<algorithm>
#define REP(i, a, b) for(int i = (a); i < (b); i++)
#define _for(i, a, b) for(int i = (a); i <= (b); i++)
using namespace std;

const int MAXN = 11234;
int a[MAXN], n, m;
void read(int& x)
{
	int f = 1; x = 0; char ch = getchar();
	while(!isdigit(ch)) { if(ch == '-1') f = -1; ch = getchar(); }
	while(isdigit(ch)) { x = x * 10 + ch - '0'; ch = getchar(); }
	x *= f;
}

int main()
{
	read(n); read(m);
	REP(i, 0, n) read(a[i]);
	while(m--) next_permutation(a, a + n);
	printf("%d", a[0]); REP(i, 1, n) printf(" %d", a[i]);
	puts("");
	return 0;
}

还可以不用STL做,原理见https://blog.csdn.net/HyJoker/article/details/50899362

#include<cstdio>
#include<cctype>
#include<algorithm>
#define REP(i, a, b) for(int i = (a); i < (b); i++)
#define _for(i, a, b) for(int i = (a); i <= (b); i++)
using namespace std;

const int MAXN = 11234;
int a[MAXN], n, m;
void read(int& x)
{
	int f = 1; x = 0; char ch = getchar();
	while(!isdigit(ch)) { if(ch == '-1') f = -1; ch = getchar(); }
	while(isdigit(ch)) { x = x * 10 + ch - '0'; ch = getchar(); }
	x *= f;
}

void next()
{
	int j, k;
	for(j = n - 2; j >= 0 && a[j] > a[j+1]; j--);
	for(k = n - 1; k >= 0 && a[k] < a[j]; k--);
	swap(a[k], a[j]);
	reverse(a + j + 1, a + n);
}

int main()
{
	read(n); read(m);
	REP(i, 0, n) read(a[i]);
	while(m--) next();
	printf("%d", a[0]); REP(i, 1, n) printf(" %d", a[i]);
	puts("");
	return 0;
}

 

posted @ 2018-09-17 11:23  Sugewud  阅读(332)  评论(0编辑  收藏  举报