Sunteți pe pagina 1din 3

// Generarea partitiilor unei multimi

#include <iostream>

using namespace std;

int st[10];
int k,i,n, as,ev;

void init(int st[10], int k)


{
st[k]=0;
}

void succesor(int st[10], int k, int &as)


{
int max,i;
if(k==1)max=1; // daca sunt pe nivelul 1 atunci maximul este 1
else
max=st[1]; // in caz contrar determin max de pe cele k-1 nivele
for(i=2;i<=k-1;i++)
if(max<st[i])max=st[i];
if((st[k]<k)&&(st[k]<max+1))
// daca valoarea de pe nivelul k nu depaseste nici maximul anterior si nici nivelul
{
st[k]++; // genereaza un nou succesor
as=1;
}
else as=0;
}
void valid(int st[10], int k, int &ev)
{
ev=1; // orice valoare aflata pe un nivel este valida

int solutie(int k)
{
if(k==n) // avem solutie cand am pus toate valorile pe stiva solutie
return 1;
else
return 0;
}

void tipar(int st[10], int k)


{
int i,j,max;
max=st[1];
for(i=1;i<=k;i++)
if(max<st[i])max=st[i]; // determin cea mai mare valoare pe prima k nivele
cout<<"O partitie este "<<endl;
for(j=1;j<=max;j++) // afisez partitiile construite anterior
{
cout<<"{";
for(i=1;i<=n;i++)
if(st[i]==j)cout<<i<<" ";
cout<<"}";
}
cout<<endl;
}
int main()
{
cout<<"Dati n =";cin>>n;
k=1;
init(st,k);
while(k>0)
{
do
{
succesor(st,k,as);
if(as)valid(st,k,ev);
}while(as && !ev);
if(as)
if(solutie(k))
tipar(st,k);
else
{
k++;
init(st,k);
}
else k--;
}
return 0;
}

S-ar putea să vă placă și