这应该是道模拟题,但是我看到了一种用STL next_permutation()函数的做法,觉得很有趣。
next_permutation() 和 prev_permutation()是一对亲兄弟。
简单来讲,next_permutation() 可以将一个数列升序 从小到大输出,而prev_permutation() 可以将一个数列降序从大到小输出
注意:这两个函数都是对数列直接进行操作,改变数列的顺序,调整成下一个顺序的数列。
下面给出示例代码
#include <bits/stdc++.h>
using namespace std;
///数字排序
int main()
{
int a[3]={1,2,3};
do
{
cout<<a[0]<<" "<<a[1]<<" "<<a[2]<<endl;
}while(next_permutation(a,a+3));
return 0;
}
#include <bits/stdc++.h>
using namespace std;
///字符排序
int main()
{
char ch[205];
cin>>ch;
sort(ch,ch+strlen(ch));
char *first =ch;
char *last=ch+strlen(ch);
do{
cout<<ch<<endl;
}while(next_permutation(first,last));
return 0;
}
下面是本题的代码
#if 1
#include <bits/stdc++.h>
using namespace std;
int N;///火星人手指数目
int M;///加数
int a[10010];
int main()
{
cin>>N;
cin>>M;
for(int i=0;i<N;i++)
cin>>a[i];
while(M--) next_permutation(a,a+N);
///while (M--) 是核心所在
for(int i=0;i<N;i++)
cout<<a[i]<<" ";
/// cout<<a[N-1];
return 0;
}
#endif // 1