probleme sda

of 100 /100
Universitatea Politehnica Bucuresti Probleme rezolvate la SDA Gostinar Nicolae Viorel Grupa 314 AB 2010-2011

Upload: bosoiro

Post on 18-Jul-2016

235 views

Category:

Documents


6 download

DESCRIPTION

Probleme Sda

TRANSCRIPT

Page 1: Probleme Sda

Universitatea Politehnica Bucuresti

Probleme rezolvate la SDA

Gostinar Nicolae Viorel

Grupa 314 AB

2010-2011

Page 2: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 4

Cuprins:

Problema 1 .......................................................................................................................................6Problema 2 .......................................................................................................................................8Problema 3 .......................................................................................................................................9Problema 4 .....................................................................................................................................11Problema 5 .....................................................................................................................................12Problema 6 .....................................................................................................................................14Problema 7 ....................................................................................................................................15Problema 8 .....................................................................................................................................18Problema 9 .....................................................................................................................................21Problema 10 ....................................................................................................................................23Problema 11 ....................................................................................................................................25Problema12 .....................................................................................................................................27Problema 13 ....................................................................................................................................30Problema 14 ....................................................................................................................................31Problema 15 ....................................................................................................................................33Problema 16 ....................................................................................................................................34Problema 17 ....................................................................................................................................36Problema 18 ....................................................................................................................................37Problema 19 ....................................................................................................................................38Problema 20 ....................................................................................................................................39Problema 21 ....................................................................................................................................45Problema 22 ....................................................................................................................................46Problema 23 ....................................................................................................................................48Problema 24 ....................................................................................................................................49Problema 25 ....................................................................................................................................50Problema 26 ....................................................................................................................................52Problema 27 ....................................................................................................................................53Problema 28 ....................................................................................................................................54Problema 29 ....................................................................................................................................55Problema 30 ....................................................................................................................................56Problema 31 ....................................................................................................................................57

Page 3: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 5

Problema 32 ....................................................................................................................................58Problema 33 ....................................................................................................................................60Problema 34 ....................................................................................................................................51Problema 35 ....................................................................................................................................62Problema 36 ....................................................................................................................................63Problema 37 ....................................................................................................................................64Problema 38 ....................................................................................................................................65Problema 39 ....................................................................................................................................69Problema 40 ....................................................................................................................................70Problema 41 ....................................................................................................................................71Problema 42 ....................................................................................................................................74Problema 43 ....................................................................................................................................75Problema 44 ....................................................................................................................................76Problema 45 ....................................................................................................................................77Problema 46 ....................................................................................................................................78Problema 47 ....................................................................................................................................80Problema 48 ....................................................................................................................................82Problema 49 ....................................................................................................................................84Problema 50 ....................................................................................................................................86Problema 51 ....................................................................................................................................89Problema 52 ....................................................................................................................................90Problema 53 ....................................................................................................................................91Problema 54 ....................................................................................................................................93Problema 55 ....................................................................................................................................94Problema 56 ....................................................................................................................................97Problema 57 ....................................................................................................................................98Problema 58 .................................................................................................................................. 100

Page 4: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 6

Problema 1/*Sa se creeze programul construieste recursiv si tipareste un arbore de numere intregi, utilizand

functiile recursive: 'inserare', 'listare'. Arborele contine pe langa valorile intregi ordonate (SRD) si numarul de aparitii pentru valorile ce se repeta. Programul permite eliminarea unei anumite valori (chei), adica un nod din arbore ce contine cheia, pastrand arborele de cautare (SRD).*/#include <stdio.h>#include <stdlib.h>#include <conio.h>typedef struct tnod

{int nr;int ap;struct tnod *pstg;struct tnod *pdr;} ARB;

int nel = 0;ARB *e;void inserare (ARB * &v, int val){ARB *pc;int gasit;if (!v)

{v = new ARB; v->nr=val; v->ap=1;v->pstg=NULL; v->pdr=NULL;}

else if (v->nr > val)inserare(v->pstg, val);

else if (v->nr < val)inserare(v->pdr, val);

elsev->ap++;

}void inlocuire_nod(ARB * &n){if (n->pdr)

inlocuire_nod(n->pdr);else {e->nr=n->nr;

e->ap=n->ap;e=n;n=n->pstg; free(e);}

}void elimina_nod (ARB * &a, int x){if (!a)

printf("\nCheia cautata %d nu este in arbore!\n", x);else if (x < a->nr)

elimina_nod (a->pstg, x);

Page 5: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 7

else if (x > a->nr)elimina_nod (a->pdr, x);

else{e=a;if (!a->pstg){

a=a->pdr;free(e);}

else if (!a->pdr){a=a->pstg;free(e);}

elseinlocuire_nod(a->pstg);

} }void listare_SRD (ARB *v){if (v)

{if (v->pstg)listare_SRD (v->pstg);

printf("%3d(%d) -> ", v->nr, v->ap);nel++;if (nel%7==0)

printf("\n");if (v->pdr)

listare_SRD(v->pdr);}

}main(){ARB *pl;int valoare;pl = NULL;//clrscr();printf("Se construieste un arbore de cautare si permite elimarea unui nod.\n");printf ("\nIntroduceti un sir de valori, terminat cu EOF.\n");printf ("Valoare:");while ( scanf ("%d", &valoare) != EOF) {

inserare (pl,valoare);printf ("Valoare:");}

/* afisare arbore */printf("\nListare arbore SRD:\n");listare_SRD (pl);printf ("NULL\n");printf("\nValoare de eliminat: ");scanf("%d", &valoare);elimina_nod(pl, valoare);

Page 6: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 8

/* afisare arbore dupa eliminare */printf("\nListare arbore SRD, dupa eliminarea valorii %d:\n", valoare);nel=0;listare_SRD (pl);printf ("NULL\n");printf("Terminare dupa apasarea unei taste!\n");getch();}Problema 2/*Sa se creeze programul construieste recursiv si tipareste un arbore de intregi, utilizand functiile recursive: 'inserare' si 'listare'.Arborele contine pe langa valorile intregi ordonate (SRD) si numarul de aparitii pentru valorile ce se repeat;- afiseaza arborele si inaltimea lui.*/#include <stdio.h>#include <stdlib.h>#include <conio.h>typedef struct tnod

{int nr;int ap;struct tnod *pstg;struct tnod *pdr;} ARB;

int nel = 0;void inserare (ARB * &v, int val){ARB *pc;int gasit;if (!v)

{v = new ARB; v->nr=val; v->ap=1;v->pstg=NULL; v->pdr=NULL;}

else if (v->nr < val)inserare(v->pstg, val);

else if (v->nr > val)inserare(v->pdr, val);

elsev->ap++;

}void listare_SRD (ARB *v){if (v)

{if (v->pstg)listare_SRD (v->pstg);

printf("%3d(%2d) -> ", v->nr, v->ap);nel++;if (nel%7==0)

printf("\n");

Page 7: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 9

if (v->pdr)listare_SRD(v->pdr);

}}int maxim (int a, int b){if (a>b)

return a;return b;}int inaltime (ARB *v){if (!v)

return 0;else

return 1+maxim(inaltime(v->pstg), inaltime(v->pdr));}main(){ARB *pl;int valoare;pl = NULL;//clrscr();printf("Dimensiune structura: %d\n", sizeof (struct tnod));printf ("\nIntroduceti un sir de valori, terminat cu 0.\n");printf ("Valoare:");while ( scanf ("%d", &valoare) != EOF) {

inserare (pl,valoare);printf ("Valoare:");}

/* afisare arbore */printf("\nListare arbore SRD:\n");listare_SRD (pl);printf ("NULL\n");printf("Inaltime arbore: %d\n", inaltime(pl));

}Problema 3/*Sa se creeze programul care construieste recursiv si tipareste un arbore de numere intregi,utilizand functiile recursive: 'inserare' si 'listare'.Arborele contine pe langa valorile intregi ordonate (SRD) si numarul de aparitii pentru valorile ce se repeta.- varianta 2 pentru functia 'inserare' (total recursiva)

*/#include <stdio.h>#include <stdlib.h>#include <conio.h>typedef struct tnod

{int nr;

Page 8: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 10

int ap;struct tnod *pstg;struct tnod *pdr;} ARB;

int nel = 0;void inserare (ARB * &v, int val){ARB *pc;int gasit;if (!v)

{v = new ARB; v->nr=val; v->ap=1;v->pstg=NULL; v->pdr=NULL;}

else if (v->nr > val)inserare(v->pstg, val);

else if (v->nr < val)inserare(v->pdr, val);

elsev->ap++;

}void listare_RSD (ARB *v){if (v)

{printf("%3d(%2d) -> ", v->nr, v->ap);nel++;if (nel%7==0)

printf("\n");if (v->pstg)

listare_RSD (v->pstg);if (v->pdr)

listare_RSD(v->pdr);}

}void listare_SRD (ARB *v){if (v)

{if (v->pstg)listare_SRD (v->pstg);

printf("%3d(%2d) -> ", v->nr, v->ap);nel++;if (nel%7==0)

printf("\n");if (v->pdr)

listare_SRD(v->pdr);}

}main(){ARB *pl;int valoare;pl = NULL;//clrscr();

Page 9: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 11

printf("Dimensiune structura: %d\n", sizeof (struct tnod));printf ("\nIntroduceti un sir de valori, terminat cu 0.\n");printf ("Valoare:");scanf ("%d", &valoare);while ( valoare ) {

inserare (pl,valoare);printf ("Valoare:");scanf ("%d", &valoare);}

/* afisare lista */listare_RSD (pl);printf ("NULL\n");nel=0;printf("\nListare SRD:\n");listare_SRD (pl);printf ("NULL\n");

}Problema 4/* Sa se creeze un arbore, construit recursiv, ce contine cuvinte, si numarul de aparitie a acestora, citite de la tastatura (cate un cuvant pe linie) introducerea cuvintelor se termina cu un cuvant vid (Enter la inceputul liniei), si apoi sunt afisate cuvintele in ordine alfabetica.*/

#include <stdio.h>#include <string.h>#include <stdlib.h>#include <conio.h>#define LUNGMAX 20struct st_arbore{char *cuvant; int nrap; struct st_arbore *st, *dr;};

int nle=0;void actualizare (struct st_arbore * arb , char *cuv){if (strcmp(cuv, arb->cuvant) < 0)if (arb->st)

actualizare (arb->st, cuv);else {

arb->st=(struct st_arbore *) malloc (sizeof(struct st_arbore)) ;arb=arb->st;arb->cuvant=cuv;arb->nrap=1;arb->st=NULL;arb->dr=NULL;}

Page 10: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 12

else if (strcmp(cuv, arb->cuvant) >0 )if(arb->dr)

actualizare (arb->dr, cuv);else {

arb->dr=(struct st_arbore *) malloc (sizeof(struct st_arbore)) ;arb=arb->dr;arb->cuvant=cuv;arb->nrap=1;arb->st=NULL;arb->dr=NULL;}

elsearb->nrap=arb->nrap + 1;

}void tiparire_arbore (struct st_arbore *arbo){if (arbo!=NULL){tiparire_arbore (arbo->st) ; printf ("%s (ap: %d)\n", arbo -> cuvant, arbo -> nrap ) ;nle++;if (nle%24==0){

printf("Apasati o tasta pentru a continua afisarea!\n");getch();}

tiparire_arbore (arbo->dr) ; }

}void main (){struct st_arbore *arb;char cuvant[LUNGMAX] ;//clrscr();printf("Introduceti cuvinte, care vor fi apoi tiparite in ordine"

" alfabetica:\n");gets(cuvant) ;arb=(struct st_arbore *) malloc (sizeof(struct st_arbore)) ;arb->cuvant=strdup(cuvant);arb->nrap=1;arb->st=NULL;arb->dr=NULL;gets(cuvant) ;while (strcmp(cuvant, "")){actualizare (arb, strdup(cuvant));gets(cuvant);}

printf("Lista ordonata a cuvintelor (numar aparitii):\n");tiparire_arbore (arb);}

Page 11: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 13

Problema 5/*Sa se creeze programul care construieste o coada de cuvinte, pe care o afiseaza, la terminarea introducerii de cuvinte, cu eliberarea spatiului alocat pentru aceasta structura.*/#include <stdio.h>#include <stdlib.h>#include <string.h>#include <conio.h>#define SIR_VID ""#define DIMCV 25struct st_cuvant{char *cuvant;struct st_cuvant *urmator;};

int ncl=0;struct st_cuvant * atasare_coada (struct st_cuvant *ultim, char *sirc){struct st_cuvant *vr;vr=(struct st_cuvant *) malloc(sizeof(struct st_cuvant));if (vr){vr->cuvant=strdup(sirc);vr->urmator=NULL;ultim->urmator=vr;}

return (vr);}void extragere ( struct st_cuvant * primu){struct st_cuvant *ptr;while (primu){ptr=primu;printf (" %s -> ", primu->cuvant);ncl++;if (ncl%5==0)

printf("\n");primu=primu->urmator;free(ptr);}

printf ("NULL\n");}void main(){struct st_cuvant *primul, *ultimul;char cuv[DIMCV];//clrscr();

Page 12: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 14

printf("Programul construieste o lista de tip coada cu cuvinte de la"" tastatura\n");

printf("Programul ia sfarsit cu un cuvant vid, adica RETURN,"" la inceput de linie.\n");

printf("Cuvant de introdus in lista:");gets(cuv);primul=(struct st_cuvant *) malloc(sizeof(struct st_cuvant));primul->cuvant=strdup(cuv);primul->urmator=NULL;ultimul=primul;printf("Cuvant de introdus in lista:");gets(cuv);while (strcmp(cuv, SIR_VID)){if(!(ultimul=atasare_coada (ultimul, cuv)))

break;printf("Cuvant de introdus in lista:");gets(cuv);}

extragere (primul);}Problema 6/* Sa se creeze programul care construieste o coada de cuvinte, pe care o afiseaza, la terminarea introducerii de cuvinte, cu eliberarea spatiului alocat pentru aceasta structura; varianta citeste in ciclu si primul cuvant introdus.*/

#include <stdio.h>#include <stdlib.h>#include <string.h>#include <conio.h>#define SIR_VID ""#define DIMCV 25struct st_cuvant{char *cuvant;struct st_cuvant *urmator;};

int ncl=0;struct st_cuvant * atasare_coada (struct st_cuvant *ultim, char *sirc){struct st_cuvant *vr;vr=(struct st_cuvant *) malloc(sizeof(struct st_cuvant));if (vr){vr->cuvant=strdup(sirc);vr->urmator=NULL;ultim->urmator=vr;

Page 13: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 15

}return (vr);}void extragere ( struct st_cuvant * primu){struct st_cuvant *ptr;while (primu){ptr=primu;printf (" %s -> ", primu->cuvant);ncl++;if (ncl%5==0)

printf("\n");primu=primu->urmator;free(ptr);}

printf ("NULL\n");}void main(){struct st_cuvant *primul, *ultimul;char cuv[DIMCV];printf("Programul construieste o lista de tip coada cu cuvinte de la"

" tastatura\n");printf("Programul ia sfarsit cu un cuvant vid, adica RETURN,"

" la inceput de linie.\n");printf("Cuvant de introdus in lista:");gets(cuv);primul=ultimul=NULL;while (strcmp(cuv, SIR_VID)){if(!(ultimul=atasare_coada (ultimul, cuv)))

break;if (!primul)

primul=ultimul;printf("Cuvant de introdus in lista:");gets(cuv);}

extragere (primul);}Problema 7/* Sa se creeze programul care contine operatii cu o coada realizata static intr-un tablou; operatii disponibile: inserare, extragere, afisare cap coada, afisare coada, afisare pozitii referinte la primul si ultimul element din coada */#include <stdio.h>#include <conio.h>#define MaxC 10

Page 14: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 16

typedef int ElTip;typedef struct {

ElTip elem [MaxC];int prim, ultim;} TCoada, *ACoada;

void eroare (char *meserr){printf("%s\n", meserr);}int IncIndexC (int i){ return ((i+1) % MaxC);}void InitCoada (ACoada pc){pc->prim=0;pc->ultim=MaxC-1;}int CoadaGoala (ACoada pc){return (IncIndexC (pc->ultim) == pc->prim);}int CoadaPlina (ACoada pc){return (IncIndexC (IncIndexC(pc->ultim)) == pc->prim);}void AdaugElC (ACoada pc, ElTip el){if (IncIndexC (IncIndexC(pc->ultim)) == pc->prim)eroare ("Coada Plina !!!");

else {pc->ultim=IncIndexC(pc->ultim);pc->elem[pc->ultim]=el;}

}ElTip ScotElC (ACoada pc){ElTip e;if (CoadaGoala (pc)){eroare ("Coada Goala !!!");return 0;}

else{e=pc->elem[pc->prim];pc->prim=IncIndexC(pc->prim);return e;}

}ElTip CapCoada (ACoada pc){if (CoadaGoala (pc)){eroare ("Coada Goala !!!");return 0;}

elsereturn pc->elem[pc->prim];

}

