写之前先膜拜了一遍题解区的大佬……
思路:
我的第一反应就是全排列!
至于全排列不会的,建议首先做一下这道题练练手再回来。
当然,暴力会 TLE……
但是现在,我们知道了全排列函数!
它就是 next_permutation,这个函数的作用是求某一个全排列的下一个全排列,这个可以帮助理解。
看了上面的链接后,你就已经基本了解了这个函数的用法。
于是,代码自然也就写出来了。
代码
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <iostream>
#include <cstring>
#include <stdio.h>
#include <string>
#include <map>
#include <vector>
#include <queue>
#include <set>
#include <list>
#include <deque>
#include <stack>
#define int long long
//#define rep(i, s, t) for (int i = (s), i <= (t), i++)
const int N = 1e6 + 5;
int n, m, a[N];
int read() {
int res = 0;
char c = getchar();
bool f = false;
while (c < '0' || c > '9') {
if (c == '-')
f = true;
c = getchar();
}
while (c >= '0' && c <= '9') {
res = res * 10 + (c - '0');
c = getchar();
}
if (f)
res = -res;
return res;
}
void print (int x) {
if (x == 0) {
putchar('0');
return;
}
if (x < 0) {
putchar('-');
x = -x;
}
int b[50] = {}, top = 0;
for (; x; x /= 10) {
b[++top] = x % 10;
}
do {
putchar(b[top] + '0');
} while (--top > 0);
}
signed main() {
n = read (); m = read ();
for (int i = 1;i <= n;i ++) a[i] = read ();
for (int i = 1;i <= m;i ++) std::next_permutation (a + 1, a + n + 1);//也是直接调用函数就行了 ,调用方式类似于sort
for (int i = 1;i <= n;i ++) print (a[i]), putchar (' ');
return 0;
}
进食后人: 不要随便使用 define,不然可能会为此逝掉1个小时。