#Include #Include #Include: "Sap Xep Topo /N/N"
#Include #Include #Include: "Sap Xep Topo /N/N"
h> typedef struct job* cv; typedef struct lienket* lk; struct job{ int key; int count; cv next; lk trail; }; struct lienket{ cv id; lk next; }; int readData(cv&, int&); void topoSort(cv&, int&); void main() { clrscr(); cv head=NULL; int z; if(readData(head,z)) { printf("sap xep topo \n\n"); topoSort(head,z); } else printf("ko sap topo dc"); getch(); }; cv addList(cv &head, int w, int &z) { cv tam; cv h = head; while((h->key != w)&&(h!=NULL)) h = h->next; if(h==NULL) { tam = new job; tam->next=head; tam->trail=NULL; tam->key=w; z++; tam->count = 0; head=tam; h= tam; } return h; }
int readData(cv &head, int &z) { int x, y; cv p,q; lk t; FILE *f; // head = new job; head->next=NULL; z = 0; f=fopen("topo.txt","rt"); if(!feof(f)) { fscanf(f,"%d",&x); head->key=x; while(!(feof(f))) { fscanf(f,"%d",&y); // tao 2 leader p = addList(head, x, z); q = addList(head, y, z); // them trailer cho p t = new lienket; t->id = q; t->next = p->trail; p->trail = t; q->count ++; fscanf(f,"%d",&x); } return 1; } return 0; } void topoSort(cv &head, int &z) { cv p,q,tg; lk t; p=head; q=p; int kt=1; while(1) { p=head; q=p; while((p->count!=0)) { q=p; p=p->next; } if(p==NULL) break; if(p==q) //neu phan tu dau danh sach co count=0; {
t=q->trail; while(t!=NULL) { tg=t->id; if(tg->count==0) kt=0; tg->count--; t=t->next; } head=p->next; printf("%3d",q->key); z--; } else if(p->next==NULL) //truong hop phan tu cuoi ds co count=0; { printf("%3d",p->key); z--; t=p->trail; while(t!=NULL) { tg=t->id; if(tg->count==0) kt=0; tg->count--; t=t->next; } q->next=NULL; } else { t=p->trail; while(t!=NULL) { tg=t->id; if(tg->count==0) kt=0; tg->count--; t=t->next; } printf("%3d",p->key); q->next=p->next; z--; } if(kt==0) break; } delete p; delete q; if(z>0) printf("\n\n ko the sap xep topo tren day nay dc"); }
Vi file topo.txt l : 1 2 tc l 1 lin thng vi 2(nhng cha chc c ng i t 2 n 1). 12 24 2 10 48 63 13 35 58 75 79 94 9 10 Th s cho kt qu Kt qu s l 7 ->9->1->2->4->6->3->5->8->10.