You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
# 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 ;
}