Page 15: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 17

void AfisareCoada (ACoada pc){ TCoada c=*pc;ACoada pt=&c;int nvl=0;if (CoadaGoala(pt))eroare("Coada Goala !!!\n");

elsewhile (!CoadaGoala (pt))

{printf ("%d -> ", CapCoada (pt));ScotElC (pt);if (++nvl % 10 == 0)

printf("\n");}

printf("NULL\n");}void Afisare_Poz_Prim_Ultim (ACoada pc){printf("Cei doi indecsi (referinte), prim si ultim: %d(p), %d(u)\n",

pc->prim, pc->ultim);}void main (void){TCoada c, *pc;char optiune[20];ElTip n;printf("Exemplu de coada realizata utilizand un tablou.\n");printf("Coada este alcatuita din numere intregi.\n");InitCoada (pc);printf("\nOptiuni Int, Ext, Afis coada, Cap coada, Poz p/u, Stop: ");gets(optiune);while (optiune[0] != '\0' && optiune[0] != 's' && optiune[0] != 'S'){switch(optiune[0]){case 'i':case 'I':if (CoadaPlina(pc)){

eroare("\n\tCOADA PLINA !!! ELIMINATI...\n");break;}

printf("Introd. nr. (CTRL-Z, Enter-Stop Introd): ");while (scanf("%d", &n) == 1){

AdaugElC (pc, n);if (CoadaPlina (pc)){

eroare("Coada PLINA !!! ELIMINATI.....\n");break;}

printf("Introd. nr. (CTRL-Z, Enter-Stop Introd): ");}fflush(stdin);break;

case 'e':case 'E': optiune[0]='D';

while ( !CoadaGoala (pc) &&

Page 16: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 18

(optiune[0] == 'D' || optiune[0] == 'd') ){printf ("Se extrage primul element din coada: %d\n",

CapCoada (pc));ScotElC (pc);if (!CoadaGoala (pc)){

printf("Continuati extragerea (Da/Nu): ");gets(optiune);fflush(stdin);}

}if (CoadaGoala (pc))

printf("Coada Goala !!! INTRODUCETI ELEMENTE \n");break;

case 'c':case 'C': if (!CoadaGoala (pc))

printf("Afisare element din capul cozii: %d\n",CapCoada (pc));

elseeroare("Coada Goala !!!\n");

break;case 'a':case 'A':AfisareCoada (pc);

break;case 'p':case 'P': Afisare_Poz_Prim_Ultim (pc);

break;}printf("\nOptiuni Int, Ext, Afis coada, Cap coada, Poz p/u, Stop: ");gets(optiune);}

}Problema 8/*Sa se creeze programul care contine operatii cu o coada realizata static intr-un tablou; operatii disponibile: inserare, extragere, afisare cap coada, afisare coada, afisare pozitii referinte la primul si ultimul element din coada.Varianta: pentru afisare nu se creaza o copie a cozii, ci se utilizeaza doi indecsi locali in functia Afisare

CoadaV (pc) */#include <stdio.h>#include <conio.h>#define MaxC 10typedef int ElTip;typedef struct {

ElTip elem [MaxC];int prim, ultim;} TCoada, *ACoada;

void eroare (char *meserr){

Page 17: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 19

printf("%s\n", meserr);}int IncIndexC (int i){ return ((i+1) % MaxC);}void InitCoada (ACoada pc){pc->prim=0;pc->ultim=MaxC-1;}int CoadaGoala (ACoada pc){return (IncIndexC (pc->ultim) == pc->prim);}int CoadaPlina (ACoada pc){return (IncIndexC (IncIndexC(pc->ultim)) == pc->prim);}void AdaugElC (ACoada pc, ElTip el){if (IncIndexC (IncIndexC(pc->ultim)) == pc->prim)eroare ("Coada Plina !!!");

else {pc->ultim=IncIndexC(pc->ultim);pc->elem[pc->ultim]=el;}

}ElTip ScotElC (ACoada pc){ElTip e;if (CoadaGoala (pc)){eroare ("Coada Goala !!!");return 0;}

else{e=pc->elem[pc->prim];pc->prim=IncIndexC(pc->prim);return e;}

}ElTip CapCoada (ACoada pc){if (CoadaGoala (pc)){eroare ("Coada Goala !!!");return 0;}

elsereturn pc->elem[pc->prim];

}void AfisareCoadaV (ACoada pc){/* se parcurge coada cu doi indecsi locali, copii ai celor din coada */int pp, pu; /* indecsi la primul si ultimul din coada */int nvl=0; /* Numar de valori afisate pe linie */pp=pc->prim;pu=pc->ultim;

Page 18: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 20

if (CoadaGoala(pc))eroare("Coada Goala !!!\n");

elsewhile ((pu+1) != pp) /* conditie de coada goala */

{printf ("%d -> ", pc->elem[pp]);pp++;if (++nvl % 10 == 0)

printf("\n");}

printf("NULL\n");}void Afisare_Poz_Prim_Ultim (ACoada pc){printf("Cei doi indecsi (referinte), prim si ultim: %d(p), %d(u)\n",

pc->prim, pc->ultim);}void main (void){TCoada c, *pc;char optiune[20];ElTip n;//clrscr();printf("Exemplu de coada realizata utilizand un tablou.\n");printf("Coada este alcatuita din numere intregi.\n");InitCoada (pc);printf("\nOptiuni Int, Ext, Afis coada, Cap coada, Poz p/u, Stop: ");gets(optiune);while (optiune[0] != '\0' && optiune[0] != 's' && optiune[0] != 'S'){switch(optiune[0]){case 'i':case 'I':if (CoadaPlina(pc)){

eroare("\n\tCOADA PLINA !!! ELIMINATI...\n");break;}

printf("Introd. nr. (CTRL-Z, Enter-Stop Introd): ");while (scanf("%d", &n) == 1){

AdaugElC (pc, n);if (CoadaPlina (pc)){

eroare("Coada PLINA !!! ELIMINATI.....\n");break;}

printf("Introd. nr. (CTRL-Z, Enter-Stop Introd): ");}fflush(stdin);break;

case 'e':case 'E': optiune[0]='D';

while ( !CoadaGoala (pc) &&(optiune[0] == 'D' || optiune[0] == 'd') )

{printf ("Se extrage primul element din coada: %d\n",CapCoada (pc));

Page 19: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 21

ScotElC (pc);if (!CoadaGoala (pc)){

printf("Continuati extragerea (Da/Nu): ");gets(optiune);fflush(stdin);}

}if (CoadaGoala (pc))

printf("Coada Goala !!! INTRODUCETI ELEMENTE \n");break;

case 'c':case 'C': if (!CoadaGoala (pc))

printf("Afisare element din capul cozii: %d\n",CapCoada (pc));

elseeroare("Coada Goala !!!\n");

break;case 'a':case 'A':AfisareCoadaV (pc);

break;case 'p':case 'P': Afisare_Poz_Prim_Ultim (pc);

break;}printf("\nOptiuni Int, Ext, Afis coada, Cap coada, Poz p/u, Stop: ");gets(optiune);}

}Problema 9/* Sa se construiasca un program care construieste o stiva de numere intregi, distincte, pe care o afiseaza, utilizand functiile: adauga_stiva si afisare_stiva .*/

#include <conio.h>#include <stdio.h>#include <stdlib.h>struct s_stiva{int valoare;int nr_aparitii; struct s_stiva *urmator;};

struct s_stiva *adauga_stiva (struct s_stiva *ultimul, int val){

struct s_stiva *ptr_stiva;if (ultimul==NULL)

Page 20: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 22

{ultimul=(struct s_stiva *) malloc(sizeof(struct s_stiva));if (ultimul==NULL)

{printf("Memorie plina!\n");return(NULL);}

else{ultimul->valoare=val;ultimul->nr_aparitii=1;ultimul->urmator=NULL;return(ultimul);}

}else{ptr_stiva=ultimul;while(ptr_stiva->valoare!=val && ptr_stiva->urmator!=NULL)

ptr_stiva=ptr_stiva->urmator;if(ptr_stiva->valoare==val)

{ptr_stiva->nr_aparitii++;return(ultimul);}

else{ptr_stiva=(struct s_stiva *)malloc(sizeof(struct s_stiva));if (ptr_stiva==NULL)

{printf("Mmeorie plina!\n");return(NULL);}

else{ptr_stiva->valoare=val;ptr_stiva->nr_aparitii=1;ptr_stiva->urmator=ultimul;return(ptr_stiva);}

}}

}void afisare_stiva(struct s_stiva *ultim){int nr_val_linie = 0;while (ultim!=NULL){printf("%2d(%d)-> ", ultim->valoare, ultim->nr_aparitii);ultim=ultim->urmator;nr_val_linie++; if (nr_val_linie%8==0)

printf("\n");

Page 21: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 23

}printf ("\n");}void eliberare_spatiu (struct s_stiva *ptrs){struct s_stiva *p=ptrs;while(p){ptrs=p;p=p->urmator;free(ptrs);}

}void main(){struct s_stiva *ultim=NULL;int numar;//clrscr();printf("Prg. construieste si afiseaza o stiva de nr. intregi, distincte.\n");printf("Introducerea se termina cu EOF(CTRL-Z, ENTER.\n");printf("Introduceti numar: ");while(scanf("%d", &numar)!=EOF){if((ultim=adauga_stiva(ultim, numar))==NULL)

break;printf("Introduceti numar: ");}

afisare_stiva(ultim);eliberare_spatiu(ultim);}Problema 10/*Sa se construiasca programul care construieste o coada de numere intregi, pe care o afiseaza, utilizand functii recursive: adaug_coada, afisez_coada .*/#include <conio.h>#include <stdio.h>#include <stdlib.h>struct s_coada{int valoare;struct s_coada *urmator;};

int nr_val_linie=0; void adaug_coada (struct s_coada *primul, int val){if (primul->urmator==NULL){primul->urmator=(struct s_coada *)malloc(sizeof(struct s_coada));if(!primul->urmator)

{printf("Memorie plina!!!\n");exit(1);}

Page 22: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 24

primul=primul->urmator;primul->valoare=val;primul->urmator=NULL;}

elseadaug_coada(primul->urmator, val);

}void afisez_coada(struct s_coada *primul){if (primul){printf("%2d-> ", primul->valoare);nr_val_linie++;if (nr_val_linie%8==0)

printf("\n");afisez_coada(primul->urmator);}

}void eliberare_spatiu (struct s_coada *ptrs){struct s_coada *p=ptrs;if(p){ ptrs=p;p=p->urmator;free(ptrs);eliberare_spatiu(p);}

}void main(){struct s_coada *prim=NULL;int numar;//clrscr();printf("Prg. construieste si afiseaza o coada de nr. intregi, distincte.\n");printf("Introducerea se termina cu EOF(CTRL-Z, ENTER.\n");printf("Introduceti numar: ");scanf("%d", &numar);prim=(struct s_coada *)malloc(sizeof(struct s_coada));if(!prim){printf("Memorie plina!!!\n");exit(1);}

prim->valoare=numar;prim->urmator=NULL;printf("Introduceti numar: ");while(scanf("%d", &numar)!=EOF){adaug_coada(prim, numar);printf("Introduceti numar: ");}

afisez_coada(prim);

Page 23: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 25

printf("NULL\n");eliberare_spatiu(prim);}Problema 11/*Sa se construiasca programul care contine operatii cu o stiva realizata static intr-un tablou; operatii disponibile: inserare, extragere, afisare cap stiva, afisare stiva, afisare pointer la varful stivei. */#include <stdio.h>#include <conio.h>#define MaxS 10typedef int ElTip;typedef struct {

ElTip elem [MaxS];int sp;} TStiva, *AStiva;

void eroare (char *meserr){printf("%s\n", meserr);}void InitStiva (AStiva rs){rs->sp=-1;}int StivaGoala (AStiva rs){return (rs->sp == -1);}int StivaPlina (AStiva rs){return (rs->sp == MaxS-1);}void Push (AStiva rs, ElTip el){if (StivaPlina (rs))eroare ("Stiva Plina !!!");

else {rs->sp=rs->sp+1;rs->elem[rs->sp]=el;}

}ElTip Pop (AStiva rs){ElTip e;if (StivaGoala (rs)){eroare ("Stiva Goala !!!");return 0;}

else{e=rs->elem[rs->sp];rs->sp=rs->sp-1;return e;}

}ElTip CapStiva (AStiva rs){

Page 24: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 26

if (StivaGoala (rs)){eroare ("Stiva Goala !!!");return 0;}

elsereturn rs->elem[rs->sp];

}void AfisareStiva (AStiva rs){ TStiva s=*rs;AStiva pt=&s;int nvl=0;if (pt->sp == -1)eroare("Stiva Goala !!!\n");

elsewhile (!StivaGoala (pt))

{printf ("%d -> ", CapStiva (pt));Pop (pt);if (++nvl % 10 == 0)

printf("\n");}

printf("NULL\n");}void Afisare_Poz_sp (AStiva rs){printf("Referinta (indexul), sp: %d\n", rs->sp);if (!rs->sp)printf("\tSTIVA GOALA!!!\n");

else if (rs->sp == MaxS-1)printf("\tSTIVA PLINA !!! ELIMINATI ...\n");

}void main (void){TStiva s, *rs;char optiune[20];ElTip n;//clrscr();printf("Exemplu de stiva realizata utilizand un tablou.\n");printf("Stiva este alcatuita din numere intregi.\n");InitStiva (rs);printf("\nOptiuni Introduc, Extrag, Afis stiva, Cap stiva, Poz sp, Stop: ");gets(optiune);while (optiune[0] != '\0' && optiune[0] != 's' && optiune[0] != 'S'){switch(optiune[0]){case 'i':case 'I':if (StivaPlina(rs)){

eroare("\n\tSTIVA PLINA !!! ELIMINATI...\n");break;}

printf("Introd. nr. (CTRL-Z, Enter-Stop Introd): ");while (scanf("%d", &n) == 1 && !StivaPlina(rs)){

Push (rs, n);

Page 25: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 27

if (StivaPlina (rs)){eroare("Stiva PLINA !!! ELIMINATI.....\n");break;}

printf("Introd. nr. (CTRL-Z, Enter-Stop Introd): ");}fflush(stdin);break;

case 'e':case 'E': optiune[0]='D';

while ( !StivaGoala (rs) &&(optiune[0] == 'D' || optiune[0] == 'd') )

{printf ("Se extrage primul element din stiva: %d\n",CapStiva (rs));

Pop (rs);if (!StivaGoala (rs)){

printf("Continuati extragerea (Da/Nu): ");gets(optiune);fflush(stdin);}

}if (StivaGoala (rs))

printf("Stiva Goala !!! INTRODUCETI ELEMENTE \n");break;

case 'c':case 'C': if (!StivaGoala (rs))

printf("Afisare element din capul stivei: %d\n",CapStiva (rs));

elseeroare("Stiva Goala !!!\n");

break;case 'a':case 'A':AfisareStiva (rs);

break;case 'p':case 'P': Afisare_Poz_sp (rs);

break;}printf("\nOptiuni Int, Ext, Afis stiva, Cap stiva, Poz sp, Stop: ");gets(optiune);}

}Problema 12/*Construiti programul care contine operatii cu o stiva realizata static intr-un tablou; operatii disponibile: inserare, extragere, afisare cap stiva, afisare stiva, afisare pointer la varful stivei Varianta: functia de afisare AfisareStivaV (rs), nu mai creaza o copie a stivei, si deci nu mai utilizeaza functiile stivei, ci un index local .*/

Page 26: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 28

#include <stdio.h>#include <conio.h>#define MaxS 10typedef int ElTip;typedef struct {

ElTip elem [MaxS];int sp;} TStiva, *AStiva;

void eroare (char *meserr){printf("%s\n", meserr);}void InitStiva (AStiva rs){rs->sp=-1;}int StivaGoala (AStiva rs){return (rs->sp == -1);}int StivaPlina (AStiva rs){return (rs->sp == MaxS-1);}void Push (AStiva rs, ElTip el){if (StivaPlina (rs))eroare ("Stiva Plina !!!");

else {rs->sp=rs->sp+1;rs->elem[rs->sp]=el;}

}ElTip Pop (AStiva rs){ElTip e;if (StivaGoala (rs)){eroare ("Stiva Goala !!!");return 0;}

else{e=rs->elem[rs->sp];rs->sp=rs->sp-1;return e;}

}ElTip CapStiva (AStiva rs){if (StivaGoala (rs)){eroare ("Stiva Goala !!!");return 0;}

elsereturn rs->elem[rs->sp];

}void AfisareStivaV (AStiva rs){

Page 27: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 29

int psl=rs->sp;int nvl=0;if (rs->sp == -1)eroare("Stiva Goala !!!\n");

elsewhile (psl != -1)

{printf ("%d -> ", rs->elem[psl]);psl--;if (++nvl % 10 == 0)

printf("\n");}

printf("NULL\n");}void Afisare_Poz_sp (AStiva rs){printf("Referinta (indexul), sp: %d\n", rs->sp);if (!rs->sp)printf("\tSTIVA GOALA!!!\n");

else if (rs->sp == MaxS-1)printf("\tSTIVA PLINA !!! ELIMINATI ...\n");

}void main (void){TStiva s, *rs;char optiune[20];ElTip n;//clrscr();printf("Exemplu de stiva realizata utilizand un tablou.\n");printf("Stiva este alcatuita din numere intregi.\n");InitStiva (rs);printf("\nOptiuni Introduc, Extrag, Afis stiva, Cap stiva, Poz sp Stop: ");gets(optiune);while (optiune[0] != '\0' && optiune[0] != 's' && optiune[0] != 'S'){switch(optiune[0]){case 'i':case 'I':if (StivaPlina(rs)){

eroare("\n\tSTIVA PLINA !!! ELIMINATI...\n");break;}

