在 6楼 代码的基础上改善了一下。(6楼代码不好的地方在于,可能先筛选出k比较小的排列,后面需要舍弃)
输出结果
程序代码:
#include <stdio.h> size_t foo( const int a[static 21] ) { size_t k_max=0, k=21; for( unsigned m=0; m!=(1u<<20)-1; ) { _Bool bok = 1; for( unsigned i=0; bok && i!=21; ++i ) if( (~m)&(1u<<i) ) for( unsigned j=i+1; bok && j!=21; ++j ) if( (~m)&(1u<<j) ) bok = a[j-i]==a[0]; if( bok && k_max==0 ) k_max = k; if( bok && k==k_max ) { for( unsigned i=0; i!=21; ++i ) if( (~m)&(1u<<(21-1-i)) ) printf( "%u, ", i ); printf( "k=%zu\n", k_max ); } // next m unsigned r = m==0 ? 1 : (((m|(m-1))+1)|((m^((m|(m-1))+1))/((m^(m-1))+1)/2)) & ((1u<<20)-1); if( r<m && k_max!=0 ) break; if( m==0 || r<m ) --k; m = r<m ? ((r<<2)|3) & ((1u<<20)-1) : r; } return k_max; } int main( void ) { const int a[21] = { 10, 10, 10, 45, 87, 66, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 85, 47, 15, 10, 10 }; foo( a ); }
输出结果
0, 1, 2, 8, 9, 10, k=6
0, 1, 2, 8, 9, 15, k=6
0, 1, 2, 8, 14, 15, k=6
0, 1, 2, 9, 10, 11, k=6
0, 1, 2, 10, 11, 12, k=6
0, 1, 2, 11, 12, 13, k=6
0, 1, 2, 12, 13, 14, k=6
0, 1, 2, 13, 14, 15, k=6
0, 1, 7, 8, 9, 15, k=6
0, 1, 7, 8, 9, 20, k=6
0, 1, 7, 8, 14, 15, k=6
0, 1, 7, 8, 14, 20, k=6
0, 1, 7, 13, 14, 15, k=6
0, 1, 7, 13, 14, 20, k=6
0, 1, 8, 9, 10, 20, k=6
0, 1, 9, 10, 11, 20, k=6
0, 1, 10, 11, 12, 20, k=6
0, 1, 11, 12, 13, 20, k=6
0, 1, 12, 13, 14, 20, k=6
0, 6, 7, 8, 14, 15, k=6
0, 6, 7, 8, 14, 20, k=6
0, 6, 7, 8, 19, 20, k=6
0, 6, 7, 13, 14, 15, k=6
0, 6, 7, 13, 14, 20, k=6
0, 6, 7, 13, 19, 20, k=6
0, 6, 12, 13, 14, 20, k=6
0, 6, 12, 13, 19, 20, k=6
0, 7, 8, 9, 19, 20, k=6
0, 8, 9, 10, 19, 20, k=6
0, 9, 10, 11, 19, 20, k=6
0, 10, 11, 12, 19, 20, k=6
0, 11, 12, 13, 19, 20, k=6
0, 1, 2, 8, 9, 15, k=6
0, 1, 2, 8, 14, 15, k=6
0, 1, 2, 9, 10, 11, k=6
0, 1, 2, 10, 11, 12, k=6
0, 1, 2, 11, 12, 13, k=6
0, 1, 2, 12, 13, 14, k=6
0, 1, 2, 13, 14, 15, k=6
0, 1, 7, 8, 9, 15, k=6
0, 1, 7, 8, 9, 20, k=6
0, 1, 7, 8, 14, 15, k=6
0, 1, 7, 8, 14, 20, k=6
0, 1, 7, 13, 14, 15, k=6
0, 1, 7, 13, 14, 20, k=6
0, 1, 8, 9, 10, 20, k=6
0, 1, 9, 10, 11, 20, k=6
0, 1, 10, 11, 12, 20, k=6
0, 1, 11, 12, 13, 20, k=6
0, 1, 12, 13, 14, 20, k=6
0, 6, 7, 8, 14, 15, k=6
0, 6, 7, 8, 14, 20, k=6
0, 6, 7, 8, 19, 20, k=6
0, 6, 7, 13, 14, 15, k=6
0, 6, 7, 13, 14, 20, k=6
0, 6, 7, 13, 19, 20, k=6
0, 6, 12, 13, 14, 20, k=6
0, 6, 12, 13, 19, 20, k=6
0, 7, 8, 9, 19, 20, k=6
0, 8, 9, 10, 19, 20, k=6
0, 9, 10, 11, 19, 20, k=6
0, 10, 11, 12, 19, 20, k=6
0, 11, 12, 13, 19, 20, k=6
[此贴子已经被作者于2020-10-11 10:06编辑过]