这是一个C ++程序,用于生成所有子集对,它们的并集构成Set。
Begin function UnionSet(): Arguments: a[] = an array. n = number of elements. Body of the function: 1) Generate binary code from 0 to 2^(n-1)-1 for all 2^(n-1) pairs. 2) Print the array element which has 0 or 1 in corresponding indexes in code string for each code. 3) Print them in a different set, which on the union of both sets gives the super set. End
#include<iostream> #include<math.h> #include<iomanip> using namespace std; void display(char code[], int a[], int n) //display the pairs { int i; cout<<"\t{ "; for(i = 0; i < n; i++) { if(code[i] == '1') cout<<a[i]<<" "; } cout<<"}"; cout<<" { "; for(i = 0; i < n; i++) { if(code[i] == '0') cout<<a[i]<<" "; } cout<<"}\n"; } void UnionSet(int a[], int n) { int i, r, l; char binary[n]; r = pow(2, n-1); for(i = 0; i < n; i++) binary[i] = '0'; for(i = 0; i < r; i++) { display(binary, a, n); l=n-1; h: if(binary[l] == '0') binary[l] = '1'; else { binary[l] = '0'; l--; goto h; } } } int main() { int i, n; cout<<"\nEnter the number of elements: "; cin>>n; int a[n]; cout<<"\n"; for(i = 0; i < n; i++) { cout<<"Enter "<<i+1<<" element: "; cin>>a[i]; } cout<<"\nThe possible subset pairs which on union generates the superset, are: \n"; UnionSet(a, n); return 0; }
输出结果
Enter the number of elements: 4 Enter 1 element: 4 Enter 2 element: 3 Enter 3 element: 2 Enter 4 element: 1 The possible subset pairs which on union generates the superset, are: { } { 4 3 2 1 } { 1 } { 4 3 2 } { 2 } { 4 3 1 } { 2 1 } { 4 3 } { 3 } { 4 2 1 } { 3 1 } { 4 2 } { 3 2 } { 4 1 } { 3 2 1 } { 4 }