洛谷 P1088 火星人 (全排列)

时间:2020-12-28 05:54:35

直接调用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;
}