printf("Introd. nr. (CTRL-Z, Enter-Stop Introd): ");while (scanf("%d", &n) == 1 && !StivaPlina(rs)){

Push (rs, n);if (StivaPlina (rs)){

eroare("Stiva PLINA !!! ELIMINATI.....\n");break;}

printf("Introd. nr. (CTRL-Z, Enter-Stop Introd): ");}fflush(stdin);break;

case 'e':

Page 28: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 30

case 'E': optiune[0]='D';while ( !StivaGoala (rs) &&

(optiune[0] == 'D' || optiune[0] == 'd') ){printf ("Se extrage primul element din stiva: %d\n",

CapStiva (rs));Pop (rs);if (!StivaGoala (rs)){

printf("Continuati extragerea (Da/Nu): ");gets(optiune);fflush(stdin);}

}if (StivaGoala (rs))

printf("Stiva Goala !!! INTRODUCETI ELEMENTE \n");break;

case 'c':case 'C': if (!StivaGoala (rs))

printf("Afisare element din capul stivei: %d\n",CapStiva (rs));

elseeroare("Stiva Goala !!!\n");

break;case 'a':case 'A':AfisareStivaV (rs);

break;case 'p':case 'P': Afisare_Poz_sp (rs);

break;}printf("\nOptiuni Int, Ext, Afis stiva, Cap stiva, Poz sp, Stop: ");gets(optiune);}

}Problema 13/*Creati programul care construieste o stiva de caractere distincte, pe care apoi o tipareste .*/#include <stdio.h>struct st_lista{char car;struct st_lista *urmator;};

void main(){struct st_lista *vr, *primul;char c;int distinct (struct st_lista *prim, char ch);

Page 29: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 31

primul = NULL;printf("\nProgramul construieste si afiseaza o stiva de caractere.\n");printf("Introduceti caractere (CTRL-Z, Enter-pentru sfarsit):\n");fflush(stdin);while ((c=getchar()) != EOF)if (c != '\n' && (distinct(primul, c)))

{vr=(struct st_lista *) malloc(sizeof(struct st_lista));if (vr == NULL)

{printf("Memorie plina !!!!!!\n");break;}

vr->car=c;vr->urmator=primul;primul=vr;}

vr=primul;while (vr != NULL){printf("%c -> ", vr->car);vr=vr->urmator;}

printf(" NULL");}int distinct (struct st_lista *prim, char ch){struct st_lista *ptr;int gasit;ptr=prim;gasit=0;while (ptr != NULL && !gasit){gasit=(ptr->car == ch);ptr=ptr->urmator;}

return (!gasit);}Problema 14/*Sa se creeze programul care construieste o lista de cuvinte, introduse de la tastatura, pe care apoi le

afiseaza, utilizand functii recursive: aatsare - pentru construire lista, si afisare - pentru afisare lista;*/#include <stdio.h>#include <stdlib.h>#include <string.h>

Page 30: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 32

#include <conio.h>#define SIR_VID ""#define DIMC 20int nvl=0;struct st_cuvant{char cuvant[DIMC]; /* sirul de caractere (cuvant) */struct st_cuvant *urmator;};

int atasare (struct st_cuvant * &vr){ /* citeste un cuvant, creaza o variabila dinamica vr si o ataseaza la lista */if (vr==NULL) /* daca referinta este NULL se ceaza un pointer */{vr=(struct st_cuvant *) malloc (sizeof(struct st_cuvant));

if (vr==NULL)return (0);else

{vr->urmator = NULL;gets(vr->cuvant);if ( !strcmp(vr->cuvant,SIR_VID) )

{vr=NULL;return(0);}

elsereturn (1);

}}

else /* daca s-a putut crea un pointer se continua atasarea */return(atasare (vr->urmator));

}void afisare (struct st_cuvant * curent){if (curent){printf ("%s -> ", curent -> cuvant);nvl++;if(nvl%5==0)

printf("\n");afisare (curent -> urmator);}

}void main(){struct st_cuvant *primul;primul = NULL;//clrscr();

Page 31: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 33

printf("Programul construieste o lista de tip coada cu cuvinte ""de la tastatura\n");

printf("Programul ia sfarsit cu un cuvant vid, adica RETURN,"" la inceput de linie.\n");

while (atasare(primul));afisare (primul);printf("NULL\n");}Problema 15/*Sa se creeze programul construieste o lista de cuvinte, introduce de la tastatura, pe care apoi le

afiseaza, utilizand functii recursive: atasare - pentru construire lista, si afisare - pentru afisare lista; Varianta : elementul din lista contine adresa cuvantului citit, pentru care se aloca spatiu (strdup) la citire;*/#include <stdio.h>#include <stdlib.h>#include <string.h>#include <conio.h>#define SIR_VID ""#define DIMC 25int nvl=0;struct st_cuvant{char *cuvant; struct st_cuvant *urmator;};

int atasare (struct st_cuvant * &vr){ char cuv[DIMC];if (vr==NULL){vr=(struct st_cuvant *)malloc (sizeof(struct st_cuvant));

if (vr==NULL)return (0);else

{vr->urmator = NULL;gets(cuv);if (!strcmp(cuv,SIR_VID))

{vr=NULL;return(0);}

else{if(!(vr->cuvant=strdup(cuv)))

{vr=NULL;

Page 32: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 34

return(0);};

return (1);}

}}

elseatasare (vr->urmator);

}void afisare (struct st_cuvant * curent){if (curent){printf ("%s -> ", curent -> cuvant);nvl++;if(nvl%5==0)

printf("\n");afisare (curent -> urmator);}

}void main(){struct st_cuvant *primul;primul = NULL;//clrscr();printf("Programul construieste o lista de tip coada cu cuvinte de la"

" tastatura\n");printf("Programul ia sfarsit cu un cuvant vid, adica RETURN,"

" la inceput de linie.\n");while (atasare(primul));afisare (primul);printf("NULL\n");}Problema 16/* Sa se creeze programul care construiete o lista ordonata de numere intregi, distincte.*/

#include <stdio.h>#include <stdlib.h>#include <conio.h>struct st_numar {

int numar;struct st_numar *next;};

int nvl=0;void main(){struct st_numar *inserare (struct st_numar *, int );

Page 33: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 35

struct st_numar *prim, *vr;int nr;//clrscr();printf("Programul construieste o lista ordonata, de numere distincte.\n");printf("Introducerea numerelor se termina cu o valoare nenumerica.\n");printf("Numar de inserat in lista: ");prim=(struct st_numar *) malloc(sizeof (struct st_numar));scanf("%d", &prim->numar);prim->next=NULL;printf("Numar de inserat in lista: ");while (scanf("%d", &nr)==1){prim=inserare (prim, nr);printf("Numar de inserat in lista: ");}

printf("\nLista de numere ordonata este:\n");while (prim){vr=prim; printf("%d -> ", vr->numar);nvl++;if (nvl%8==0)

printf("\n"); prim=prim->next;free(vr); }

printf("NULL\n");}struct st_numar *inserare (struct st_numar *primul, int n){struct st_numar *anterior, *curent, *vr;vr=(struct st_numar *) malloc(sizeof(struct st_numar));if (vr == NULL){printf("\nNu mai introduceti numere!!!\nMEMORIE PLINA!!!\n");return (primul);}

else{vr->numar=n;anterior=NULL;curent=primul; while (curent != NULL && vr->numar > curent->numar)

{anterior=curent;curent=curent->next;}

if(vr->numar == curent->numar) {free(vr);return (primul);}

vr->next=curent;

Page 34: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 36

if (anterior == NULL) primul=vr;

elseanterior->next=vr;

return (primul);}

}Problema 17/*Sa se realizeze programul ce construieste o lista circulara de caractere, pe care apoi o tipareste, si in

care se cauta un anumit caracter .*/#include <stdio.h>#include<conio.h>struct st_litera{char car;struct st_litera * pred, *urm;};

int ncl=0;void atasare(struct st_litera *pl){char c;struct st_litera *vr;while ((c=getchar()) != EOF) if (c!='\n'){vr=(struct st_litera *) malloc(sizeof(struct st_litera));if (vr == NULL)

{ printf("Memorie plina !!!!!!\n");break;}

vr->car=c;if(pl->pred==pl)

{vr->pred=vr->urm=pl;pl->urm=pl->pred=vr;}

else {vr->urm=pl;vr->pred=pl->pred;pl->pred->urm=vr;pl->pred=vr;}

}}void afis_list_circ (struct st_litera *plc){struct st_litera *p;p=plc->urm;while (p != plc){printf("%c -> ", p->car);

Page 35: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 37

p=p->urm;ncl++;if (ncl%10==0)

printf("\n");}

if (plc->urm!=plc)printf("%c (primul).\n", plc->urm->car);

elseprintf("NULL");

}int numar_aparitii_car (struct st_litera *start, char *pcar){int numar = 0;struct st_litera *curent;*pcar=start->car;curent=start->urm;while (curent != start){if (start->car == curent->car)

numar++;curent=curent->urm;}

return (numar);}void main(){struct st_litera *primul;char ch;primul->urm=primul->pred=primul; printf("\nProgramul construieste si afiseaza o lista circulara de char.\n");printf("Introduceti caractere (CTRL-Z, Enter-pentru sfarsit):\n");atasare(primul);printf("\nLista circulara construita este:\n");afis_list_circ(primul);printf("Caracterul de cautat in lista: ");ch=getch();primul->car=ch;printf("\nCaracterul \'%c\' este in lista de %d ori\n",

ch, numar_aparitii_car(primul, &ch));}Problema 18/*Sa se creeze programul ce construieste, apoi tipareste, o lista de intregi, de tip coada, utilizand functiile recursive: 'adaugare' si 'listare'.*/#include <stdio.h>#include <stdlib.h>struct tnod

Page 36: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 38

{int valoare;struct tnod *urmator;};

void adaugare (tnod * &v, int val){tnod *sf;if (!v)

{v = new tnod; v->valoare=val; v->urmator=NULL;}else

adaugare (v->urmator, val);}

void listare (tnod *v){if (v)

{printf("%d->", v->valoare);listare (v->urmator);}

}main(){struct tnod *pl;int valoare;pl = NULL;printf ("Introduceti un sir de valori, terminat cu 0.\n");printf ("Valoare:");scanf ("%d", &valoare);while ( valoare ) {

adaugare (pl,valoare);printf ("Valoare:");scanf ("%d", &valoare);}

/* afisare lista */listare (pl);printf ("NULL\n");

}Problema 19/* Sa se creeze programul ce construieste o stiva de caractere, pe care apoi o tipareste */#include <stdio.h>struct st_lista{char car;struct st_lista *urmator;};

void main(){struct st_lista *vr, *primul;char c;primul = NULL;

Page 37: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 39

printf("\nProgramul construieste si afiseaza o stiva de caractere.\n");printf("Introduceti caractere (CTRL-Z, Enter-pentru sfarsit):\n");fflush(stdin);while ((c=getchar()) != EOF) if (c!='\n'){vr=(struct st_lista *) malloc(sizeof(struct st_lista));if (vr == NULL)

{ printf("Memorie plina !!!!!!\n");break;}

vr->car=c;vr->urmator=primul;primul=vr;}

vr=primul;while (vr != NULL){printf("%c -> ", vr->car);vr=vr->urmator;}

printf(" NULL");}Problema 20/*Sa se scrie programul care realizeaza : 1 Creare arbore binar de cautare; 2 Parcurgere arbore; 3 Inserare nod in arbore; 4 Stergere nod din arbore; 5 Determinarea inaltimii arborelui; 6 Determinarea greutatii arborelui; 7 Verificare daca arborele este binar complet sau nu.*/# include <stdio.h># include <conio.h># include <stdlib.h># define NEW (NOD*)malloc(sizeof(NOD));struct NOD{int inf;struct NOD *st,*dr;};//Crearea arboreluiNOD *creare(){NOD *p;int nr;

Page 38: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 40

p=NEW;printf("Nr=");scanf("%d",&nr);p->inf=nr;p->st=NULL;p->dr=NULL;printf("Introducem arbore in stanga pentru nodul cu informatia %d (d/n)? \n",nr);if(getch()=='d') p->st=creare();printf("Introducem arbore in dreapta pentru nodul cu informatia %d (d/n)? \n",nr);if(getch()=='d') p->dr=creare();return p;}

// Parcurgerea RSD arboreluivoid parc_preord (NOD *p){if(p!=NULL)

{printf("\t Nr=%d", p->inf);parc_preord(p->st);parc_preord(p->dr);

}}// Parcurgerea SRD arboreluivoid parc_inord (NOD *p){if(p!=NULL)

{parc_inord(p->st);printf("\t Nr=%d", p->inf);parc_inord(p->dr);

}}// Parcurgerea SDR arboreluivoid parc_postord (NOD *p){if(p!=NULL)

{parc_postord(p->st);parc_postord(p->dr);printf("\t Nr=%d", p->inf);

}}// Stergerea arboreluivoid stergarbore(NOD *p){if (p!=NULL)

{stergarbore(p->st);stergarbore(p->dr);

Page 39: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 41

delete p;}

}

// Afisare spatiivoid spatii(int n){int i;for(i=0;i<n;i++)putchar(' ');}// Afisare arborevoid afisare(int n, int f, int k, int vb, int *vn){int i;spatii(4);if(n)

{for(i=1;i<n;i++)

{if(vn[i]) putchar(' ');else putchar('|');spatii(4);}

if(f) putchar('|');else putchar('|');for(i=0;i<4;i++) putchar('-');}

if(vb) printf("%d\n",k);else printf("...\n");}// Afisare pe nivelevoid afisare_nivel (NOD *p, int n=0){static int vn[50],f=1;if(p)

{afisare(n,f,p->inf,1,vn);if(p->st || p->dr)

{f=1;vn[n+1]=0;afisare_nivel(p->st,n+1);}

if(p->st || p->dr){f=0;vn[n+1]=1;afisare_nivel(p->dr,n+1);}

Page 40: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 42

}else afisare(n,f,10,0,vn);}

// Stergerea unui nod cu doi descendentiint sterg(NOD *&pa){if(pa->st) return sterg(pa->st);else

{NOD *a=pa;int k=a->inf;pa=pa->dr;free(a);

return k;}

}///// Stergerea unui nod cu cel putin un descendent vidvoid stergerenod(NOD *& p, int k){NOD *aux;if(p==NULL) printf("\n Nodul %d nu exista ",p->inf);else if(k<p->inf) stergerenod(p->st,k);

elseif(k>p->inf) stergerenod(p->dr,k);else

{aux=p;if(!aux->dr)

{p=aux->st;free(aux);}

elseif(!aux->st)

{p=aux->dr;free(aux);}

else p->inf=sterg(p->dr);}

}// Inserare nodvoid inserare(NOD *&p,int x){NOD *pnou;if (p==NULL)

{

Page 41: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 43

pnou=NEWpnou->inf=x;pnou->st=NULL;pnou->dr=NULL;p=pnou;}

elseif (p->inf>x)

inserare(p->st,x);else

if (p->inf<x)inserare(p->dr,x);

elseprintf("Elementul deja exista! \n");

}// Maximul dintre doua nrint max(int x,int y){if (x<y)

return y;else return x;}// Numararea nodurilor arboreluiint nrnod(NOD *p){if(p!=NULL) return 1+nrnod(p->st)+nrnod(p->dr);else return 0;}// Determinarea numarului de niveluri ale arboreluiint inaltime(NOD *p){int stanga, dreapta;if(p!=NULL)

return 1+max(inaltime(p->st),inaltime(p->dr));else return 0;}// Numararea frunzelorint greutate (NOD *p, int *a){

if(p!=NULL){

greutate(p->st, a);if((p->st==NULL) && (p->dr==NULL)) (*a)++;greutate(p->dr, a);

}return (*a);

}//Arbore in/completvoid compl (NOD *p){

if(p!=NULL)

Page 42: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 44

