跳到正文

个人记录

2036 next_permutation方法

厨神约 1 分钟
原文
文章信息与版本

文章信息

发布
2020年7月12日
收录
2026年8月2日
更新
2026年11月14日
篇幅
约 1 分钟
获赞
1

版本

  1. v1当前

其实是排列组合的问题。 非常好的全排列练习题。 next_permutation是头文件<algorithm>里面的一个函数 可以输出一个数组的全排列。参数与sort一样。

比如 a={1,2,3,4,5}; 那么运行next_permutation(a,a+5)之后呢 数组就变成了 1 2 3 5 4. 输出所有a的排列就是

C++
do{
  for(int i=0;i<5;i++){
   		cout << a[i];                     
  }
  cout << endl;
}while(next_permutation(a,a+5));

这个函数非常重要,是二等奖冲刺一等奖的利器。10以内的数据几乎都能骗到分!

这个题的全排列函数解法

C++
#include<bits/stdc++.h>
using namespace std;
int n,id[20],a,b=1,minans=1e9;
int x[20],y[20]; 
int main(){
  cin >> n;
  for(int i=0;i<n;i++){
  	id[i]=i;
  	cin >> x[i] >> y[i];
  }
  do{
  	b=1;a=0;
  	for(int i=0;i<n;i++){
  			a+=y[id[i]];
  			b*=x[id[i]];
  		minans=min(minans,abs(a-b));
  	}
  }while(next_permutation(id,id+n));
  cout << minans;
  return 0;
}
原文