diferenta>modul

Se citesc de la tastatura doua nr naturale n si v.Scrieti un program care afiseaza toate nr de la 1 la n in toate modurile posibile, astfel incat intre oricare doua numere afisate in pozitii invecinate, diferenta in modul sa fie mai mare decat valoarea data v.

Exemplu: n=4,v=1 solutiile vor fi 3 1 4 2 si 2 4 1 3

#include<iostream.h>
#include<conio.h>
#include<math.h>
int st[20],n,k,v;

void init()
{st[k]=0;}

int succesor()
{if (st[k]<n)
{st[k]++;
return 1;
}
else return 0;}

int valid()
{for(int i=1;i<k;i++)
if(st[i]==st[k]) return 0;
if((k>1) &&(abs(st[k]-st[k-1]<=v)) return 0;

return 1;}

int sol()
{return (k==n);}

void tipar()
{for(int i=1;i<=n;i++) cout<<st[i];
cout<<endl;
}

void bkt()
{int as;k=1;
init();
while(k>0)
{
do {} while ((as=succesor()) && !valid());
if (as)
if (sol()) tipar();
else {k++;init();}
else k–;
}
}

void main()
{cout<<“n=”;cin>>n;
cout<<“v=”;cin>>v;
bkt();
getch();
}

{joscommentenable}

Leave a Reply