{compl(p->st);if((p->st==NULL) && (p->dr!=NULL)){

printf("Nu este complet!");return;

}if((p->st!=NULL) && (p->dr==NULL)){

printf("Nu este complet!");return;

}compl(p->dr);

}}// Programul principalvoid main(){NOD *rad;int nr,nivel,nrnou,nrsters;char complet[10];//clrscr();// Crearea si afisarea RSD, SRD, SDR a unui arborerad=creare();printf("--------------------------------------------------- \n");printf("Parcurgere preordine \n");parc_preord(rad);printf("\n");printf("Parcurgere inordine \n");parc_inord(rad);printf("\n");printf("Parcurgere postordine \n");parc_postord(rad);printf("\n");printf("\n");printf("Afisarea pe niveluri: \n");afisare_nivel(rad);printf("\n");// Stergerea unui nodprintf("--------------------------------------------------- \n");printf("Nodul care se sterge = ");scanf("%d",&nrsters);stergerenod(rad,nrsters);

printf("Parcurgere preordine \n");parc_preord(rad);printf("\n");printf("Parcurgere inordine \n");parc_inord(rad);printf("\n");printf("Parcurgere postordine \n");parc_postord(rad);printf("\n");

printf("Afisarea pe niveluri: \n");afisare_nivel(rad);

Page 43: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 45

// Inserarea unui nodprintf("--------------------------------------------------- \n");printf("Numarul de inserat este=");scanf("%d",&nrnou);inserare(rad,nrnou);

printf("Parcurgere preordine \n");parc_preord(rad);printf("\n");printf("Parcurgere inordine \n");parc_inord(rad);printf("\n");printf("Parcurgere postordine \n");parc_postord(rad);printf("\n");

printf("Afisarea pe niveluri: \n");afisare_nivel(rad);// Nr. noduri & nr. nivelurinr=nrnod(rad);printf("Numarul de noduri este=%d \n",nr);nivel=inaltime(rad);printf("Inaltimea este=%d \n",nivel);}Problema 21/* Ordonarea descrescatoare, prin selectie Heapsort: construim Heap-ul, arborele de selectie, memorat intr-un vector, dupa care se interschmba prima valoare (maximul) cu ultima si in vectorul ramas (n-1) se construieste din nou Heap-ul, s.a.m.d.*/#include<stdio.h>#include <conio.h>void cerne (double a[], int l, int r){int i,j;double x;i=l; j=2*i; x=a[i];while (j<=r){

if (j<r)if (a[j]<a[j+1])

j++;if (x>a[j])

goto gata; a[i]=a[j]; i=j; j=2*i; }

gata: a[i]=x; }void heapsort(double a[], int n){int i, l, r;double x;l=(n/2)+1; r=n;while (l>1){

l--;

Page 44: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 46

cerne(a,l,r);for( i = 1 ; i <= n ; ++i ){

printf (" %0.lf ", a[i]);if (i%10==0)

printf("\n");}

printf("\nApasa o tasta pentru continuare program!\n");getch();}

while(r>1){x=a[1];a[1]=a[r];a[r]=x;r--;cerne(a,l,r);for( i = 1 ; i <= n ; ++i ){

printf (" %0.lf ", a[i]);if (i%10==0)

printf("\n");}

printf("\nApasa o tasta pentru continuare program!\n");getch();}

}void main(void){double sir[1000];int ne, i;//clrscr();printf("HeapSort pentru ordonare crescatoare vector.\n");printf ("Numarul de elemente: ");scanf ("%d",&ne);for ( i = 1 ; i <= ne ; ++i)

{printf (" sir(%d)=", i);scanf ("%lf", &sir[i]);}

heapsort(sir,ne);for( i = 1 ; i <= ne ; ++i ){

printf (" %0.lf ", sir[i]);if (i%10==0)

printf("\n");}

printf("\nPROGRAM TERMINAT! Apasa o tasta-iesire!!!\n");getch();}Problema 22/*

Page 45: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 47

Ordonarea descrescatoare, prin selectie Heapsort: construim Heap-ul, arborele de selectie, memorat intr-un vector, dupa care se interschmba prima valoare (minimul) cu ultima si in vectorul ramas (n-1) se construieste din nou Heap-ul, s.a.m.d.*/#include<stdio.h>#include <conio.h>void cerne (double a[], int l, int r){int i,j;double x;i=l; j=2*i; x=a[i]; while (j<=r){

if (j<r)if (a[j]>a[j+1])

j++;if (x<a[j])

goto gata;a[i]=a[j]; i=j; j=2*i; }

gata: a[i]=x; }void heapsort(double a[], int n){int i, l, r;double x;l=(n/2)+1; r=n;while (l>1){

l--;cerne(a,l,r);for( i = 1 ; i <= n ; ++i ){

printf (" %0.lf ", a[i]);if (i%10==0)

printf("\n");}

printf("\nApasa o tasta pentru continuare program!\n");getch();}

while(r>1){x=a[1];a[1]=a[r];a[r]=x;r--;cerne(a,l,r);for( i = 1 ; i <= n ; ++i ){

printf (" %0.lf ", a[i]);if (i%10==0)

printf("\n");}

Page 46: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 48

printf("\nApasa o tasta pentru continuare program!\n");getch();}

}void main(void){double sir[1000];int ne, i;//clrscr();printf ("Numarul de elemente: ");scanf ("%d",&ne);for ( i = 1 ; i <= ne ; ++i)

{printf (" sir(%d)=", i);scanf ("%lf", &sir[i]);}

heapsort(sir,ne);for( i = 1 ; i <= ne ; ++i ){

printf (" %0.lf ", sir[i]);if (i%10==0)

printf("\n");}

printf("\nPROGRAM TERMINAT! Apasa o tasta-iesire!!!\n");getch();}Problema 23/*Sa se creeze programul de ordonare crescatoare in sir, utilizand metoda de inserare binara, adica: se considera un sir ordonat, format initial din primul element din sirul initial, si un sir neordonat, format din restul elementelor sirului, din care se iau pe rand celelalte elemente si li se cauta, de la dreapta la stanga, pozitia in sirul ordonat, construit tot in sirul initial. Cautarea se face utilizand metoda "binara".*/#include<stdio.h>#include <conio.h>int ncomp=0, nins=0; void sort_ins_binara ( double a[], int n ){double x;int i, j, s, d, m;for (i=1; i<n; ++i)

{x=a[i]; s=0; d=i-1;while (s <= d)

{ncomp++;m=(s+d)/2; if (x < a[m])

d=m-1; else

Page 47: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 49

s=m+1; }

for (j=i-1; j>=s; --j, nins++) a[j+1]=a[j];

a[s]=x;

}}void main(void){double sir[100]; int ne,i;//clrscr();printf("Numar elemente:");scanf("%d", &ne);for(i=0; i<ne; i++)

{printf("sir(%d)= ", i+1);scanf("%lf", &sir[i]);}

printf("Sirul ordonat este: \n");sort_ins_binara(sir , ne);for (i=0;i<ne;i++)

{printf(" sir (%2d) = %lf \n", i+1, sir[i]);if ((ne+1)%4==0)

printf("\n");}

printf("\n");printf("Ordonarea s-a realizat prin %d comparatii si %d deplasari\n",

ncomp, nins);}Problema 24/* Sa se creeze programul de ordonare crescatoare in sir, utilizand metoda de inserare directa, adica:se considera un sir ordonat, format initial din primul element din sirul initial, si un sir neordonat, format din restul elementelor sirului, din care se iau pe rand celelalte elemente si li sa cauta, de la dreapta la stanga, pozitia in sirul ordonat, construit tot in sirul initial.*/

#include <stdio.h>#include <conio.h>int ncomp=0, nins=0;void sort_ins_direct (double a[], int n){double x;int i, j;for (i=1; i<n; ++i)

{ x=a[i];

j=i-1;

Page 48: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 50

while (x < a[j] && j >= 0) {

a[j+1]=a[j]; j--;

ncomp++; nins++; } a[j+1]=x;

}}void main(){double sir[100];int ne, i;//clrscr();printf("Numar elemente:");scanf("%d", &ne);for(i=0; i<ne; i++)

{printf("sir(%d)= ", i+1);scanf("%lf", &sir[i]);}

sort_ins_direct (sir, ne); printf("\n Sirul ordonat:\n");for(i=0; i<ne; i++)

{ printf(" sir(%d)=%5.2lf ", i+1, sir[i]); if ( (i+1) %5 == 0 )

printf("\n");}

printf("\n");printf("Ordonarea s-a realizat prin %d comparatii si %d deplasari\n",

ncomp, nins);}Problema 25/* Ordonare utilizand metoda MergeSort (interclasare).*/

#include <stdio.h>#include <conio.h>#define DIM 20void MergeSort (int v[], int p, int q){int m, aux;void Interclasare(int [], int, int, int);if (q-p <= 1){

if (v[p]>v[q]){aux=v[p];v[p]=v[q];v[q]=aux;

Page 49: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 51

}}

else{m=(p+q)/2;MergeSort(v, p, m);MergeSort(v, m+1, q);Interclasare(v, p, q, m);}

}void Interclasare (int v[], int p, int q, int m){int i=p, j=m+1, k=0;int *u=(int *) malloc (DIM * sizeof(int)); while (i<=m && j<=q){

if (v[i] <= v[j]){u[k]=v[i];i++; k++;}

else{u[k]=v[j];j++; k++;}

}if (i <= m)

for (j=i; j<=m; j++){u[k]=v[j];k++;}

elsefor (i=j; i<=q; i++){

u[k]=v[i];k++;}

k=0;for (i=p; i<=q; i++){

v[i]=u[k];k++;}

free(u); }void scrie_vector(int vect[], int d){int i;for (i=0; i<d; i++)

printf("%5d,", vect[i]);}void main(){int vector[]={10, 5, 6, 12, -3, 7, 11, 17, 9, 4, 3,};int ne=11;//clrscr();

Page 50: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 52

MergeSort(vector, 0, ne-1);scrie_vector(vector, ne);printf("\nApasati o tasta pentru a termina programul!\n");getch();}Problema 26/* Sortarea unui vector utilizand algoritmul QuickSort, iterativ.*/#include<stdio.h>#include<conio.h>#define DIM 100typedef int VECTOR[DIM];int ncomp=0, ninv=0;void cit_vect(int n, VECTOR v){int i;for(i=0; i<n; i++)

{printf("v[%d]=", i+1);scanf("%d", &v[i]);}

}void scrie_vect(int n, VECTOR v){int i;for(i=0; i<n; i++)

printf("v[%d]=%d\n", i+1, v[i]);}void QuickSortit (VECTOR a, int n){int s, d, i, j, is, x, t;struct st_stiva {int s, d;}; struct st_stiva stiva[DIM]; is=1; stiva[is].s=0; stiva[is].d=n-1; d=n-1; do{

s=stiva[is].s; d=stiva[is].d; is--;do {i=s; j=d;

x=a[(s+d)/2];do {

while (a[i]<x) i++, ncomp++;while (a[j]>x) j--, ncomp++;if (i<=j)

{t=a[i];a[i]=a[j];a[j]=t;i++; j--;ninv++;}

} while(i<=j);if (i<d){

is++; stiva[is].s=i;

Page 51: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 53

stiva[is].d=d;}

d=j;} while (s<d);

}while (is>0);}void main(void){int n;VECTOR v;//clrscr();printf("Programul ordoneaza (sorteaza) un vector cu alg. QuickSort.\n");printf("Dimensiune vector, n=");scanf("%d", &n);cit_vect(n, v);QuickSortit (v, n);printf("\nVectorul ordonat este:\n");scrie_vect(n, v);printf("Sortarea s-a realizat dupa %d comparatii si %d inversiuni\n",

ncomp, ninv);getch();}Problema 27/* Sortarea unui vector utilizand algoritmul QuickSort.*/

#include<stdio.h>#include<conio.h>#define DIM 100typedef int VECTOR[DIM];int ncomp=0, ninv=0;void cit_vect(int n, VECTOR v){int i;for(i=0; i<n; i++)

{printf("v[%d]=", i+1);scanf("%d", &v[i]);}

}void scrie_vect(int n, VECTOR v){int i;for(i=0; i<n; i++)

printf("v[%d]=%d\n", i+1, v[i]);}void QuickSort(VECTOR a, int s, int d){int i, j, m, x, temp;i=s;j=d;m=(s+d)/2;x=a[m];do

{while (a[i]<x) i++, ncomp++;

Page 52: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 54

while (a[j]>x) j--, ncomp++;if (i<=j)

{temp=a[i];a[i]=a[j];a[j]=temp;i++;j--;ninv++;}

}while(i<=j);if(s < j) QuickSort(a, s, j);if(i < d) QuickSort(a, i, d);}void main(void){int n;VECTOR v;//clrscr();printf("Programul ordoneaza (sorteaza) un vector cu alg. QuickSort.\n");printf("Dimensiune vector, n=");scanf("%d", &n);cit_vect(n, v);QuickSort(v, 0, n-1);printf("\nVectorul ordonat este:\n");scrie_vect(n, v);printf("Sortarea s-a realizat dupa %d comparatii si %d inversiuni\n",

ncomp, ninv);getch();}Problema 28/* Sa se creeze programul care ordoneaza un vector prin selectie directa, utilizand pentru aceasta determinarea minimului si a pozitiei lui, la fiecare iteratie si realizand o singura inversiune intre acestminim si valoarea a[i], corespunzatoare iteratiei curente; se determina si numarul de comparatii si

inversiuni realizate.*/

#include<stdio.h>#include <conio.h>int ncomp=0, ninv=0; void sort_sel_direct ( double a[], int n ){double x;int i, j, k;for ( i = 0 ; i < n-1 ; ++i ){k = i;x = a[i];for ( j = i+1 ; j < n ; ++j, ncomp++ )

if (a[j] < x){

Page 53: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 55

k = j;x = a[k];}

a[k] = a[i];a[i] = x;ninv++;}

}void main(){double sir[100];int ne,i, nl=0;

//clrscr();printf("Numar elemente:");scanf("%d",&ne);for(i=0;i<ne;i++)

{printf("sir(%d)=",i+1);scanf("%lf",& sir[i]);}

sort_sel_direct(sir,ne); for(i=0;i<ne;i++)

{printf(" sir(%2d)=%5.1lf",i+1,sir[i]);nl++;if ( nl % 5 == 0 )

printf("\n");}

printf("\n");printf("Ordonarea s-a realizat prin %d comparatii si %d inversiuni\n",

ncomp, ninv);}Problema 29/*Sa se creeze programul de ordonare crescatoare sir, utilizand metoda de selectie directa, adica: din

sirul initial se pune valoarea minima pe prima pozitie, apoi pentru subsirul ramas, [2,n], se pune valoarea minima pe pozitia 2, s.a.m.d, prin interschimbari multiple; pentru fiecare valoare, sir[i], ori de cate ori se determina o valoare sir[j]<sir[i], se inverseaza cele doua valori (se determina si numarul de comparatii si inversiuni realizate pentru ordonare).*/#include<stdio.h>#include <conio.h>int ncomp=0, ninv=0; void sort_sel_dir (double sir[], int nrelem){int i, j;double aux;for( i = 0; i < nrelem-1; ++i)

Page 54: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 56

for( j = i+1; j < nrelem ; ++j, ncomp++){if ( sir[i] > sir[j] )

{aux = sir[i];sir[i] = sir[j];sir[j] = aux;ninv++;}

}}void main(void){double sir[1000];int ne, i;//clrscr();printf ("Numarul de elemente: ");scanf ("%d",&ne);for ( i = 0 ; i < ne ; ++i)

{printf (" sir(%2d)=", i+1);scanf ("%lf", &sir[i]);}

sort_sel_dir(sir,ne);for( i = 0 ; i < ne ; ++i ){

printf (" sir(%2d)=%5.2lf ", i+1, sir[i]);if ((i+1)%4==0)

printf("\n");}

printf("\n");printf("Ordonarea s-a realizat prin %d comparatii si %d inversiuni\n",

ncomp, ninv);}Problema 30/* Sa se creeze programul de ordonare (sortare) vector utilizand metoda "ShakerSort".*/#include<stdio.h>#include<conio.h>typedef int VECTOR[30];int ncomp=0, ninv=0; void cit_vect(int n, VECTOR v){int i;for(i=0; i<n; i++)

