Files
python/TangDou/LuoGuBook/P1157.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

46 lines
1.3 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <bits/stdc++.h>
using namespace std;
const int N = 30; //n的上限是20开数组是20+10=30个
vector<vector<int>> res;
//总结:要求双重排序的,都可以利用本题的思想干掉!
/**
自定义排序函数
*/
bool cmp(const vector<int> &a, const vector<int> &b) {
for (int i = 0; i < a.size(); i++)
if (a[i] != b[i]) return a[i] < b[i];
return false;
}
int main() {
int n, r;
cin >> n >> r; //n个自然数选择r个组成组合
for (int S = 0; S <= (1 << n) - 1; S++) {
//只要对应二进制数字的1的个数是r的
if (__builtin_popcount(S) == r) {
vector<int> t;
//遍历数字S的每一个二进制位
for (int i = 0; i <= n - 1; i++)
if (S & (1 << i)) t.push_back(i + 1);//i+1为对应的数字
//加入结果数组
res.push_back(t);
}
}
//1、每个子数组内部进行一轮排序
for (int i = 0; i < res.size(); i++)
sort(res[i].begin(), res[i].end());
//2、二维数组进行一次排序
sort(res.begin(), res.end(), cmp);
//输出
for (int i = 0; i < res.size(); i++) {
for (int j = 0; j < res[0].size(); j++)
printf("%3d", res[i][j]);
printf("\n");
}
return 0;
}