Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and beauty - Discrete question: Given an arbitrary group, find the algorithm for all its subgroups.

Discussing a specific subgroup, for each element in the group, there are only two states: in/not in the

Discrete question: Given an arbitrary group, find the algorithm for all its subgroups.

Discussing a specific subgroup, for each element in the group, there are only two states: in/not in the

Discrete question: Given an arbitrary group, find the algorithm for all its subgroups.

Discussing a specific subgroup, for each element in the group, there are only two states: in/not in the subgroup

So, by changing this of each element Bool tags of presence and absence can generate all subgroups

For example, for a subgroup of a group of three elements, the complete set means that all elements are located in the subgroup, that is, 111, and only the first two It is 110 at that time, and only the last subgroup is 001

Similarly, for any subgroup with multiple elements, all subgroups can be generated by changing the state of each element

The following algorithm regards each bit of the integer variable as the existence mark of the element, that is, the third bit is 1, indicating that the third element is in this subgroup:

#include

int main()

{

unsigned iLen = 0;

puts("The number of collection elements?( 1~31)");

scanf("%u", &iLen);

if (iLen > 31 || iLen <= 0)

{

puts("out of range");

return -1;

}

FILE *pFile = fopen("out .txt", "w");

if (pFile == NULL)

{

puts("Failed to open file");

return -2;

}

unsigned iMax = 1 << iLen;

for (unsigned i = 1; i < iMax; + +i)

{

for (int j = 0; j < iLen; ++j)

{

if ( (i >> j) & 1)

{

fprintf(pFile, "%u ", j + 1);

}

}

fputc('\n', pFile);

}

fclose(pFile);

}< /p>

The above algorithm, when there are 3 elements, will process the first three digits. The range of integers composed of 3 digits is 1~7 (the empty set will not be processed), so for 1~7 For each number, take out each of their digits in turn to determine whether it is 1, then you can know whether the element corresponding to this digit is in the set corresponding to this number

For example

When i is equal to 5, 5 is equal to 101 in binary. The first and third elements are in the set, but the second one is not. This is a subset

The above code can only handle 1~31 bit elements, mainly because when there are too many elements, it is impossible to list them all (n! grows too fast); if you have to list them, similarly, you can just implement the addition of large numbers, and the large numbers range from 1 to n , each number is treated as a set and each bit is 1, indicating that this element is in the set