{printf("v[%d]=", i+1);scanf("%d", &v[i]);}

}void scrie_vect(int n, VECTOR v){int i;

Page 55: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 57

for(i=0; i<n; i++)printf("v[%d]=%d\n", i+1, v[i]);

}void shaker(int n, VECTOR v){int t, i, k, s, d;d=n-2; s=0; k=d;do

{for (i=s; i<=d; i++, ncomp++)if (v[i] > v[i+1])

{t=v[i];v[i]=v[i+1];v[i+1]=t;k=i;ninv++;}

d=k-1;for (i=d; i>=s; i--, ncomp++)

if (v[i+1] < v[i]) {t=v[i];v[i]=v[i+1];v[i+1]=t;k=i;ninv++;}

s=k+1;}while(s <= d);

}void main(void){int n;VECTOR v;//clrscr();printf("\nProgramul ordoneaza (sorteaza) un vector, metoda \"Shaker\".\n");printf("\tDimensiune vector, n= ");scanf("%d",&n);cit_vect(n,v);shaker(n,v);printf("\nSirul ordonat este:\n");scrie_vect(n,v);printf("Ordonarea s-a realizat prin %d comparatii si %d deplasari\n",

ncomp, ninv);printf("\n\tApasati o tasta pentru a termina programul\n");getch();}Problema 31/*Sa se creeze programul ordoneaza un sir de valori prin metoda inversiunilor (bulelor) - forma clasica.*/#include <stdio.h>#include <conio.h>int ncomp=0, ninv=0; void sort_met_bulelor (double a[], int n)

Page 56: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 58

{double x;int i, j;for (i=1; i<n; i++)

for (j=n-1; j>=i; j--, ncomp++)if (a[j-1] > a[j])

{x=a[j-1];a[j-1]=a[j];a[j]=x;ninv++;}

}void main(){double sir[100];int ne,i, nl=0;//clrscr();printf("Numar elemente:");scanf("%d", &ne);for(i=0; i<ne; i++) {printf("sir(%d)=",i+1);

scanf("%lf", &sir[i]);}

sort_met_bulelor (sir, ne);for(i=0; i<ne; i++)

{printf("sir(%2d)=%5.1lf ", i+1, sir[i]);nl++;if (nl % 5 == 0)

printf("\n");}

printf("\n");printf("Ordonarea s-a realizat prin %d comparatii si %d deplasari\n",

ncomp, ninv);}Problema 32/* Sa se creeze programul prin care se sorteaza indecsii unui tablou de tip structura, care contine date pentru un numar de studenti (nume, prenume si media) asociat acestui tablou definim un tablou cu indecsii tabloului de studenti; vom sorta studentii dupa medii prin intermediul tabloului de indecsi, iar sortarea indicilor se va face utiliznd algoritmul ShakerSort.*/#include <stdio.h>#define DIM 100#include <conio.h>struct tip_struct

{char nume_prenum [DIM];

Page 57: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 59

float medie;};

void main(void){struct tip_struct stud [100];int ind[100]; int i, ns;float f;void ShakerSort (struct tip_struct tab[], int index[], int n);//clrscr();printf("Numarul de studenti:");scanf("%d", &ns);f=0.0; fflush(stdin);for (i=0; i<ns; i++)

{printf("Numele si prenumele studentului %d: ", i+1);gets(stud[i].nume_prenum);printf("Media notelor sale: ");scanf("%f", &f);stud[i].medie=f;while (getchar() != '\n');}

for (i=0; i<ns; i++)ind[i] = i;

ShakerSort (stud, ind, ns);printf("Lista ordonata cu numele / prenumele si media studentilor\n");for (i=0; i<ns; i++)

printf("%s %.2f\n", stud[ind[i]].nume_prenum,stud[ind[i]].medie);

}void ShakerSort (struct tip_struct tab[], int index[], int n){int i, s, d, k, t;d=n-2; s=0; k=d;do {

for (i=s; i<=d; i++)if (tab[index[i]].medie < tab[index[i+1]].medie)

{t=index[i];index[i]=index[i+1];index[i+1]=t;k=i;}

d=k-1;for (i=d; i>=s; i--)

if (tab[index[i+1]].medie > tab[index[i]].medie){t=index[i];

Page 58: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 60

index[i]=index[i+1];index[i+1]=t;k=i;}

s=k+1;} while (s <= d);

}Problema 33/* Sa se creeze programul care ordoneaza un vector cu metoda Shell. */#include <stdio.h>#include <conio.h>#define N_MAX 100typedef double VECTOR [N_MAX];int ncomp=0, ninv=0;void Sort_Shell (VECTOR v, int dim){int i, pas, inv;double a;pas = dim;while (pas >1 )

{pas=pas/2 ;do

{inv=0 ; for (i=0; i < dim-pas; i++)

{ncomp++;if (v[i] > v[i+pas])

{a=v[i+pas];v[i+pas]=v[i];v[i]=a;inv=1;ninv++;}

}} while (inv);

}}void main (void){VECTOR sir, a;int n, i, j , inv ;//clrscr();printf ("Numarul de elemente ale sirului (<=100): " ) ;scanf ("%d", &n) ;for (i=0; i<n; ++i)

Page 59: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 61

{printf ("sir[%2d]= ", i+1);scanf ("%lf", &sir[i]) ;}

Sort_Shell(sir, n);printf("\nVectorul ordonat este:\n");for (i=0; i<n; ++i){

printf ("sir[%2d]=%5.2lf ", i+1, sir[i]);if ((i+1)%4==0)

printf("\n");}

printf("\nSortarea s-a realizat dupa %d comparatii si %d inversiuni\n",ncomp, ninv);

getch();}Problema 34/*Problema "fotografiei": determina numarul de obiecte dintr-o fotografie. Obiectele din fotografie

sunt codificate cu 1, iar celelalte sunt 0. Pornind de la prima unitate determinate se cauta unitati adiacente pe cele 8 directii, care sunt puse pe 0 eliminandu-se astfel obiectul identificat.Functia main() reapeleaza functia "obiect" pentru unitatile ramase.*/#include <stdio.h>#include <conio.h>#define N 10#define M 15int F[N][M] = {{0, 0, 0, 0, 0, 0, 0},

{ 0, 1, 0, 1, 0, 1, 0},{ 0, 0, 0, 0, 0, 0, 0},{ 0, 1, 0, 0, 1, 0, 0},{ 0, 0, 1, 0, 0, 1, 0},{ 0, 0, 1, 1, 0, 1, 0},{ 0, 0, 0, 0, 0, 0, 0},};

int i, j, n=5, m=5;void obiect (int i, int j, int F[N][M]){if (F[i][j]==1){

F[i][j]=0;obiect(i-1, j, F);obiect(i-1, j+1, F);obiect(i, j+1, F);obiect(i+1, j+1, F);obiect(i+1, j, F);obiect(i+1, j-1, F);obiect(i, j-1, F);obiect(i-1, j-1, F);}

}

Page 60: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 62

void main (void) {int il, ic, nr_ob=0; //clrscr();printf("Dimensiuni fotografie (matrice), linii, coloane: ");scanf("%d%d", &n, &m);printf("Citire fotografie:\n");for (il=1; il<=n; il++)

for (ic=1; ic<=m; ic++){printf("F[%d, %d]=", il, ic);scanf("%d", &F[il][ic]);

}for (ic=1; ic<=m; ic++){

F[0][ic]=0;F[n+1][ic]=0;}

for (il=1; il<=m; il++){F[il][0]=0;F[il][m+1]=0;}

printf("\nFotografia are urmatoarea configuratie:\n\n");for (il=1; il<n+1; il++){

printf("\t");for (ic=1; ic<m+1; ic++)

printf("%2d", F[il][ic]);printf("\n\n");}

printf("\nCoordonate obiecte (stanga-sus):\n");do

{il=0; do {

il++;ic=0;do

ic++;while (ic<m+1 && F[il][ic]==0);

}while (il<n+1 && F[il][ic]==0);if (F[il][ic] && ic<m+1 && il<n+1){

printf("\n\tObiect %d: (%d,%d)\n", nr_ob+1, il, ic);obiect(il, ic, F);nr_ob++;}

}while (il<n+1 || ic<m+1); printf("\n\tNumar obiecte: %i\n", nr_ob);printf("\nApasati ENTER pentru a termina programul !");getch();}Problema 35/*

Page 61: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 63

Problema comis-voiajorului, utilizand metoda Greedy.*/#include <stdio.h>#include <conio.h>#define DIM_MAX 6void main(){int dist[DIM_MAX][DIM_MAX], muchie_sel[DIM_MAX];int n, i, j, isel=0, nsel=0, distmin;//clrscr();printf("Numarul total de orase de parcurs de comis-voiajor: ");scanf("%d", &n);printf("Specificati pentru ruta distanta:\n");for(i=0; i<n-1; i++){

for (j=i+1; j<n; j++){printf("Distanta (%d, %d)= ", i+1, j+1);scanf("%d", &dist[i][j]);dist[j][i]=dist[i][j];}

muchie_sel[i]=0;}

do {i=0;while (muchie_sel[i] || i==isel)

i++;distmin=dist[isel][i];}while (nsel!=n);

getch();}Problema 36/*Sa se creeze programul care furnizeaza o solutie (prima) pentru problema asezarii a 8 regine pe tabla

de sah, astfel incat nici una dintre ele sa nu o atace pe alta (prima regina este amplasata in pozitia (1,1) .*/#include <stdio.h>#include <conio.h>int a[9] = {0, 1, 1, 1, 1, 1, 1, 1, 1}; int b[17] = {0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};int c[15] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};int x[9]; void incearca (int i, int *pq){int j;j=0;do

{j++; *pq=0; if (a[j] && b[i+j] && c[i-j+7])

Page 62: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 64

{x[i]=j; a[j]=0; b[i+j]=0; c[i-j+7]=0; if (i < 8)

{incearca (i+1, pq); if ( !(*pq) )

{a[j]=1; b[i+j]=1; c[i-j+7]=1;}

}else

*pq=1; }

}while (!(*pq) && j !=8); }void main (void){int i, q;//clrscr();incearca (1, &q);for (i=1; i<= 8; i++)

printf("%4d", x[i]);printf("\n");}Problema 37/* Sa se creeze programul care furnizeaza toate solutiile pentru problema asezarii a 8 regine pe tabla de sah, astfel incat nici una dintre ele sa nu o atace pe alta (prima regina este amplasata in pozitia (1,1).*/#include <stdio.h>#include <conio.h>int a[9] = {0, 1, 1, 1, 1, 1, 1, 1, 1}; int b[17] = {0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};int c[15] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};int x[9]; int ntotsol=0; void afiseaza (void){int k;printf("Sol. %2d: ", ntotsol+1);for ( k = 1; k <= 8; k++)

printf("%4d", x[k]);printf("\n");ntotsol++; if (ntotsol%20 == 0){

printf("\nProgramul (si afisarea) continua! Apasati o tasta!\n");getch();

Page 63: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 65

}}void incearca (int i){int j;for (j=1; j<=8; j++)

if (a[j] && b[i+j] && c[i-j+7]){x[i]=j; a[j]=0; b[i+j]=0; c[i-j+7]=0; if ( i < 8 )

incearca (i+1);else

afiseaza ();a[j]=1; b[i+j]=1; c[i-j+7]=1;}

}void main (void){//clrscr();incearca (1);printf("\nNumarul tota de solutii gasite este %4d.\n", ntotsol);printf("\nProgramul s-a terminat! Apasati o tasta!\n");getch();}Problema 38/*Sa se creeze un program Sudoku pentru "acoperirea" unui careu de 81 casute (9*9) din care o parte sunt fixate, dupa urmatoarea regula: orice linie, coloana sau patrat de 3*3 casute sa contina o singura data fiecare cifra cuprinsa intre 1 si 9. Verificarea incrucisata a liniilor coloanelor si patratelor mici de 3*3 ofera indicii pentru gasirea solutiei se determina si afiseaza prima solutie gasita.*/#include <stdio.h>#include <conio.h>#define N 9#define NSQ N*N// N - dimensiunea careului de joc; NSQ=N^2;int q;long int nr_incercari;int si[N][N]={ {8,0,3,0,0,9,1,0,0},

{0,0,9,0,0,1,0,0,0},{6,0,0,0,4,0,0,0,8},{0,0,0,6,0,7,0,5,0},{3,0,6,0,0,0,2,0,9},{0,7,0,9,0,3,0,0,0},{5,0,0,0,7,0,0,0,2},{0,0,0,1,0,0,7,0,0},{0,0,1,4,0,0,8,0,3}};

Page 64: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 66

int s[N][N];int vp[NSQ][N+1]; void init_joc(){int i, j, l, c, il, ic, nr1;//clrscr();printf("\nInitializare careu de joc:\n");/*for (i=0; i<N; i++){ // initializare careu de joc

printf("Valorile pentru linia %d (separate prin spatii): ", i+1);for (j=0; j<N; j++)

scanf("%d", &si[i][j]);}*/

//clrscr();for (i=0; i<N; i++)

{for (j=0; j<N; j++)printf("%4d", si[i][j]);

printf("\n");}

for (i=0; i<NSQ; i++){vp[i][0]=0;for (j=1; j<=N; j++)

vp[i][j]=1; l=i/N; c=i%N;if (si[l][c]==0)

{for (il=0; il<N; il++)

if (si[il][c]) vp[i][si[il][c]]=0;

for (ic=0; ic<N; ic++) if (si[l][ic])

vp[i][si[l][ic]]=0;l=(i/N/3)*3; c=(i%N/3)*3;for (il=l; il<l+3; il++)

for (ic=c; ic<c+3; ic++) if (si[il][ic])

vp[i][si[il][ic]]=0; }

else{for (ic=1; ic<=N; ic++)

vp[i][ic]=0;vp[i][0]=-1;vp[i][si[l][c]]=1;}

nr1=0;for (j=1; j<=N; j++)

if (vp[i][j]) nr1++;

if (nr1==1)vp[i][0]=-1;

Page 65: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 67

}for (i=0; i<N; i++)

for (j=0; j<N; j++) s[i][j]=si[i][j];

//clrscr();/*printf("Matricea numerelor permise pentru fiecare pozitie din careu:\n");for (i=0; i<NSQ; i++){

if (i%18==0) // se continua afisarea dupa un numar de linii afisate {printf("\nContinua afisarea dupa apasarea unei taste\n"); getch(); /clrscr(); }printf("Pozitia [%d,%d] : ", i/N+1, i%N+1);printf("% d ", vp[i][0]);for (j=1; j<=N; j++)

if (vp[i][j])printf("%d ", j);

elseprintf("%d ", 0);

printf("\n");} */

}int valid(int ip, int k){int l, c, i, j;l=ip/N; c=ip%N;for (i=0; i<N; i++)

if (k==s[i][c]) return 0;

for (j=0; j<N; j++) if (k==s[l][j])

return 0; l=(ip/N/3)*3; c=(ip%N/3)*3;for (i=l; i<l+3; i++)

for (j=c; j<c+3; j++) if(k==s[i][j])

return 0;return 1; }void incearca (int i, int *pq){int k, x, y, q1=0;k = 0;x=i/N; y=i%N; do {k++; if (k<=9 && vp[i][0]==-1){

if(vp[i][k]){s[x][y]=k;q1=1;if (i<NSQ-1){

Page 66: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 68

incearca(i+1, &q1);if (!q1)

{if(vp[i][0]!=-1)s[x][y]=0;

nr_incercari++; }

}else

q1 = 1;}

} else if (k<=9 && vp[i][k]){

q1 = 0;if (k<=N && valid(i,k))

{s[x][y] = k;if (i < NSQ-1)

{incearca (i+1, &q1);if (!q1)

{if(vp[i][0]!=-1) s[x][y]=0;

nr_incercari++; }

}else

q1 = 1;}

} } while (!q1 && k<=N); *pq = q1; }void main (void) {int i, j;init_joc();for (i=0; i<N; i++)

for(j=0; j<N; j++)s[i][j]=si[i][j];

printf("Careul initial este urmatorul:\n");for (i=0; i<N; i++)

{for (j=0; j<N; j++)if (s[i][j])

printf("%2d", s[i][j]);else

printf(" ");printf("\n");}

incearca(0, &q);if (!q)

Page 67: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 69

printf("Problema nu are solutie !!!\n");else

{printf("\nSolutia finala este urmatoarea:\n");for (i=0; i<N; i++)

{for (j=0; j<N; j++)printf("%2d", s[i][j]);

printf("\n");}

printf("\nNumarul total de incercari a fost de: %ld\n",nr_incercari);}

printf("Pentru terminare apasati o tasta!\n");getch();}Problema 39/* Sa se creeze programul care incarca un rucsac, utilizand metoda Greedy(problema continua arucsacului).*/#include <stdio.h>#include <conio.h>#define DIM_MAX 20void main(){float p[DIM_MAX], g[DIM_MAX], ef[DIM_MAX];int n, i, j, inv, ordonat[DIM_MAX];float gr, castig;//clrscr();printf("Capacitate rucsac (greutate admisa): ");scanf("%f", &gr);printf("Numarul de obiecte ce trebuie incarcate in rucsac (disponibile): ");scanf("%d", &n);printf("Specificati pentru fiecare obiect greutatea/profitul:\n");for(i=0;i<n;i++)

{printf("Greutate(%d)= ",i+1);scanf("%f", &g[i]);printf("Profit(%d) = ",i+1);scanf("%f", &p[i]);ordonat[i]=i;ef[i]=p[i]*g[i];}

