目录
P1088 [NOIP2004 普及组] 火星人 - 全排列函数
leetcode 题号:238. 除自身以外数组的乘积 - 前后缀
P1088 [NOIP2004 普及组] 火星人 - 全排列函数
输入 #1
5
3
1 2 3 4 5
输出 #1
1 2 4 5 3
小知识:全排列 (next_permutation)
对于next_permutation函数,其函数原型为:
#include <algorithm>
bool next_permutation(iterator start,iterator end)
当当前序列不存在下一个排列时,函数返回false,否则返回true
数字
next_permutation(num,num+n)函数是对数组num中的前n个元素进行全排列,同时并改变num数组的值。如例2
另外,需要强调的是,next_permutation()在使用前需要对欲排列数组按升序排序,否则只能找出该序列之后的全排列数。如例1
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int num[3]={1,2,3};
//int num[3]={2,1,3}; //例1
//int num[6]={1,2,3,4,5,6}; //例2
do
{
for(int i=0;i<sizeof(num)/4;i++)
cout<<num[i]<<" ";
puts("");
}while(next_permutation(num,num+3));
return 0;
}
例1:
2 1 3
2 3 1
3 1 2
3 2 1
例2:
1 2 3 4 5 6
1 3 2 4 5 6
2 1 3 4 5 6
2 3 1 4 5 6
3 1 2 4 5 6
3 2 1 4 5 6
字符串
next_permutation是一个原地算法(会直接改变这个集合,而不是返回一个集合),它对一个可以遍历的集合(如string,如vector),将迭代器范围 [first, last] 的排列 排列到下一个排列。
也就是说,可以排序字符串;
字符串“123”的按照字典序正确的全排列是:"123" "132" "213" "231" "312" "321"
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
//string number = "213";
string number = "abc";
do
{
cout << number << endl;
}while(next_permutation(number.begin(), number.end()));
return 0;
}
输出:
213
231
312
321
abc
acb
bac
bca
cab
cba
值得注意的是,空格也是字符,也会一起全排序
所以,该题根本不要思考,直接秒杀
#include<bits/stdc++.h>
using namespace std;
int a[10005],n,m;
int main(){
scanf("%d%d",&n,&m);
for(int i=0;i<n;i++) cin>>a[i];
while(m--) next_permutation(a,a+n);
for(int i=0;i<n;i++) printf("%d ",a[i]);
return 0;
}
最大乘积 - 蓝桥杯国赛
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
typedef long long ll;
int num[10], arr[12];
int maxv = 0, ret,j,x,y;
int js(int l, int r)
{
int t = 0;
for (int i = l; i <= r; i++)
t = t * 10 + num[i];
return t;
}
int main()
{
for (int i = 0; i < 9; i++) num[i] = i + 1;
do
{
for (int i = 0; i < 9; i++)
{
int a = js(0, i);
int b = js(i + 1, 8);
ret = a * b;
//cout<<a<<" "<<b<<" "<<ret<<endl;
memset(arr,0,sizeof(arr));
while (ret)
{
arr[ret%10]++;
ret /= 10;
}
for (j = 1; j <= 9; j++) if (arr[j]!=1) break;
if (j == 10)
{
//cout << a * b<<endl;
maxv = max(maxv, a * b);
x=a;
y=b;
//cout<<x<<" "<<y<<" "<<maxv<<endl;
}
}
} while (next_permutation(num, num + 9));
cout<<x<<" "<<y<<" "<<maxv<<endl;
return 0;
}
AcWing 2067. 走方格 - DP优化暴搜
第十一届蓝桥杯省赛第一场C++A/B组