do{inv=0;for (i=0; i < n-1; i++)

if (ef[ordonat[i]] < ef[ordonat[i+1]]){j=ordonat[i];

Page 68: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 70

ordonat[i]=ordonat[i+1];ordonat[i+1]=j;inv=1;}

} while (inv);castig=0;i=0;printf("\nSe incarca in rucsac:\n");while (gr > 0 && i < n)

{if (gr >= g[ordonat[i]])

{printf("\tObiect %d incarcat in intregime\n", ordonat[i]+1);gr=gr - g[ordonat[i]];castig=castig + p[ordonat[i]];}

else{printf("Obiect %d incarcat in proportie de"

" %.2f %\n", ordonat[i]+1, gr/g[ordonat[i]]*100);castig=castig + p[ordonat[i]]*gr/g[ordonat[i]];gr=0;}

i++;}

printf("\nObiectele incarcate in rucsac sunt urmatoarele:\n");for (j=0; j<i; j++)

printf("\tObiectul: %d, de greutate: %.2f si profit: %.2f\n",ordonat[j]+1, g[ordonat[j]], p[ordonat[j]]);

if (gr){printf("\nSe mai pot incarca obiecte de greutate: %.2f", gr);printf("\n\t\t rucsacul nu este plin, dar nu mai sunt obiecte.\n");}

printf("\nProfitul total obtinut pentru aceasta incarcare: %.2f\n", castig);printf("\nApasati o tasta pentru a termina programul !!!\n");getch();}Problema 40/* Sa se creeze programul care determina cel mai mare subsir crescator, dintr-un sir dat, utilizand "programarea dinamica".*/#include<stdio.h>#include <conio.h>#define DIM 100void main(void){int vmax, v[DIM]={1, 5, 2, 6, 7, 4, 10, 13, 9, 20, 14, 7, 15, 12, 17};int n=15, i, k, max, imax, L[DIM], Lmax;//clrscr();

Page 69: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 71

/*printf("Numar elemente:");scanf("%d", &n);for(i=0; i<n; i++) // citire sir unde caut cel mai mare subsir crescator

{printf("v(%d)= ", i+1);scanf("%d", &v[i]);} */

L[n-1]=1;for (k=n-2; k>=0; k--){

L[k]=1;imax=k; Lmax=1; for (i=k+1; i<n; i++)

if (v[k] <= v[i] && Lmax <= L[i]){ Lmax=L[i]; imax=i;L[k]=L[imax]+1;}

}printf("Vectorul L este urmatorul:\n");for (i=0; i<n; i++)

printf("%3i", L[i]);printf("\n");Lmax=L[0]; imax=0; for (i=1; i<n; i++){

if (Lmax < L[i]){ Lmax=L[i];imax=i;}

}printf("\nSubsirul cel mai lung este (incepe de la poz %d):\n", imax+1);printf("%5d", v[imax]);vmax=v[imax]; Lmax=L[imax]; for (i=imax+1; i<n; i++)

if (vmax <= v[i] && L[i]==Lmax-1){ vmax=v[i]; printf("%5d ", vmax);Lmax--; }

printf("\n\n\tApasati o tasta pentru a termina programul\t!!!\n");getch();}Problema 41/* Sa se creeze programul care permuta liniile dintr-o matrice pentru a ordona crescator valorile de pe diagonala principala a matricei.*/

Page 70: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 72

#include <stdio.h>#include <conio.h>#define NR_MAX 3int a[NR_MAX][NR_MAX];int nl, nc, l, c;int ntotsol=0; void main (void){int lin, col, il, ic, aux;int incearca (int);//clrscr();printf("Programul ordoneaza valorile de pe diagonala unei matrici.\n");printf("Numar de linii/coloane: ");scanf("%d%d", &nl, &nc);printf("\n");for (l=0; l<nl; l++)

for (c=0; c<nc; c++){printf("a[%d,%d]=", l+1, c+1);scanf("%d", &a[l][c]);};

printf("\nApasati o tasat pentru a continua programul\n");getch();for (l=0; l<nl; l++)

for (c=0; c<nc; c++){for (col=0; col<nc; col++)

{aux=a[0][col];a[0][col]=a[l][col];a[l][col]=aux;};

for (lin=0; lin<nl; lin++){aux=a[lin][0];a[lin][0]=a[lin][c];a[lin][c]=aux;};

if (incearca(0)) ntotsol++;printf("\nSolutia %d:\n", ntotsol);for (il=0; il<nl; il++)

{for (ic=0; ic<nc; ic++)

printf("%4d", a[il][ic]);printf("\n");};

printf("\nApasati o tasta pentru a continua programul !\n");getch();

Page 71: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 73

for (col=0; col<nc; col++){aux=a[0][col];a[0][col]=a[l][col];a[l][col]=aux;};

for (lin=0 ;lin<nl; lin++){aux=a[lin][0];a[lin][0]=a[lin][c];a[lin][c]=aux;};

};printf("\nNumarul total de solutii este %d.\n", ntotsol);printf("\nApasati o tasta pentru a termina programul !\n");getch();};int incearca (int i){int lin, col, l, c;int aux, q;lin=col=i;do

{q=0;if ((i > 0 && a[lin][col] >= a[i-1][i-1] ) || (i == 0))

{for (c=0; c<nc; c++)

{aux=a[i][c];a[i][c]=a[lin][c];a[lin][c]=aux;};

for (l=0; l<nl; l++){aux=a[l][i];a[l][i]=a[l][col];a[l][col]=aux;};

if (i < nl-1){q=incearca (i+1);if (!q)

{for (c=0; c<nc; c++)

{aux=a[i][c];a[i][c]=a[lin][c];a[lin][c]=aux;};

for (l=0; l<nl; l++){aux=a[l][i];a[l][i]=a[l][col];

Page 72: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 74

a[l][col]=aux;};

};}

elseq=1;

};if (col == nc-1)

{col=i;lin++;}

elsecol++;

} while (!q && lin < nl && col < nc);return (q);}Problema 42/*Problema 'Turnurilor din Hanoi', rezolvata recursiva.*/

#include <stdio.h>#include <conio.h>enum pozitie { stanga , mijloc , dreapta};void tipareste_pozitie ( enum pozitie poz ){switch ( poz )

{case 0 : printf ( "stanga" );

break;case 1 : printf ( "mijloc" );

break;case 2 : printf ( "dreapta" );}

}void deplasare( enum pozitie sursa , enum pozitie dest ){printf ( "muta un disc din " );tipareste_pozitie ( sursa );printf ( " in " );tipareste_pozitie ( dest );printf ( "\n" );return;}void muta ( int n, enum pozitie sursa, enum pozitie inter, enum pozitie dest ){if ( n > 0 )

{

Page 73: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 75

muta ( n - 1 , sursa , dest , inter );deplasare ( sursa , dest );muta ( n - 1 , inter, sursa , dest );}

}void main (void){int i , nd;//clrscr();printf ( "Nr. de discuri :" );scanf ("%d", &nd);while ( getchar() != '\n' );printf ("Mutarile pt. deplasarea unui turn cu %d discuri sunt :\n", nd);muta ( nd , stanga , mijloc , dreapta );printf("\n\n");}Problema 43/*Sa se creeze programul care determina tabloul coeficientilor binomului (a+b)^n, adica combinbari de

n luate cate k. Tabloul coeficientilor este urmatorul: 0 1 2 3 4 5 6 7 8 1 1 1 2 1 2 1 3 1 3 3 1 4 1 4 6 4 1 5 1 5 10 10 5 1 6 1 6 15 20 15 6 1 7 1 7 21 35 35 21 7 1 care utilizeaza relatiile:C(n,k)=C(n-1,k-1) + C(n-1, k), C(k,k)=1, C(k,1)=1 si C(k,j)=1, pentru j>k

Utilizand "programarea dinamica" vom pastra linia curenta din tablou intr-un vector si vom calcula linia urmatoare din tablou in acelasi vector, de la dreapta la stanga, observand ca un nou termen este suma precedentilor doi, cu exceptia celor doua valori extreme, care sunt 1.*/#include<stdio.h>#include <conio.h>#define DIM 80void main(void){long int c[DIM];int n=15, i, k, d;//clrscr();for (k=0; k<=n; k++){

for (i=k; i>=0; i--)if (i==k)

c[i]=1;else if (i==0)

c[i]=1;else

c[i] += c[i-1];

Page 74: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 76

printf("\n\n%2i", k);d=3; for (i=0; i<=k; i++){

printf("%*li", d, c[i]);if (i < (n+1)/2)

{if(i%2)d++;

}else if((i+1)%2)

d--;}

if ((k+1)%16 == 0){printf("\n\nContinua afisarea dupa apasarea unei taste!\n");getch();}

}printf("\n");printf("\n\n\tApasati o tasta pentru a termina programul\t!!!\n");getch();}Problema 44/*Sa se creeze un program "knight tour": "acoperirea" unei table de sah prin mutarile unui cal, astfel incat fiecare casuta a tablei sa fie parcursa (atinsa) o singura data; se afiseaza prima solutie gasita.*/#include <stdio.h>#include <conio.h>#define N 5#define NSQ N*N#define NrMaxMutCal 8int i, j, q;long int nr_incercari;int h[N+1][N+1];int a[NrMaxMutCal+1]={0, 1, 1, 2, 2, -1, -1, -2, -2};int b[NrMaxMutCal+1]={0, 2, -2, 1, -1, 2, -2, 1, -1};void muta (int i, int x, int y, int *pq){int k, u, v, l, c, q1;k = 0;do {

k = k + 1;u = x + a[k];v = y + b[k];q1 = 0;if ((u >= 1 && u <= N) && (v >= 1 && v <= N) && (h[u][v] == 0))

{h[u][v] = i;if (i < NSQ)

{muta (i+1, u, v, &q1);

Page 75: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 77

if (!q1) {h[u][v] = 0;nr_incercari++; }

}else

q1 = 1;}

} while (!q1 && k < NrMaxMutCal); *pq = q1;}void main (void) {int i, j, q;//clrscr();for (i=1; i<=N; i++)

for (j=1; j<=N; j++) h[i][j] = 0;

h[1][1] = 1;muta( 2, 1, 1, &q);if (!q)

printf("Problema nu are solutie !!!\n");else

{for (i=1; i<=N; i++){for (j=1; j<=N; j++)

printf("%4d", h[i][j]);printf("\n");}

printf("\nNumarul total de incercari a fost de: %ld\n\n",nr_incercari);

}}Problema 45/*Problema taieturilor, exemplu de algoritm "divide et impera". Se considera un dreptunghi dat prin

coltul din stanga jos (x,Y) si dimensiunile sale l-lungime, h-latime/inaltime. In interiorul sau se afla 'n' gauri de coordonate (xg, yg), memorate intr-un vector. Se cere sa se determine un dreptunghi de dimensiuni maxime, care sa nu contina gauri, prin realizarea de decupari/ taieturi verticale sau orizontale ale dreptunghiului initial prin gaurile sale. */

#include <stdio.h>#include <conio.h>#define MAXG 5int n=4;void dreptunghi (int x, int y, int l, int h,

int *px, int *py, int *pl, int *ph, int xg[], int yg[]){int gasit, i;i=0; gasit=0;while (i<n && !gasit)

Page 76: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 78

if (xg[i] > x && xg[i] < x+l && yg[i] > y && yg[i] < y+h)gasit=1;

elsei++;

if (gasit) {dreptunghi(x, y, xg[i]-x, h, px, py, pl, ph, xg, yg);dreptunghi(xg[i], y, l+x-xg[i], h, px, py, pl, ph, xg, yg);dreptunghi(x, y, l, yg[i]-y, px, py, pl, ph, xg, yg);dreptunghi(x, yg[i], l, h+y-yg[i], px, py, pl, ph, xg, yg);}

else if (l*h > *pl* *ph) {*px=x; *py=y;*pl=l; *ph=h;}

}void main (void){int xg[MAXG]={1, 2, 3, 4}, yg[MAXG]={1, 2, 3, 4};int l=5, h=5;int *px, *py, lmax=0, hmax=0;//clrscr();dreptunghi(0, 0, l, h, px, py, &lmax, &hmax, xg, yg);printf("\nDreptunghiul maxim este: (x,y) stanga-jos = (%d, %d)\n\t\t\t"

"lung (dx) = %d, latime (dy sau h) = %d\n", *px, *py, lmax, hmax);printf("\nApasati o tasta pentru a termina programul !!!\n");getch();}Problema 46/*Creeaza programul care citeste un vector de valori intregi si determina daca o anumita valoarea

(suma dorita) se poate furniza prin insumarea valorilor din vector, si ofera toate solutiile posibile-exemplu de backtracking.*/

#include <stdio.h>#include <conio.h>#define MAXV 16typedef struct

{int nval, val[MAXV]; long rest;int nrsol;unsigned sel;} TDate;

int nle=0; void AfiSolutie (TDate *a){int i;unsigned x;printf ("%2i:", ++a->nrsol);for (x = a->sel, i = 0; i < a->nval; i++, x >>= 1)

Page 77: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 79

if (x & 1)printf ("%4i", a->val[i]);

elseprintf(" -");

printf("\n");nle++;if(nle%23==0)

{printf("Se continua afisarea dupa apasarea unei taste!\n");getch();}

}void Cauta (TDate *a, int iv){if (a->rest == 0)

{AfiSolutie (a); return;}for (; iv < a->nval ; iv++)

if (a->rest >= a->val[iv] ) {a->sel += (1 << iv);a->rest -= a->val[iv]; Cauta (a, iv+1); a->sel -= (1 << iv); a->rest += a->val[iv]; }

}void main (){int i;long Suma;TDate x;//clrscr();printf ("Introduceti valori, terminand cu 0 sau caracter nenumeric:\n");for (i = 0; i < MAXV; i++)

if (scanf("%i", &(x.val[i])) < 1 || x.val[i] == 0)break;

if (!i){ printf ("Lipsa date!!!\n"); exit(1); }

x.nval = i;printf("\nAti introdus %u valori:\n", x.nval);for (i = 0; i < x.nval; i++)

printf ("%5i", x.val[i]);printf ("\n");for (;;)

{printf ("\nSuma dorita de construit (calculat) cu valori ""din vector\n\t(oprire program orice caracter nenumeric): ");

fflush(stdin);if (!scanf ("%ld", &Suma))

break;x.sel = 0; x.rest = Suma; x.nrsol = 0;Cauta (&x, 0); if (! x.nrsol)

Page 78: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 80

printf ("Nu exista solutie !\n");}

}Problema 47/*Sa se creeze problema "labirintului": iesirea dintr-un labirint specificat printr-o matrice L, in care se memoreaza valorile zecimale ale codificarilor binare ale drumului spre iesire, si anume: fiecare directie care duce spre iesire e codificata cu 1, iar restul cu 0; deci pentru o casuta oarecare se considera directiile: sus, dreapta, jos si stanga, in aceasta ordine; de exemplu daca o camera va avea directii spre iesire sus si stanga, adica 1001, in binar, se va memora valoarea 9; matricea va fi completata cu 2 linii si 2 coloane care vor contine valorile 16 (iesire din labirint). Drumul spre iesire va fi memorat in matricea d[2][n*m], pe prima linie i, iar pe cea de-a doua j, pentru drumul catre iesire din pozitia k.*/#include <stdio.h>#include <conio.h>#define N 10#define M 15#define DIM (N-1)*(M-1)int L[N][M] = {{16, 16, 16, 16, 16, 16, 16},

{ 16, 0, 2, 1, 1, 0, 16},{ 16, 0, 2, 0, 8, 0, 16},{ 16, 0, 2, 4, 8, 0, 16},{ 16, 1, 7, 4, 2, 0, 16},{ 16, 0, 2, 0, 2, 0, 16},{ 16, 16, 16, 16, 16, 16, 16},};

int d[2][DIM];int i, j, n=5, m=5, nr_sol=0, nse=4;void tiparire (int k, int d[2][DIM]){int h;nr_sol++;printf("\nSolutia %d:\n", nr_sol);for (h=1; h<=k; h++){

printf("[%d,%d]-> ", d[0][h], d[1][h]);if (h%8==0)

printf("\n");}

printf("\n");if (nr_sol % nse == 0)

{printf("\n");printf("Apasati ENTER pentru a continua afisarea");getch();

// clrscr();}

}void iesire (int k, int i, int j, int L[N][M], int d[2][DIM]){int gasit, h;

Page 79: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 81

if (L[i][j] == 16)tiparire(k, d);

else{k++;d[0][k]=i;d[1][k]=j;gasit=0;for (h=1; h<=k-1; h++)

if (d[0][h] == d[0][k] && d[1][h] == d[1][k])gasit=1;

if (!gasit)for (h=1; h<=4; h++)

switch (h){case 1: if (L[i][j] & 8)

iesire(k, i-1, j, L, d);break;

case 2: if (L[i][j] & 4)iesire(k, i, j+1, L, d);

break;case 3: if (L[i][j] & 2)

iesire(k, i+1, j, L, d);break;

case 4: if (L[i][j] & 1)iesire(k, i, j-1, L, d);

}k--;}

}void main (void) {int il, ic;//clrscr();printf("Dimensiuni labirint (matrice), linii, coloane: ");scanf("%d%d", &n, &m);for (il=1; il<=n; il++)

for (ic=1; ic<=m; ic++){printf("L[%d, %d]=", il, ic);scanf("%d", &L[il][ic]);

}printf("Punctul de plecare din labirint (i, j): ");scanf("%d%d", &i, &j);for (ic=1; ic<=m; ic++){

L[0][ic]=16;L[n+1][ic]=16;}

for (il=1; il<=m; il++){L[il][0]=16;L[il][m+1]=16;}

Page 80: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 82

printf("\nLabirintul are urmatoarea configuratie:\n\n");for (il=0; il<n+2; il++){

for (ic=0; ic<m+2; ic++)if (il==i && ic==j)

printf(" x");else

printf("%3d", L[il][ic]);printf("\n\n");}

printf("Coordonate punct plecare L[%d,%d]=%d\n", i, j, L[i][j]);iesire(0, i, j, L, d);printf("\nNumar total de solutii: %i\n", nr_sol);printf("Apasati ENTER pentru a termina programul !");getch();}Problema 48/*Sa se creeze programul care determina toate solutiile pentru colorarea celor m muchii ale unui graf cu n noduri, utilizand c culori diferite, cu restrictia ca doua muchii ce se intersecteaza intr-un nod sa nu aiba aceeasi culoare. Graful este reprezentat ca un vector de muchii.*/#include <stdio.h>#include <conio.h>#define DIMN 6#define DIMM 10typedef struct{

int v1, v2;} VECT_MUCHII;

int nr_sol=0;void citire_graf (VECT_MUCHII vm[DIMM+1], int a[DIMN+1][DIMN+1], int *pn, int *pm){int i, j, k;//clrscr();printf("\nDati numar noduri, graf neorientat, n: ");scanf("%d", pn);printf("Nr. de muchii: ");scanf("%d", pm);for (i=1; i<= *pn; i++)

for (j=1; j<=*pn; j++)a[i][j]=0;

printf("\nCitire graf prin muchiile sale.\n");for (k=1; k<= *pm; k++)

{printf("Muchie: varfuri sursa, dest: ");scanf ("%d%d", &vm[k].v1, &vm[k].v2);a[vm[k].v1][vm[k].v2]=a[vm[k].v2][vm[k].v1]=1;

}}void tipar_culoare(int culoare[DIMM+1], VECT_MUCHII vm[DIMM+1], int nm){

Page 81: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 83

int i;for (i=1; i<=nm; i++)

if (vm[i].v1 < vm[i].v2)printf("m(%d-%d)=c%d, ", vm[i].v1, vm[i].v2, culoare[i]);

elseprintf("m(%d-%d)=c%d, ", vm[i].v2, vm[i].v1, culoare[i]);

printf("\n");if ((nr_sol+1)%20==0){

printf("\nAfisarea continua dupa apasarea unei taste !!!\n");getch();}

}int validare_culoare (VECT_MUCHII vm[DIMM+1], int culoare[DIMM+1], int p){int val=1, k;for (k=1; k<p; k++)

if (culoare[k] == culoare [p])if (vm[k].v1==vm[p].v1 || vm[k].v1==vm[p].v2 ||

vm[k].v2==vm[p].v1 || vm[k].v2==vm[p].v2)val=0;

return val; }void incerc_culoare(VECT_MUCHII vm[DIMM+1], int culoare[DIMM+1], int c, int nm, int p){int i, j;for (i=1; i<=c; i++)

{culoare[p]=i;if (validare_culoare(vm, culoare, p))

if (p==nm){tipar_culoare(culoare, vm, nm);nr_sol++;}

elseincerc_culoare(vm, culoare, c, nm, p+1);

}}void main(){VECT_MUCHII vm[DIMM+1];int culoare[DIMM+1], a[DIMN+1][DIMN+1]; int n, nm, c;citire_graf (vm, a, &n, &nm);printf("\nNumarul de culori cu care se coloreaza: ");scanf("%d", &c);incerc_culoare(vm, culoare, c, nm, 1);if(nr_sol)

printf("\nNumarul total de solutii este: %d\n", nr_sol);else

printf("\nProblema nu are solutii");printf("\n");

Page 82: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 84

}Problema 49/* Sa se creeze programul care parcurge optim nodurile dintr-un graf, plecand dintr-un anumit nod, cu un cost (drum) optim. Avem grup de n persoane, in care nu toate se cunosc intre ele(fiecare cunoaste o parte dintre ele); o persoana poseda o carte pe care doreste sa o transmita grupului, pentru a fi citita de toti membrii grupului. Fiecare persoana poate transmite cartea doar acelor persoane pe care le cunoaste. Fiecare persoana citeste si da cartea intr-un anumit interval de timp (zile), ce depinde de persoana careia urmeaza sa-i dea cartea, si care va fi specificat pentru fiecare succesor. Sa se determine o solutie optima, daca exista, astfel incat cartea sa treca pe la fiecare persoana din grup, doar o singura data, iar in final sa ajunga la posesorul cartii, astfel incat timpul dupa care cartea revine la proprietar sa fie minim (optim). Programul afiseaza toate solutiile, dar o retine pe cea optima.*/#include <stdio.h>#include <conio.h>//#include <values.h>#define DIMN 10#define DIMM 100typedef struct{

int vi, vf;int timp;} VECT_MUCHII;

int nr_sol=0, nr_sol_op=0, sol_optima[DIMM+1];void citire_graf (VECT_MUCHII vm[DIMM+1], int a[DIMN+1][DIMN+1], int *pn){int i, j, k, durata, pers, np;//clrscr();printf("\nDati numar noduri, graf orientat, n: ");scanf("%d", pn);for (i=1; i<= *pn; i++)

for (j=1; j<=*pn; j++)a[i][j]=0;

printf("\nCitire graf prin varfurile (persoanele) sale.\n");for (k=1; k<= *pn; k++)

{vm[k].vi=k;printf("Numarul de persoane cunoscute de persoana (%d): ", k);scanf("%d", &np);for (i=1; i<=np; i++){

printf("\tcunostinta(%d): ", i);scanf("%d", &pers);vm[k].vf=pers;printf("\t\ttransferul %d -> %d dureaza (zile): ", k, pers);scanf("%d", &durata);a[vm[k].vi][vm[k].vf]=durata;}

vm[k].timp=durata;}

printf("\nMatricea costurilor pentru graful introdus este:\n");for (i=1; i<=*pn; i++){

Page 83: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 85

for (j=1; j<=*pn; j++)printf("%3d", a[i][j]);

printf("\n");}

}void init_solutie (int solutie[DIMM+1], int nn){int i;for (i=1; i<=nn; i++)

solutie[i]=0;}

int timp_sol(int a[DIMN+1][DIMN+1], int solutie[DIMM+1], int p){int k, total_timp=0;for (k=1; k<p; k++)

total_timp+=a[solutie[k]][solutie[k+1]];total_timp+=a[solutie[p]][solutie[1]];return total_timp;}void tipar_solutie(int a[DIMN+1][DIMN+1], int solutie[DIMM+1], int p){int i;for (i=1; i<=p; i++)

printf("%d -> ", solutie[i]);printf("%d\t/timp total=%d/ solutie %d\n\n", solutie[1],

timp_sol(a, solutie, p), nr_sol+1);if ((nr_sol+1)%10 == 0){

printf("\nAfisarea continua dupa apasarea unei taste!\n");getch();}

}int validare_solutie (int a[DIMN+1][DIMN+1], int solutie[DIMM+1], int p){int k;if ( !a[solutie[p-1]][solutie[p]] )

return 0;for (k=1; k<p; k++)

if (solutie[k]==solutie[p]) return 0;

return 1;}void copie_sol_optima(int solutie[DIMM+1], int sol_optima[DIMM+1], int nn){int i;for (i=1; i<=nn; i++)

sol_optima[i]=solutie[i];}void incerc_solutie(int a[DIMN+1][DIMN+1], int solutie[DIMM+1],

int n, int p, int varf_init, int *poptim){int i;for (i=1; i<=n; i++)

{solutie[p]=i;

Page 84: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 86

if (validare_solutie(a, solutie, p))if (p==n && a[solutie[p]][solutie[1]] &&

varf_init==solutie[1]){tipar_solutie(a, solutie, p);if (timp_sol(a, solutie, p) < *poptim){

copie_sol_optima(solutie, sol_optima, n);*poptim=timp_sol(a, solutie, p);nr_sol_op=nr_sol+1; }

nr_sol++; }

else incerc_solutie(a, solutie, n, p+1, varf_init, poptim);

solutie[p]=0;}

}void main(){VECT_MUCHII vm[DIMM+1];int sol[DIMM+1], a[DIMN+1][DIMN+1]; int i, n, varf_ini, optim, MAXINT;citire_graf (vm, a, &n);printf("Varful initial (persoana de pornire): ");scanf("%d", &varf_ini);init_solutie(sol, n);printf("\nSolutiile din graf sunt urmatoarele:\n");incerc_solutie(a, sol, n, 1, varf_ini, &optim);if(nr_sol)

{printf("\nNumarul total de solutii este: %d\n", nr_sol);printf("\nSolutia optima este:\n");for (i=1; i<=n; i++)

printf("%d -> ", sol_optima[i]);printf("%d\t/timp total=%d/ solutie %d\n\n", sol_optima[1],

timp_sol(a, sol_optima, n), nr_sol_op);}

elseprintf("\nProblema nu are solutii");

printf("\n");}Problema 50/* Sa se creeze programul care determina daca un graf este eulerian: este un graf conex (parcurg in latime, BF, si daca nu exista varfuri nevizitate este conex) si gradele tuturor varfurilor sunt pare (grad varf = numar de muchii ce contin varful).*/#include <stdio.h>#include <conio.h>#define MAX 20

Page 85: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 87

void cit_graf_no (int grf[][MAX], int &n, int grad[]){int i, j;int v[][MAX]={ {0, 1, 0, 0, 1, 0, 0, 0},

{1, 0, 1, 0, 0, 0, 0, 0},{0, 1, 0, 1, 0, 1, 0, 1},{0, 0, 1, 0, 1, 0, 0, 0},{1, 0, 0, 1, 0, 0, 0, 0},{0, 0, 1, 0, 0, 0, 1, 0},{0, 0, 0, 0, 0, 1, 0, 1},{0, 0, 1, 0, 0, 0, 1, 0}};

printf("\nNumarul de varfuri in graf, n= ");scanf("%d", &n);for (i=0; i<n; i++)

grad[i]=0;for (i=0; i<n; i++)

{grf[i][i]=0;for (j=i+1; j<n; j++)

{grf[i][j]=v[i][j];/*printf("muchie[%d, %d]= ", i+1, j+1);scanf("%d", &grf[i][j]); */grf[j][i]=grf[i][j];if (grf[i][j])

{grad[i]++; grad[j]++;}}

}}void scrie_graf_no (int grf[][MAX], int n, int gd[]){int i, j;printf("\nMatricea grafului este urmatoarea:\n");for (i=0; i<n; i++)

{for (j=0; j<n; j++)

printf("%3d ", grf[i][j]);printf("\n");}

printf("Gradele varfurilor grafului sunt:\n");for (i=0; i<n; i++)

printf("%3d ", gd[i]);printf("\n");}void parcurg_latime (int grf[][MAX], int n, int start, int viz[]){int i, pi, ps, x, c[MAX];for (i=0; i<n; i++)

c[i]=0;for (i=0; i<n; i++)

viz[i]=0;pi=0;

Page 86: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 88

ps=0;c[pi]=start;viz[start]=1;while (ps<=pi)

{x=c[ps];for (i=0; i<n; i++)

if(grf[x][i]==1 && !viz[i]){pi++; c[pi]=i;viz[i]=1;}

ps++;}

}int nevizitat (int viz[], int n){int prim_nev=-1, j=1;while (j<=n && prim_nev==-1)

{if (viz[j]==0)prim_nev=j;

j++;}

return prim_nev;}int conex (int grf[][MAX], int n, int start, int viz[]){parcurg_latime (grf, n, start, viz);if (nevizitat(viz,n)==-1)

return 1;else

return 0;}int grade_pare (int grd[], int n){int i, ok=1;for (i=0; i<n && ok; i++)

if (grd[i] %2)ok=0;

return ok;}void main (void) {int n, g[MAX][MAX], grad[MAX], vizitat[MAX], start;//clrscr();cit_graf_no(g, n, grad);scrie_graf_no(g, n, grad);printf("\n Specificati varful de plecare: ");scanf("%d", &start);if (conex(g, n, start, vizitat))

if (grade_pare(grad, n))printf("\nGraful este conex si eulerian\n");

elseprintf("\nGraful este conex dar nu este eulerian\n");

Page 87: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 89

elseprintf("\nGraful nu este eulerian\n");

getch();}Problema 51/*Sa se scrie programul care contine algoritmul de parcurgere in latime BF a unui graf.*/

#include <stdio.h>#include <conio.h>#define DIMN 10#define DIMM 100void citire_graf (int a[DIMN+1][DIMN+1], int *pn, int *pm){int i, j, k;//clrscr();printf("\nDati numar noduri, graf neorientat, n: ");scanf("%d", pn);printf("Nr. de muchii: ");scanf("%d", pm);for (i=1; i<= *pn; i++)

for (j=1; j<=*pn; j++)a[i][j]=0;

printf("\nCitire graf prin muchiile sale.\n");for (k=1; k<= *pm; k++)

{printf("Muchie, varfuri sursa, dest: ");scanf ("%d%d", &i, &j);a[j][i]=a[i][j]=1;

}}void parcurg_lat_BF (int a[DIMN+1][DIMN+1], int C[DIMM+1], int V[DIMM+1],

int n, int prim, int *pdimV){int k, pi=1, pe=1, v;for (k=1; k<=n; k++)

C[k]=V[k]=0;C[1]=prim;V[prim]=1;while (pe<=pi){

v=C[pe];for (k=1; k<=n; k++)

if (a[v][k] && !V[k]){pi++;C[pi]=k;V[k]=1;}

pe++;}

*pdimV=pi;

Page 88: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 90

}void main(){int a[DIMN+1][DIMN+1]; int C[DIMN+1], V[DIMN+1];int n, nm, primul, dimV, k;citire_graf (a, &n, &nm);printf("\nProgramul parcurge in latime graful.\n");printf("\nSpecificati varful de start pentru parcurgere: ");scanf("%d", &primul);parcurg_lat_BF(a, C, V, n, primul, &dimV);printf("\nParcurgerea in latime este urmatoarea:\n");for (k=1; k<dimV; k++)

printf("%4d - ", C[k]);printf("%4d\n", C[k]);printf("Apasati o tasta pentru a termina programul\n");getch();}Problema 52/* Sa se creeze programul care determina toate nodurile izolate dintr-un graf orientat cu n noduri si m muchii.*/#include <stdio.h>#include <conio.h>#define DIMN 10#define DIMM 100typedef struct{

int vi, vf;} VECT_MUCHII;

void citire_graf (VECT_MUCHII vm[DIMM+1], int a[DIMN+1][DIMN+1],int *pn, int *pm){

int i, j, k;//clrscr();printf("\nDati numar noduri, graf orientat, n: ");scanf("%d", pn);printf("Nr. de muchii: ");scanf("%d", pm);for (i=1; i<= *pn; i++)

for (j=1; j<=*pn; j++)a[i][j]=0;

printf("\nCitire graf prin muchiile sale.\n");for (k=1; k<= *pm; k++)

{printf("Muchia %d, varf initial -> final: ", k);scanf ("%d%d", &vm[k].vi, &vm[k].vf);a[vm[k].vi][vm[k].vf]=1;

}

Page 89: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 91

}void init_nod_iz (int nod_iz[DIMM+1], int nn){int i;for (i=1; i<=nn; i++)

nod_iz[i]=0;}void determin_nod_iz (int a[DIMN+1][DIMN+1], int nod_iz[DIMN+1], int nn){int i, j;for (j=1; j<=nn; j++)

for (i=1; i<=nn; i++)if (a[i][j])

nod_iz[j]++;}void tipar_nod_iz(int nod_iz[DIMM+1], int nn){int i, ni=0;printf("\nNoduri izolate:\n");for (i=1; i<=nn; i++)

if (!nod_iz[i]){printf("%5d", i);ni++;}

printf("\n");if (ni)

printf("Numar de noduri izolate: %d.\n", ni);else

printf("\tNu sunt noduri izolate.\n");}void main(){VECT_MUCHII vm[DIMM+1];int nod_iz[DIMM+1], a[DIMN+1][DIMN+1]; int n, nm;citire_graf (vm, a, &n, &nm);init_nod_iz (nod_iz, n);determin_nod_iz (a, nod_iz, n);tipar_nod_iz (nod_iz, n);printf("\n");}Problema 53/*Sa se creeze programul care determina daca exista un lant dat intr-un graf.*/

#include <stdio.h>#include <conio.h>#define DIMN 6#define DIMM 10void citire_graf (int a[DIMN+1][DIMN+1], int *pn, int *pm){int i, j, k;

Page 90: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 92

//clrscr();printf("\nDati numar noduri, graf neorientat, n: ");scanf("%d", pn);printf("Nr. de muchii: ");scanf("%d", pm);for (i=1; i<= *pn; i++)

for (j=1; j<=*pn; j++)a[i][j]=0;

printf("\nCitire graf prin muchiile sale.\n");for (k=1; k<= *pm; k++)

{printf("Muchie sursa, dest: ");scanf ("%d%d", &i, &j);a[j][i]=a[i][j]=1;

}}void citire_lant(int l[DIMM+1], int *pdl){int i;printf("\nDati numar noduri pentru lantul de testat: ");scanf("%d", pdl);for (i=1; i<= *pdl; i++)

{printf("Varful %d din lant: ", i);scanf ("%d", &l[i]);

}printf("\nLantul cautat in garf este urmatorul:\n");for (i=1; i<= *pdl; i++)

printf("%d -> ", l[i]);}int test_lant(int g[DIMN+1][DIMN+1], int l[DIMM+1], int dl, int *elem){int i, j;*elem=1;for (i=1; i<=dl; i++)

if (!g[l[i]][l[i+1]])return 0;

for (i=1; i<=dl-1; i++)for (j=i+1; j<=dl; j++)

if(l[i]==l[j])*elem=0;

return 1;}void main(){int a[DIMN+1][DIMN+1], l[DIMM+1]; int n, nm, dl, elementar;citire_graf (a, &n, &nm);citire_lant (l, &dl);if (test_lant(a, l, dl, &elementar)){

Page 91: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 93

printf("\n\nEste un lant ");if (!elementar)

printf("ne-");printf("elementar!\n");}

elseprintf("\n\nNu este un lant in graf !!!\n");

printf("\n");}Problema 54/* Creeaza programul care construieste un arbore partial de cost minim pentru un graf neorientat, utilizand algoritmul lui Prim.*/

#include <stdio.h>#include <conio.h>//#include <values.h>#define DIMN 10#define DIMM 100void citire_graf (int a[DIMN+1][DIMN+1], int *pn, int *pm){int i, j, k, cost;//clrscr();printf("\nDati numar noduri, graf neorientat, n: ");scanf("%d", pn);printf("Nr. de muchii: ");scanf("%d", pm);for (i=1; i<= *pn; i++)

for (j=1; j<=*pn; j++)a[i][j]=0;

printf("\nCitire graf prin muchiile sale.\n");for (k=1; k<= *pm; k++)

{printf("Muchie, varfuri sursa, dest: ");scanf ("%d%d", &i, &j);printf("\tCost(%d-%d)= ", i, j);scanf("%d", &cost);a[j][i]=a[i][j]=cost;

}}void construct_arb_cost_min (int a[DIMN+1][DIMN+1], int ARB[DIMM+1],

int P[DIMM+1], int C[DIMN+1], int n, int prim){int k, i, j, cost_min,MAXINT, v1, v2;for (i=1; i<=n; i++){

ARB[i]=0; C[i]=0; P[i]=0;}

ARB[prim]=1;for (k=1; k<=n-1; k++){

cost_min=MAXINT;

Page 92: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 94

v1=0; v2=0;for (i=0; i<=n; i++)

for (j=0; j<=n; j++)if (ARB[i]==1 && ARB[j]==0)

if(a[i][j]) if (a[i][j]<cost_min){

cost_min=a[i][j];v1=i; v2=j; }

ARB[v2]=1;P[v2]=v1;C[v2]=cost_min;}

}void tip_arb_cost_min (int C[DIMN+1], int P[DIMN+1], int nn){int i, cm=0;for (i=2; i<nn; i++){

printf("%2d -%2d (%d) / ", P[i], i, C[i]);cm+=C[i];}

cm+=C[nn];printf("%2d - %2d (%d)\n\t\tcost minim = %d\n", P[i], i, C[i], cm);}void main(){int a[DIMN+1][DIMN+1]; int ARB[DIMN+1], C[DIMN+1], P[DIMN+1]; int n, nm, primul, dimV, k;citire_graf (a, &n, &nm);printf("\nProgramul parcurge in latime graful.\n");printf("\nSpecificati varful de start pentru parcurgere: ");scanf("%d", &primul);construct_arb_cost_min (a, ARB, P, C, n, primul);printf("\nArborele de cost minim este urmatorul:\n");tip_arb_cost_min (C, P, n);printf("\nApasati o tasta pentru a termina programul\n");getch();}Problema 55/* Sa se creeze programul elimina noduri dintr-un graf, cu conditia ca suma drumurilor pentru nodurile ramase sa fie cuprinsa intre doua limite. Se considera graf cu n noduri si m muchii, ce reprezinta configuratia in teritoriu a unei companii impreuna cu sucursalele sale. Sucursalele sunt interconectate intre ele prin drumuri de lungime data. Matricea de adiacenta contine costurile (drumurile) intre acestei filiale. Se doreste renuntarea la un numar de filiale, astfel incat suma drumurilor intre filialele ramase sa fie cuprinsa intre 2 valori.*/#include <stdio.h>

Page 93: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 95

#include <conio.h>#define DIMN 10#define DIMM 100typedef struct{

int vi, vf;int lung;} VECT_MUCHII;

int nr_sol=0;void citire_graf (VECT_MUCHII vm[DIMM+1], int a[DIMN+1][DIMN+1],

int *pn, int *pm){int i, j, k, drum;//clrscr();printf("\nDati numar noduri, graf orientat, n: ");scanf("%d", pn);printf("Nr. de muchii: ");scanf("%d", pm);for (i=1; i<= *pn; i++)

for (j=1; j<=*pn; j++)a[i][j]=0;

printf("\nCitire graf prin muchiile sale.\n");for (k=1; k<= *pm; k++)

{printf("Muchia %d, varf sursa -> destinatie: ", k);scanf ("%d%d", &vm[k].vi, &vm[k].vf);printf("Cost (%d -> %d)= ", vm[k].vi, vm[k].vf);scanf ("%d", &drum);a[vm[k].vi][vm[k].vf]=vm[k].lung=drum;

}printf("\nMatricea drumurilor pentru graful introdus este:\n");for (i=1; i<=*pn; i++){

for (j=1; j<=*pn; j++)printf("%3d", a[i][j]);

printf("\n");}

}void init_solutie (int solutie[DIMM+1], int nm){int i;for (i=1; i<=nm; i++)

solutie[i]=0;}int suma_drum_sol(int a[DIMN+1][DIMN+1], int solutie[DIMM+1],

int p, int dmin, int dmax){int k, suma_drum=0;for (k=1; k<p; k++)

suma_drum+=a[solutie[k]][solutie[k+1]];if (suma_drum >= dmin && suma_drum <= dmax)

return suma_drum; return 0;

Page 94: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 96

}void tipar_solutie(int a[DIMN+1][DIMN+1], int solutie[DIMM+1],

int p, int dmin, int dmax){int i;for (i=1; i<p; i++)

printf("%d -> ", solutie[i]);printf("%d\n\tSuma drumurilor=%d\n", solutie[p],

suma_drum_sol(a, solutie, p, dmin, dmax));if ((nr_sol+1)%10 == 0){

printf("\nAfisarea continua dupa apasarea unei taste!\n");getch();}

}int validare_solutie (int a[DIMN+1][DIMN+1], int solutie[DIMM+1], int p){int k;if ( !a[solutie[p-1]][solutie[p]] )

return 0;for (k=2; k<p; k++)

if (solutie[k]==solutie[p]) return 0;

return 1;}void incerc_solutie(int a[DIMN+1][DIMN+1], int solutie[DIMM+1],

int n, int p, int dmin, int dmax){int i;for (i=1; i<=n; i++)

{solutie[p]=i;if (validare_solutie(a, solutie, p))

if (solutie[1] == solutie[p] && p > 3 && suma_drum_sol(a, solutie, p, dmin, dmax)){tipar_solutie(a, solutie, p, dmin, dmax);nr_sol++;}

elseincerc_solutie(a, solutie, n, p+1, dmin, dmax);

solutie[p]=0;}

}void main(){VECT_MUCHII vm[DIMM+1];int sol[DIMM+1], a[DIMN+1][DIMN+1]; int n, nm, dmin, dmax;citire_graf (vm, a, &n, &nm);printf("Limitele pentru suma drumurilor din graf (min, max): ");scanf("%d%d", &dmin, &dmax);init_solutie(sol, nm);printf("\nSolutiile din graf sunt urmatoarele:\n");

Page 95: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 97

incerc_solutie(a, sol, n, 1, dmin, dmax);if(nr_sol)

printf("\nNumarul total de solutii este: %d\n", nr_sol);else

printf("\nProblema nu are solutii");printf("\n");}Problema 56/* Sa se creese programul care determina toate ciclurile elementare dintr-un graf cu n noduri si m muchii.*/#include <stdio.h>#include <conio.h>#define DIMN 10#define DIMM 100typedef struct{

int v1, v2;} VECT_MUCHII;

int nr_sol=0;void citire_graf (VECT_MUCHII vm[DIMM+1], int a[DIMN+1][DIMN+1], int *pn, int *pm){int i, j, k;//clrscr();printf("\nDati numar noduri, graf neorientat, n: ");scanf("%d", pn);printf("Nr. de muchii: ");scanf("%d", pm);for (i=1; i<= *pn; i++)

for (j=1; j<=*pn; j++)a[i][j]=0;

printf("\nCitire graf prin muchiile sale.\n");for (k=1; k<= *pm; k++)

{printf("Muchia %d, varfuri: ", k);scanf ("%d%d", &vm[k].v1, &vm[k].v2); a[vm[k].v1][vm[k].v2]=a[vm[k].v2][vm[k].v1]=1;

}}void init_ciclu (int ciclu[DIMM+1], int nm){int i;for (i=1; i<=nm; i++)

ciclu[i]=0;}void tipar_ciclu(int ciclu[DIMM+1], int p){int i;for (i=1; i<p; i++)

printf("%d -> ", ciclu[i]);printf("%d\n", ciclu[p]);

Page 96: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 98

if ((nr_sol+1)%20==0){printf("\nAfisarea continua dupa apasarea unei taste !!!\n");getch();}

}int validare_ciclu (int a[DIMN+1][DIMN+1], int ciclu[DIMM+1], int p){int k;if ( !a[ciclu[p]][ciclu[p-1]] )

return 0;for (k=2; k<p; k++)

if (ciclu[k] == ciclu [p])return 0;

return 1;}void incerc_ciclu(int a[DIMN+1][DIMN+1], int ciclu[DIMM+1], int n, int p){int i;for (i=1; i<=n; i++)

{ciclu[p]=i;if (validare_ciclu(a, ciclu, p))

if (ciclu[p]==ciclu[1] && p>3){tipar_ciclu(ciclu, p); nr_sol++;}

elseincerc_ciclu(a, ciclu, n, p+1);

}}void main(){VECT_MUCHII vm[DIMM+1];int ciclu[DIMM+1], a[DIMN+1][DIMN+1]; int n, nm;citire_graf (vm, a, &n, &nm);printf("\nCiclurile din graf sunt urmatoarele:\n");init_ciclu(ciclu, nm);incerc_ciclu(a, ciclu, n, 1);if(nr_sol)

printf("\nNumarul total de solutii este: %d\n", nr_sol);else

printf("\nProblema nu are solutii");printf("\n");}Problema 57/* Sa se creeze programul care determina drumul unui concurent pt. un concurs: concurentul poate incepe concursul din orice punct, dar nu poate parcurge traseul decat intr-o anumita directie si trecand cate o singura data prin fiecare punct (matricea grafului va contine doar cate un 1 pe fiecare linie si pe fiecare coloana): vom memora intr-un vector dr drumul curent, pornind dintr-un punct de

Page 97: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 99

'start', si vom determina urmatorul punct din graf, pe care-l introducem in vector, pana parcurgem toate nodurile grafului.*/#include <stdio.h>#include <conio.h>#define MAX 20void cit_graf_orientat (int grf[][MAX], int &n){int i, j;int v[][MAX]={ {0, 0, 1, 0, 0, 0, 0, 0},

{0, 0, 0, 1, 0, 0, 0, 0},{0, 1, 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 1, 0, 0},{0, 0, 0, 0, 0, 0, 1, 0},{0, 0, 0, 0, 1, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0, 1},{1, 0, 0, 0, 0, 0, 0, 0}};

printf("\nNumarul de noduri (puncte) in graf, n= ");scanf("%d", &n);for (i=0; i<n; i++)

{grf[i][i]=0;for (j=0; j<n; j++)

if (i!=j){grf[i][j]=v[i][j];/*printf("muchie[%d, %d]= ", i+1, j+1);scanf("%d", &grf[i][j]); */}

}}void scrie_graf_o (int grf[][MAX], int n){int i, j;printf("\nMatricea grafului este urmatoarea:\n");for (i=0; i<n; i++)

{for (j=0; j<n; j++)

printf("%3d ", grf[i][j]);printf("\n");}

printf("\n");}void generare_drum(int gf[][MAX], int n, int start, int dr[MAX]){int k, i, j, p, m, gasit;i=0;while (!gf[start][i])

i++;if (gf[start][i]==1)

{dr[0]=start; dr[1]=i;}else

Page 98: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 100

{dr[0]=i; dr[1]=start;}m=2;do {p=0;

while (!gf[dr[m-1]][p])p++;

dr[m]=p;m++;} while (m<n);

}void scrie_drum (int drum[], int n){int i;printf("\nDrumul grafului este urmatorul:\n");for (i=0; i<n; i++)

printf("%3d ", drum[i]);printf("\n");}void main (void) {int n, g[MAX][MAX], d[MAX], start;//clrscr();cit_graf_orientat(g, n);scrie_graf_o(g, n);printf("\nPunctul de pornire (start) ales din graf: ");scanf("%d", &start);generare_drum(g, n, start, d);scrie_drum(d, n);getch();}Problema 58/*Sa se scrie programul ce determina cele mai scurte drumuri dintr-un graf, utilizand algoritmul Floyd

(sau Djikstra modificat), care poate fi aplicat atat pentru grafuri orientate cat si pentru cele neorientate (se elimina linia care face simetrica matricea drumurilor, din functia de citire graf).*/#include <stdio.h>#include <conio.h>//#include <values.h>#define DIM 6int D[DIM+1][DIM+1], P[DIM+1][DIM+1], t[DIM+1];int i, j, k, n, nm, sursa, dest;char rasp[10];void main(){//clrscr();printf("\nDati numar noduri graf, n: ");scanf("%d", &n);printf("Nr. de muchii: ");scanf("%d", &nm);for (i=1; i<=n; i++)

Page 99: Probleme Sda

Gostinar Nicolae V. 314 AB

P a g e | 101

for (j=1; j<=n; j++){D[i][j]=0;P[i][j]=0;}

printf("Se citeste graful prin muchii, nod sursa, dest, si costul asociat.\n");for (k=1; k<=nm; k++)

{printf("Muchiile sursa, dest: ");scanf ("%d%d", &i, &j);printf("Cost(%d,%d): ", i, j);scanf("%d", &D[i][j]);D[j][i]=D[i][j];

}for (i=1; i<=n; i++)

for (j=1; j<=n; j++)if (D[i][j]==0)

D[i][j]=1000;else

P[i][j]=i; for (k=1; k<=n; k++)

for (i=1; i<=n; i++)for (j=1; j<=n; j++)

if (i != j && D[i][j] > D[i][k]+D[k][j]){D[i][j]=D[i][k]+D[k][j];P[i][j]=P[k][j]; }

for (i=1; i<=n; i++){for (j=1; j<=n; j++)

printf("%5d", D[i][j]);printf("\n");}

do{printf("\nDoriti distanta (costul) intre doua noduri (da/nu)? ");fflush(stdin);gets(rasp);if (rasp[0]!='d' && rasp[0]!='D')

{fflush(stdin);printf("\nApasati o tasta pentru a termina programul !\n");getch();exit(1);}

printf("Drumul (costul) intre nodurile sursa, destinatie: ");scanf("%d%d", &sursa, &dest);k=dest;i=0;while (P[sursa][k] && P[sursa][k] != sursa)

Page 100: Probleme Sda

Gostinar Nicolae V. 314AB

P a g e | 102

{ t[++i]=k;k=P[sursa][k]; }

t[++i]=k;t[++i]=sursa;printf("Drumul (%d->%d): ", sursa, dest);for (j=i; j>0; j--)

{if (j!=1)

printf("%2d -> ", t[j]);else

printf("%2d.", t[j]);}

printf("\tcost: %d\n", D[sursa][dest]);} while (rasp[0]=='d' || rasp[0]=='D');

}