Upload
hien89
View
20
Download
0
Embed Size (px)
Citation preview
STACK( Ngăn Xếp )
+ Cài đặt ngăn xếp bằng mảng + Cài đặt ngăn xếp bằng danh sách liên kết
struct STACK{
int top;int items[MAXSIZE];int n;
};
STACK S;//khoi taovoid Init(STACK &S) {
S.top=0;}// Kiểm tra Stack rỗngbool Stack_Empty(STACK S){
if(S.top==0)return true;
return false;}//Kiểm tra ngăn xếp đầybool Stack_Full(STACK S){
if(S.top==S.n)return true;
return false;}// Thêm 1 phần vào Stackvoid Push(STACK &S, int x){
S.top=S.top+1;S.items[S.top]=x;
}// Lấy 1 phần tử khỏi Stackint Pop(STACK &S){
if(!Stack_Empty(S))S.top=S.top-1;
return S.items[S.top+1];}
typedef struct Node*Stack;struct Node{
int key;Stack next;
};Stack S;//khởi tạovoid Init(Stack &S){
S=NULL;}//Kiểm tra ngăn xếp rỗngvoid Stack_Empty(Satck S){
if(S==NULL)return true;
return false;}//Thêm 1 phần tử vào ngăn xếpvoid Push(Stack &S, int x){
Stack p=new(Node);p->key=x;p->next=S;S=p;
}//Lấy 1 phần tử ra ngăn xếpint Pop(Stack &S){
if(!Stack_Empty(S)){
Stack p;p=S;S=p->next;x=p->key;delete(p);
}}
Trang 1
QUEUE( Hàng Đợi )
+ Cài đặt hàng đợi bằng mảng + Cài đặt hàng đợi bằng danh sách liên kết
#define Max 50struct Queue{
int a[Max];int head, tail;int n;
};Queue Q;// Khởi tạo hàng đợivoid Init(Queue &Q){
Q.head=0;Q.tail=0;
}//Kiểm tra hàng đợi rỗngbool overflow(Queue Q){
if( Q.head==Q.tail)return true;
return false;}//Kiểm tra hàng đợi đầybool underflow(Queue Q){
if( Q.head==Q.tail+1)return true;
return false;}// Thêm 1 phần tử vào hàng đợivoid ENQUEUE(Queue &Q, int x){
if ( ! underflow(Q)){
Q.a[Q.tail]=x;if( Q.tail== Q.n)
Q.tail=0;else
Q.tail=Q.tail+1;}
}//Lấy 1 phần tử khỏi hàng đợi
int DEQUEUE(Queue &Q){
int x=Q.a[Q.head];if(Q.head==Q.n)
Q.head=0;else
Q.head=Q.head+1;return x;
}typedef struct Node*List;struct Node{
int key;List next;
};struct Queue{
List head, tail;};Queue Q;// Khởi tạovoid Init(Queue &Q){
Q.head=0;Q.tail=0;
}// Kiểm tra hàng đợi rỗngbool Queue_Empty(Queue Q){
if(Q.head==Q.tail)return true;
return false;}// Thêm 1 phần tử vào hàng đợivoid ENQUEUE(Queue &Q, int x){
List p=new(Node);p->key=x;p->next=0;if(Q.head==0)
Q.head=p;
Trang 2
elseQ.tail->next=p;
Q.tail=p;}//Lấy 1 phần tử khỏi hàng đợiint DEQUEUE(Queue &Q){
List p;p=Q.head;
int x=p->key;if(Q.head==Q.tail)
Q.head=0;else
Q.head->next=p;delete(p);return x;
}
----------------- Chuyển đổi từ trung tố sang hậu tố------------------------------
ConverInfix_Postfix(infix[], postfix[]){
while(infix[i]!='\0'){
if(IsNumber(infix[i])){
j++;postfix[j]=infix[i];
}else if(IsOperty(infix[i])){
if(Stack_Empty(S))Push(S,infix[i]);
else {
if(Priority(infix[i])<Priority(Peek(S))){
j++;postfix[j]=Pop(S);
}Push(S,infix[i]);
}}else if(infix[i]==')'){
while(!Stack_Empty(S)){
j++;postfix[j]=Pop(S);
}}i++;
}while(!Stack_Empty(S)){
j++;postfix[j]=Pop(S);
Trang 3
}}
----------------------------------- Tính giá trị biểu thức hậu tố--------------------------------
tinh_giatri(postfix[]){
i=0;while(postfix[i]!='\0')
{ ch=postfix[i]; switch (ch) { case '0' : case '1' : case '2' : case '3' : case '4' : case '5' : case '6' : case '7' : case '8' : case '9' :
Push(S,(ch-'0'));break;//mã ASCII của 'ch' trừ đi mã ASCII của '0' thì dc giá trị của số t/ung với 'ch'//Nhưng chỉ hiệu quả trong khỏang 0~9 vì sau 9 trong bảng ASCII là kí tự khác rồi
case '+' : num1=Pop(S);num2=Pop(S);Push(S,num1+num2); break;
case '-' :num1=Pop(S);num2=Pop(S);Push(S,num2-num1);break;
case '*' :num1=Pop(S);num2=Pop(S);Push(S,num1*num2);break;
case '/' :num1=Pop(S);num2=Pop(S);Push(S,num2/num1);break;
Trang 4
} } return Pop(S);}
--------------------------Kiểm tra vị trí dấu ngoặc trong biểu thức----------------------CapDauNgoac(str[]){
i=0;while(str[i]!='\0'){
if(str[i]=='(' )Push(S,i);
if(str[i]==')' )cout<<"("<<Pop(S)<<","<<i<<") ";
i++;}
}
-----------------------------Tìm phương pháp hoán vị---------------------------------------------void phuongphaphoanvi(){
while(a[i]!='\0'&& j<=maxvalue())// maxvalue là giá trị lớn nhất trong mảng a{
if(a[i]==j){
cout<<"A->C, ";i++; j++;
}else{
Push(S,j);cout<<"A->B, ";j++;
}}while(i<4){
tam[k]=a[i];k++; i++;
}k=0;bool thoat=false;while(!Stack_Empty(S)&& thoat==false){
if(tam[k]==Pop(S)){
cout<<"B->C, ";k++;
}else
thoat=true;
Trang 5
}if(thoat==true)
cout<<" => Khong co phuong an hoan vi\n";}
DANH SÁCH LIÊN KẾT ( Kép )
#include <iostream>using namespace std;//Dinh nghia kieu du lieustruct Node{
int key;Node *next;Node *prev;
};struct LIST{
Node *head, *tail;int size;
};//Khoi tao danh sach Lvoid ListInit (LIST &L){
L.head = NULL;L.tail = NULL;L.size=0;
}//Kiem tra L rong?bool Empty(LIST L){
if (L.head== NULL)return true;
return false;}// Tạo 1 nútNode *CreateNode(int i){
Node *x = new Node;x->key = i;x->next =NULL;x->prev=NULL;return x;
}//In danh sachvoid ListPrint ( LIST &L){
Node *temp =L.head;while(temp!=NULL){
cout<<(temp->key)<<" ";temp=temp->next;
}}void AddFirst(LIST &L, Node *x) //Chèn đầu{
if(L.head==NULL){
L.head=x;L.tail=L.head;
}else{
x->next=L.head;L.head->prev=x;L.head=x;
}}void AddEnd(LIST &L, Node *x) // Chèn vào cuối{
if(L.head==NULL){
L.head=x;L.tail=L.head;
}else{
x->prev=L.tail;L.tail->next=x;L.tail=x;
}}//Chèn vào sau nút qvoid AddLasrQ(LIST &L, Node *x, Node *q){
Node *p;if(q!=NULL){
Trang 6
p=q->next;x->next=p;x->prev=q;q->next=x;if(p!=NULL)
p->prev=x;if(q==L.tail)// Them vao sau DS
L.tail=x;}else
AddFirst(L,x);}//Chèn vào trước nút qvoid AddBeforeQ(LIST &L, Node *x, Node *q){
Node *p;if(q!=NULL){
p=q->prev;x->next=q;q->prev=x;x->prev=p;if(p!=NULL)
p->next=x;if(q==L.head)
L.head=x;}else
AddEnd(L,x);}//Tim phan tu co khoa k trong danh sach LNode *ListSearch(LIST L, int k){
Node *x = L.head;while ((x != NULL) && (x->key != k))
x = x->next;return x;
}//Xoa phan tu duoc tro boi xvoid DeleteNode(LIST L, Node *x){
if(x->prev!=NULL)x->prev->next=x->next;
else L.head = x->next;
if (x->next!=NULL)x->next->prev=x->prev;
}// xoa nut dau DSvoid DeleteFirst(LIST &L)
{Node *p;if(L.head!=NULL){
p=L.head;L.head=L.head->next;L.head->prev=NULL;delete p;if(L.head==NULL)
L.tail=NULL;}
}// xoa nut cuoi DSvoid DeleteEnd(LIST &L){
Node *p;if(L.head!=NULL){
p=L.tail;L.tail=L.tail->prev;L.tail->next=NULL;delete p;if(L.tail==NULL)
L.head=NULL;}
}//Xoa nút x ra khỏi DSvoid DeleteNode(LIST &L, Node *x){
if(x->prev!=NULL)x->prev->next=x->next;
else L.head = x->next;
if (x->next!=NULL)x->next->prev=x->prev;
}//Xoa 1 nút sau nút Qvoid DeleteLastQ(LIST &L, Node *q){
Node *p;if(q!=NULL){
p=q->next;if(p!=NULL){
q->next=p->next;if(p==L.tail)
L.tail=q;else
p->next->prev=q;Trang 7
delete p;}
}else
DeleteFirst(L);}
//Xoa 1 nút trước nút Qvoid DeleteBeforeQ(LIST &L, Node *q){
Node *p;if(q!=NULL){
p=q->prev;if(p!=NULL){
q->prev=p->prev;if(p==L.head)
L.head=q;else
p->prev->next=q;delete p;
}}else
DeleteEnd(L);}//Sap xep DSvoid HoanVi(int &n, int &m){
int t=n; n=m; m=t;}void SapXep(LIST &L){
Node *p,*q;p=L.head;while(p!=L.tail){
q=p->next;while(q!=NULL){
if(p->key>q->key) HoanVi(p->key,q->key);q=q->next;
}
p=p->next;}
}//Dao DS chi thay doi lien ketvoid DaoDS(LIST &L){
Node *p=L.head->next;L.tail=L.head;while(p!=NULL){
L.tail->next=p->next;p->next=L.head;L.head=p;p=L.tail->next;
}}void Chen_ThuTu(LIST &L, Node *x){
Node *q=L.head;while(q!=NULL){
if(x->key<q->key)break;
q=q->next;
}AddBeforeQ(L,x,q);
}
Bài tập DSLK Nhân viên#include <iostream>#include <stdio.h>#include<conio.h>#include <iomanip>using namespace std;struct NHANVIEN{
char MaNV[10];char HoTen[30];int ThamNien;float Luong;NHANVIEN *next;NHANVIEN *prev;
};NHANVIEN NV;struct DANHSACH_NV{
NHANVIEN *Head;};DANHSACH_NV DSNV;
Trang 8
void KhoiTao_DS(DANHSACH_NV &ds){
ds.Head = NULL;}void IN_DSNV(DANHSACH_NV ds){
NHANVIEN *p = ds.Head;int i=1;while(p!=NULL){
cout<<"\nThong tin nhan vien thu "<<i<<" : ";
cout<<"\n\tMaNV: "<<p->MaNV;cout<<"\n\tTenNV: "<<p->HoTen;cout<<"\n\tTham Nien: "<<p-
>ThamNien;cout<<"\n\tLuong: "<<p->Luong;p=p->next;i++;
}}void Tao_1NV(NHANVIEN * &p){
p = new NHANVIEN();cout<<"\n\tNhap manv: ";cin>>p->MaNV;cout<<"\tHo ten: ";cin>>p->HoTen;cout<<"\tTham nien: ";cin>>p->ThamNien;cout<<"\tLuong: ";cin>>p->Luong;
}void Chen(DANHSACH_NV &ds){
NHANVIEN *p;Tao_1NV(p);p->prev = NULL;p->next = ds.Head;ds.Head = p;
}void Chen_ThuTu(DANHSACH_NV &ds){
NHANVIEN *p;Tao_1NV(p);NHANVIEN * past = NULL;NHANVIEN * curr = ds.Head;while(curr!=NULL && curr->ThamNien <
p->ThamNien){
past = curr;curr = curr->next;
}p->prev = past;p->next = curr;if(past!=NULL)
past->next = p;else
ds.Head = p;if(curr!=NULL)
curr->prev = p;} NHANVIEN * TimNV(DANHSACH_NV ds,int ThamNien){
NHANVIEN * curr = ds.Head;while(curr!=NULL && curr->ThamNien !=
ThamNien){
curr = curr->next;}return curr;
}void Xoa(DANHSACH_NV &ds,NHANVIEN *p){
if(p!=NULL){
if(p->prev!=NULL)p->prev->next=p->next;
elseds.Head=p->next;
if(p->next!=NULL)p->next->prev=p->prev;
}else
cout<<"Khong tim thay tham nien can xoa";}void main(){
}
Trang 9
TREEstruct Node{
int key;Node *p;Node *left;Node *right;
};struct Tree{
Node *root;};Tree T;struct STACK //{// Node *A[10];// int top;// int n;//};//STACK S;void INIT(Tree &T){
T.root=NULL;}// Thủ tục chèn vào cây T một phần tử z void TREE_INSERT(Tree &T, Node *z){
Node *y=NULL;Node *x=T.root;while(x!=NULL){
y=x;if(z->key<x->key)
x=x->left;else
x=x->right;}z->p=y;if(y==NULL)
T.root=z;else if (z->key<y->key)
y->left=z;else
y->right=z;}// Thủ tục tạo 1 câyNode *NODE_CREAT(int k)// Tạo 1 nút{
Node *z=new Node;z->key=k;z->left=NULL;z->right=NULL;return z;
}
// Tạo câyvoid TREE_CREAT(Tree &T){
int a[]={4,2,6};for(int i=0;i<3;i++){
Node *z=NODE_CREAT(a[i]);TREE_INSERT(T,z);
}}// Duyệt cây theo thứ tự trung tựvoid INODER_TREE_WALK(Node *x){
if(x!=NULL){
INODER_TREE_WALK(x->left);cout<<x->key<<" ";INODER_TREE_WALK(x->right);
}//Node *p=x;bool dung=false;//do//{
//while(p!=NULL)//{
//S.top=S.top+1;//S.A[S.top]=p;//p=p->left;
//}//if(S.top!=0)//{
//p=S.A[S.top];//S.top=S.top-1;//cout<<p->key;//p=p->right;
//}//else
//dung=true;//}while(dung!=true);
}
Trang 10
// Tìm khóa k trên cây có gốc là con trỏ xNode *TREE_SEARCH(Node *x,int k){
if(x==NULL || k==x->key)return x;
else if(k<x->key)return TREE_SEARCH(x->left,k);
elsereturn TREE_SEARCH(x->right,k);
return 0;}//Tìm phần tử lớn nhất và nhỏ nhất, x trỏ đến nút gốc của cây, x khác NULLNode *TREE_MINIMUM(Node *x){
while(x->left!=NULL)x=x->left;
return x;}Node *TREE_MAXIMUM(Node *x){
while(x->right!=NULL)x=x->right;
return x;}//Cài đặt thủ tục tìm phần tử đi sau 1 phần tửNode *TREE_SUCCESSOR(Node *x){
if(x->right!=NULL)return TREE_MINIMUM(x->right);
Node *y=x->p;while(y!=NULL && x==y->right){
x=y;y=y->p;
}return y;
}//Thủ tục xóa nút z trong câyvoid TRANSPLANT(Tree T, Node *u, Node *v){
if(u->p==NULL)T.root=v;
else if(u==u->p->left)u->p->left=v;
elseu->p->right=v;
if(v!=NULL)v->p=u->p;
}
void TREE_DELETE(Tree &T, Node *z){
if(z->left==NULL)TRANSPLANT(T,z,z->right);
else if(z->right==NULL)TRANSPLANT(T,z,z->left);
else{
Node *y=TREE_MINIMUM(z->right);
if(y->p!=z){
TRANSPLANT(T,y,y->right);
y->right=z->right;y->right->p=y;
}TRANSPLANT(T,z,y);y->left=z->left;y->left->p=y;
}}int ChieuCao(Node *p){
if(p==NULL)return 0;
if(ChieuCao(p->left)>ChieuCao(p->right))return 1+ChieuCao(p->left);
return 1+ChieuCao(p->right);}int SoNutLa(Node *p){
if(p==NULL)return 0;
if(p->left==NULL && p->right==NULL)return 1;
return SoNutLa(p->left)+SoNutLa(p->right);} int SoNutBac2(Node *p) {
if(p->left!=NULL && p->right!=NULL)return 1+SoNutBac2(p->left)
+SoNutBac2(p->right);return 0;
}void main() { }
Trang 11
HEAPSORT & QUICKSORT
#include<iostream>using namespace std;#define MAX 50struct Heap{
int items[MAX];int size;int lenght;
};// tìm vị trí nút chaint Parent(int i){
return i=i/2;}// tìm vị trí nút con trái int Left(int i){
return i=2*i+1;}//tìm vị trí nút con phảiint Right(int i){
return i=2*i+2;}// Khởi tao heapvoid InitHeap(Heap &H,int A[], int n){
for(int i=0;i<n;i++)H.items[i]=A[i];
H.size=H.lenght=n;}// in mang A với độ dài nvoid PrintArray(int A[],int n){
for(int i=0;i<n;i++)cout<<A[i]<<" ";
}// in heap với độ dài sizevoid PrintHeap(Heap H){
for(int i=0;i<H.lenght;i++)cout<<H.items[i]<<" ";
}
// hoán vịvoid Hoanvi(int &a, int &b){
int t=a;a=b;b=t;
}// Duy trì tính chất heapvoid Max_Heapity(Heap &H, int i){
int l=Left(i);int r=Right(i);int largest=i;if(l<=H.size && H.items[l]>H.items[i])
largest=l;if(r<=H.size &&
H.items[r]>H.items[largest])largest=r;
if(largest!=i){
Hoanvi(H.items[i],H.items[largest]);Max_Heapity(H, largest);
}}// Xây dựng heapvoid Build_Max_Heap(Heap &H){
for(int i=H.size/2;i>=0;i--)Max_Heapity(H,i);
}// sắp xếp heapvoid Heap_sort(Heap &H){
Build_Max_Heap(H);for(int i=H.size-1;i>=1;i--){
Hoanvi(H.items[0],H.items[i]);H.size=H.size-1;Max_Heapity(H,0);
}
Trang 12
}//trả về phần tử có khóa lớn nhất trong heapint Heap_Maximum(Heap H){
return H.items[0];}//tăng giá trị khóa của phần tử i lên keyvoid Heap_Increase_Key(Heap &H,int i, int key){
if(key<H.items[i])cout<<"New key is smaller than
curent key";H.items[i]=key;while(i>1 &&
H.items[Parent(i)]<H.items[i]){
Hoanvi(H.items[Parent(i)],H.items[i]);i=Parent(i);
}}//chèn phần tử void Max_Heap_Insert(Heap &H,int key){
H.items[H.size]=INT_MIN;Heap_Increase_Key(H,H.size,key);H.size=H.size+1;
}// Loại bỏ 1 phần tử khỏi heapint Heap_Extract_Max(Heap &H){
if(H.size<0)cout<<"Heap rong";
int max=H.items[0];H.items[0]=H.items[H.size-1];H.size=H.size-1;Max_Heapity(H, 0);return max;
}// cài đặt thuật giải Quick_sortint Partition(int A[],int dau, int cuoi){
int x=A[cuoi];int i=dau-1;for(int j=dau;j<cuoi;j++)
if(A[j]<=x){
i++;Hoanvi(A[i],A[j]);
}
Hoanvi(A[i+1],A[cuoi]);return i+1;
}
void Quick_sort(int A[],int dau,int cuoi){
int p;if(dau<cuoi){
p=Partition(A, dau, cuoi);Quick_sort(A,dau,p-1);Quick_sort(A,p+1,cuoi);
}}
void main(){
Heap H;int A[]={4,1,3,2,16,9,10,14,8,7};InitHeap(H,A,10);cout<<"Day heap chua duoc dieu chinh : ";PrintHeap(H);
Build_Max_Heap(H);cout<<"\nDay heap sau khi duoc dieu
chinh : ";PrintHeap(H);
Max_Heap_Insert(H,15);cout<<"\nDay heap sau khi them 1 phan tu
co gia tri 15 : ";PrintHeap(H);
Heap_Extract_Max(H);cout<<"\nDay heap sau khi loai bo 1 phan tu
: ";PrintHeap(H);
Heap_sort(H);cout<<"\nDay heap sau khi da sap xep : ";PrintHeap(H);
Quick_sort(A,0,9);cout<<"\nMang sau khi da sap xep dung
Quick sort : ";PrintArray(A,10);
}Trang 13
SẮP XẾP THỜI GIAN TUYẾN TÍNH-- Sắp xếp bằng đếm#include<iostream>using namespace std;#define MAX 10int A[]={1,4,0,2,2,4,5,1,2};int n=sizeof(A)/sizeof(A[0]);void COUNTING_SORT(int A[], int B[], int k){
int *C = new int[k+1];for(int i=0;i<=k;i++)
C[i]=0;for(int j=0;j<n;j++)
C[A[j]]=C[A[j]]+1;//C[i] chứa số phần tử bằng với ifor(int i=1;i<=k;i++)
C[i]=C[i]+C[i-1];//C[i] chứa số phần tử <= ifor(int j=n-1;j>=0;j--){
B[C[A[j]]-1]=A[j];C[A[j]]=C[A[j]]-1;
}delete []C;
}void main(){
int k=5;int B[MAX];COUNTING_SORT(A,B,k);cout<<"\nDay da sap xep la: ";for(int i=0;i<n;i++)
cout<<B[i]<<" ";}-- Sắp xếp theo lôvoid bucketSort(int A[], int n) { int i, j; int count[10]; for(i=0; i < n; i++) { count[i] = 0; } for(i=0; i < n; i++) { (count[A[i]])++; } for(i=0,j=0; i < n; i++) { for(; count[i]>0; (count[i])--) {
Trang 14
A[j++] = i; } } }// Dùng Danh Sách Liên Kếtstruct NODE{
int key;NODE *next;
};struct LIST{
NODE *firstElement;};int A[]={45,2,67,13,6,92,23,47,50,83};int n=sizeof(A)/sizeof(A[0]);void LIST_SORT(LIST &L){
NODE *p=L.firstElement, *q;while(p!=NULL){
q=p->next;while(q!=NULL && q->key > p->key){
q->next->key=q->key;q=q->next;
}q->next->key=p->key;q=p;
p=p->next;}
}void LIST_JOIN(LIST &L1, LIST L2){
NODE *p=L1.firstElement, *q=L2.firstElement;while(p!=NULL)
p=p->next;while(q!=NULL)
q=q->next;p->next=q;q->next=NULL;
}void main(){
int lowend=0;// minimum element int highend=100;//max element int interval=10;
LIST *buckets=new LIST[(highend-lowend)/interval];for(int j=0;j<n;j++) //sending elments into appropriate buckets
{NODE *temp,*pre=NULL;temp=buckets[A[j]/interval].firstElement;
if(temp==NULL)//if it is the first element of the bucket {
Trang 15
temp=new NODE; buckets[A[j]/interval].firstElement=temp; temp->key=A[j]; } else {
//move till the appropriate position in the bucket while(temp!=NULL) { if(temp->key<A[j]) pre=temp; temp=temp->next; }
//if the new value is in betwen or at the begining if(temp->key>A[j]) {
if(pre==NULL) //insertion at first if the bucket has elements already { NODE *firstNode; firstNode=new NODE(); firstNode->key=A[j]; firstNode->next=temp; buckets[A[j]/interval].firstElement=firstNode; } else //insertion at middle { NODE *firstNode; firstNode=new NODE(); firstNode->key=A[j]; firstNode->next=temp; pre->next=firstNode; } }
else // if the new value is to be created at last of bucket { temp=new NODE; pre->next=temp; temp->key=A[j]; } }
}cout<<"------The Sorted Elements Are---------------\n";
for(int jk=0;jk<10;jk++) { NODE *temp; temp= buckets[jk].firstElement; while(temp!=NULL) { cout<<"*"<<temp->key<<endl; temp=temp->next; } } cout<<"-----------------END--------------\n";}
Trang 16
CÁC THUẬT TOÁN ĐỒ THỊ
// Tiềm kiếm theo chiều rộng ( BFS ) và chiều sâu ( DFS ) sử dụng danh sách cạnh
#include<iostream>#include<vector>#include<queue>using namespace std;#define White 0#define Gray 1#define Black 2struct Vecter{
int id;int color;int d;int parent;int in, out;vector<int> adj;int in,out;
};struct Graph{
int V,E;vector<Vecter> vecteres;
};//Nhập đồ thị vô hướngvoid InputUnDirectedGraph(Graph &G){
cout<<"Nhap so dinh: ";cin>>G.V;cout<<"Nhap so canh: ";cin>>G.E;for(int i=0;i<G.V;i++){
Vecter u;u.id=i;u.d=-1;u.parent=-1;u.color=White;u.out=0;u.in=0;G.vecteres.push_back(u);
}for(int i=0;i<G.E;i++){
int u,v;cout<<"Nhap canh <u,v>: ";cin>>u>>v;
G.vecteres[u].adj.push_back(v);G.vecteres[v].adj.push_back(u);
G.vecteres[u].out=G.vecteres[u].out+1;G.vecteres[v].in=G.vecteres[v].in+1;G.vecteres[u].in=G.vecteres[u].in+1;G.vecteres[v].out=G.vecteres[v].out+1;}
}// Nhập đồ thị có hướngvoid InputADirectedGraph(Graph &G){
cout<<"Nhap so dinh: ";cin>>G.V;cout<<"Nhap so canh: ";cin>>G.E;for(int i=0;i<G.V;i++){
Vecter u;u.id=i;u.d=-1;u.parent=-1;u.color=White;u.out=0;u.in=0;G.vecteres.push_back(u);
}for(int i=0;i<G.E;i++){
int u,v;cout<<"Nhap canh <u,v>: ";cin>>u>>v;G.vecteres[u].adj.push_back(v);
G.vecteres[u].out=G.vecteres[u].out+1; G.vecteres[v].in=G.vecteres[v].in+1;}
}void DemBanBacRa(Graph G/* Vecter &u*/){
for(int i=0;i<(int)G.vecteres.size();i++){
Vecter u=G.vecteres[i];int dem=0;cout<<"\nSo bac ra cua dinh
"<<G.vecteres[i].id<<" la: ";for(int j=0;j<(int)u.adj.size();j++)
dem=dem+1;cout<<dem;
}}
Trang 17
void DemBanBacVao(Graph G/* Vecter &u*/){
for(int i=0;i<(int)G.vecteres.size();i++){
int dem=0;cout<<"\nSo bac vao cua dinh
"<<G.vecteres[i].id<<" la: ";Vecter u=G.vecteres[i];for(int j=0;j<(int)G.vecteres.size();j++){
for(int k=0;k<(int)G.vecteres[j].adj.size();k++)
{int
v=G.vecteres[j].adj[k];
if(u.id==G.vecteres[v].id)dem=dem+1;
}}cout<<dem;
}}void BFS(Graph &G, int s){
queue<int> Q;G.vecteres[s].color=Gray;G.vecteres[s].d=0;G.vecteres[s].parent=-1;Q.push(s);while(!Q.empty()){
int u=Q.front();Q.pop();for(int
i=0;i<(int)G.vecteres[u].adj.size();i++){
int v=G.vecteres[u].adj[i];if(G.vecteres[v].color==White){
G.vecteres[v].color=Gray;
G.vecteres[v].d=G.vecteres[u].d+1;G.vecteres[v].parent=u;Q.push(v);
}}G.vecteres[u].color=Black;
}}int time=0;void DFS_VISIT(Graph &G, int u){
time=time+1;G.vecteres[u].d=time;G.vecteres[u].color=Gray;for(int i=0;i<(int)G.vecteres[u].adj.size();i++){
int v=G.vecteres[u].adj[i];if(G.vecteres[v].color==White){
G.vecteres[v].parent=u;DFS_VISIT(G, v);
}}G.vecteres[u].color=Black;time=time+1;
}void DFS(Graph &G){
for(int i=0;i<G.V;i++){
G.vecteres[i].color=White;G.vecteres[i].parent=-1;
}time=0;for(int i=0;i<G.V;i++)
if(G.vecteres[i].color==White)DFS_VISIT(G, i);
}
void PrintGraph(Graph G){
for(int i=0;i<(int)G.vecteres.size();i++){
Vecter u=G.vecteres[i];cout<<"Dinh"<<u.id<<"(color:"<<u.color<<",
d:"<<u.d<<", parent:"<<u.parent<<"):";for(int j=0;j<(int)u.adj.size();j++)
cout<<"Canh:"<<u.id<<"->"<<u.adj[j]<<", ";
cout<<"\n------------------------\n";}
}void main(){
Graph G;}
----------------------************-----------------------
Trang 18
// Tiềm kiếm theo chiều rộng ( BFS ) và chiều sâu ( DFS ) sử dụng ma trận kề
#include <stdio.h>#include <stdlib.h>#define MAX 10int Color[MAX]; //mau cua cac dinhint Time[MAX][2]; //luu thoi diem bat dau va ket thuc thamint Distance[MAX]; //Luu khoang cach tu dinh bat dau toi diem hien tai//do thi duoc luu dung ma tran ke co huongint Graph[MAX][MAX] = {
0, 1, 0, 0, 0, 0, 0, 0, 1, 0,0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0, 1, 0, 0,0, 0, 0, 0, 0, 1, 1, 0, 0, 1,1, 0, 0, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0, 0, 0, 1,0, 0, 0, 0, 1, 0, 0, 0, 0, 0,0, 1, 0, 0, 0, 0, 0, 1, 0, 0,0, 0, 1, 0, 0, 0, 0, 0, 0, 0};
struct Queue{
int Q[MAX];int head, tail;int n;
};Queue Q;// Khởi tạo hàng đợivoid Init_Q(Queue &Q){
Q.head=0;Q.tail=0;Q.n=MAX;
}//Kiểm tra hàng đợi rỗngbool Empty_Q(Queue Q){
if( Q.head==Q.tail)return true;
return false;}//Kiểm tra hàng đợi đầybool Full_Q(Queue Q){
if( Q.head==Q.tail+1)return true;
return false;}// Thêm 1 phần tử vào hàng đợivoid ENQUEUE(Queue &Q, int x){
if ( ! Full_Q(Q)){
Q.Q[Q.tail]=x;if( Q.tail== Q.n)
Q.tail=0;else
Q.tail=Q.tail+1;}
}//Lấy 1 phần tử khỏi hàng đợiint DEQUEUE(Queue &Q){
int x=Q.Q[Q.head];if(Q.head==Q.n)
Q.head=0;else
Q.head=Q.head+1;return x;
}
//Dinh chua duoc tham (dinh trang) co gia tri -1//Dinh dang duoc tham (dinh xam) co gia tri 0//Dinh da tham (dinh mau den) co gia tri 1void init()//Khoi tao {
int i;for(i=0;i<MAX;i++)
Color[i]=-1; }char VertexName(int u){
return u+'A';}
//thuc hien BFS bat dau tu dinh svoid BFS(int s){
Init_Q(Q);//khởi tạo hàng đợiinit(); //khoi tao do thiint i,u;Color[s]=0;Distance[s]=0;ENQUEUE(Q,s);while(!Empty_Q(Q)){
u=DEQUEUE(Q);for(i=0;i<MAX;i++)
if(Color[i]==-1 && Graph[u][i]==1)
{ENQUEUE(Q,i);
Trang 19
Color[i]=0;Distance[i]=Distance[u]
+1;}
Color[u]=1;printf("-->%d(%d)",u,Distance[u]);
}}struct STACK{
int top;int S[MAX];int n;
};
STACK S;//khoi taovoid Init_S(STACK &S) {
S.top=0;S.n=MAX;
}// Kiểm tra Stack rỗngbool Stack_Empty(STACK S){
if(S.top==0)return true;
return false;}//Kiểm tra ngăn xếp đầybool Stack_Full(STACK S){
if(S.top==S.n)return true;
return false;}// Thêm 1 phần vào Stackvoid Push(STACK &S, int x){
if(!Stack_Full(S)){
S.top=S.top+1;S.S[S.top]=x;
}}// Lấy 1 phần tử khỏi Stackint Pop(STACK &S){
//if(!Stack_Empty(S))S.top=S.top-1;return S.S[S.top+1];
}
void DFS(int s)
{int i,u,t;int found;//khoi tao do thiinit(); //khoi tao StackInit_S(S);Push(S,s);Color[s]=0;//thoi giant=1;//thoi diem bat dau tham s la 1Time[s][0]=t;
while(!Stack_Empty(S)){
t++;u=S.S[S.top];printf("-->%d",u);i=0;found=0;while(i<MAX && !found){
if(Color[i]==-1 && Graph[u][i]==1)
{Time[i][0]=t;Push(S,i);Color[i]=0;found=1;
}else
i++;}if(!found) {
Color[u]=1;Time[u][1]=t;S.top--;
}}
printf("\nThoi gian tham cac dinh:");for(i=0;i<MAX;i++){
printf("-->%d(%d|%d)",i,Time[i][0],Time[i][1]);
}}int main(){ BFS(0); //DFS(0);}
Trang 20
Trang 21
CÂY BAO TRÙM NHỎ NHẤT***** Thuật toán Kruskal# include <iostream># include <vector># include <fstream># include <algorithm>using namespace std;typedef int* PInt;struct Vertex{
int id;vector<int> adj;
};struct Edge{
int v1, v2;double w;
};struct Graph{
int V;int E;vector<Vertex> vertex;vector<Edge> edge;
};//tao n tap hop roi nhau, moi tap chua mot phan tuvoid MakeSet(PInt &S, int n){
S = new int[n];for(int i = 0; i < n; i++)
S[i] = i;}//tim phan tu dai dien cua tap hop co chua xint Find(PInt &S, int x){
while(x != S[x])x = S[x];
return x;}
//hop nhat taphop co chua x va taphop co chua yvoid Union(PInt &S, int x, int y){
if(Find(S, x) != Find(S, y))S[x] = S[y];
}
void inputUDirectedGraph(Graph &g, char * fName){
ifstream inFile(fName);if(!inFile)
return;inFile >> g.V >> g.E;for(int i=0; i<g.V; i++){
Vertex u;u.id = i;g.vertex.push_back(u);
}for (int j=0; j<g.E; j++){
int u, v;double w;inFile >> u >> v >> w;g.vertex[u].adj.push_back(v);g.vertex[v].adj.push_back(u);Edge e;e.v1 = u;e.v2 = v;e.w = w;g.edge.push_back(e);
}inFile.close();
}void printVertex(Vertex &v){
cout << v.id << ": ";for ( int j=0; j<v.adj.size();j++){
cout<<" "<<v.adj[j];}cout<<"\n";
}void PrintEdge(Edge e){
cout << e.v1 << "," << e.v2 << "(" << e.w << ")" << "\n";}
Trang 22
void printGraph(Graph &g){
cout << "G(" << g.V << "," << g.E << ")\n";for(int i=0; i < g.V; i++)
printVertex(g.vertex[i]);for(int i=0; i< g.E; i++)
PrintEdge(g.edge[i]);}bool myComp(Edge e1, Edge e2){
return (e1.w < e2.w);}void Kruskal(Graph &g){
vector<Edge> A;PInt S;MakeSet(S, g.V);sort(g.edge.begin(), g.edge.end(), myComp);for(int i = 0; i < g.E; i++){
Edge e = g.edge[i];if(Find(S, e.v1) != Find(S, e.v2)){
A.push_back(e);Union(S,e.v1,e.v2);PrintEdge(e);
}}
}void main(){
Graph G;inputUDirectedGraph(G, "D:\\BFS.txt");printGraph(G);cout << "Running Kruskal...\n";Kruskal(G);
}// Nội dung trong file BFS.txt8 100 10 41 52 32 52 63 63 75 66 7
Thuật giả Merge_Sort
#include<stdio.h>#include<conio.h>#include<iostream>using namespace std;void Merge(int A[],int start,int middle,int end){ int i=start; int j=middle+1; int k=0; int n=end-start+1; int *B=new int[n]; while((i<middle+1)&&(j<end+1))
{ if(A[i]<A[j]) B[k++]=A[i++];
else B[k++]=A[j++]; } while(i<middle+1) B[k++]=A[i++]; while(j<end+1) B[k++]=A[j++]; i=start; for(k=0;k<n;k++) A[i++]=B[k]; delete[]B;}void MergeSort(int A[],int start, int end){ if(start<end)
{ int middle=(start+end)/2; MergeSort(A,start,middle); MergeSort(A,middle+1,end); Merge(A,start,middle,end); }}void main(){ int A[10]={1,3,6,4,8,5,9,11,10,15}; MergeSort(A,0,9); for(int i=0;i<10;i++)
cout<<A[i]<<"\t";}
Trang 23
//Cai dat thuat toan PRIM (tim cay khung co trong so nho nhat)//Su dung ma tran trong so#include<stdio.h>#include<conio.h>#define maxver 50#define VOCUC 30000typedef struct{
int Ver1;int Ver2;int W;
}ARC;typedef struct{
int nVer;int a[maxver][maxver];int TrongV[maxver];ARC T[maxver];int nT;int dem;
}GRAPH;void nhap(GRAPH &g);void xuat(GRAPH &g);void initData(GRAPH &g);int searchArc(GRAPH &g,ARC &e,int &x,int &y);int searchMinArc(GRAPH&g,ARC &e,int &x,int &y);int PrimAlg(GRAPH &g);
void main(){
GRAPH gr;nhap(gr);xuat(gr);
// getch();}void nhap(GRAPH &g){
FILE *f;f=fopen("dt_prim.txt","rt");fscanf(f,"%d",&g.nVer);for(int i=0;i<g.nVer;i++){
for(int j=0;j<g.nVer;j++)fscanf(f,"%d",&g.a[i][j]);
fscanf(f,"\n");}fclose(f);
}
Trang 24
void initData(GRAPH &g){
g.nT=0; g.dem=0;for(int i=0;i<g.nVer;i++)
g.TrongV[i]=0;g.TrongV[2]=1;
}int searchArc(GRAPH &g,ARC &e,int &x,int &y){
for(int i=0;i<g.nVer;i++)if(g.TrongV[i]==1)
for(int j=0;j<g.nVer;j++)if(g.TrongV[j]==0)
if(g.a[i][j]!=VOCUC){
x=i;y=j; e.Ver1=i; e.Ver2=j; e.W=g.a[i][j]; return 1;
}return 0;
}int searchMinArc(GRAPH &g,ARC &e,int &x,int &y){
int min,i,j;if(searchArc(g,e,x,y)==0)
return 0;//ko co canh
//Canh tim duoc//printf("\nCanh nho nhat: (%d, %d)- %d", e.Ver1, e.Ver2, e.W);min=e.W;for(i=0;i<g.nVer;i++)
if(g.TrongV[i]==1)for(j=0;j<g.nVer;j++)
if(g.TrongV[j]==0)if((g.a[i][j]!=VOCUC)&&(g.a[i][j]<min)){
min=g.a[i][j];x=i;y=j;e.W=g.a[i][j];e.Ver1=i;e.Ver2=j;//printf("\nCanh nho nhat: (%d, %d)- %d", e.Ver1, e.Ver2, e.W);
}return 1;
}int PrimAlg(GRAPH& g)
Trang 25
{initData(g);while(g.nT<g.nVer-1){
ARC e;int x,y;if(searchMinArc(g,e,x,y)==0)
return 0;g.dem=g.dem+e.W;g.T[g.nT]=e;g.TrongV[y] = 1;(g.nT)++;
}return 1;
}
void xuat(GRAPH &g){
int i;if(PrimAlg(g)==0)
printf("\nDo thi khong co cay khung!\n");else{
printf("\nDo thi co cay khung nho nhat voi so canh: ");printf("%d",g.nT);printf("\nTong trong so: %d",g.dem);printf("\n");for(i=0;i<g.nT;i++)
printf("%2d--->%2d: trong so %2d \n", g.T[i].Ver1, g.T[i].Ver2,g.T[i].W) ;}
}//Nội dung file dt_prim.txt
730000 7 0 30000 30000 30000 300007 30000 9 30000 2 30000 300000 9 30000 9 34 30000 3000030000 30000 9 30000 6 30000 3000030000 2 34 6 30000 2 1130000 30000 30000 30000 2 30000 130000 30000 30000 30000 11 1 30000
-------------------------------**************************** --------------------------------------
Trang 26
//Cai dat thuat toan KRUSKAL:(tim cay khung co trong so nho nhat)//-Duyet theo danh sach canh(sap xep canh theo thu tu trong so tang)//-DL la MT mang canh//-Ktra xem co tao chu trinh khong
#include<stdio.h>//#include<iostream.h>#include<conio.h>#include<dos.h>#define VOCUC 30000#define MAXVER 50#define MAXEDGE 100typedef struct{
int Ver1;int Ver2;int w;
}ARC;typedef struct{
int nVer;int L[MAXVER][MAXVER];ARC T[MAXVER-1]; //cay khung nho nhatint nT;ARC DS[MAXEDGE]; //danh sach canhint nDS;int dem;
}GRAPH;void Input(GRAPH&);void Output(GRAPH&);void ReadEdgeList(GRAPH&);void Sort(GRAPH&);int Kruskal(GRAPH&);
void main(){
GRAPH gr;Input(gr);Output(gr);
// getch();}void Input(GRAPH& g){
FILE *f;f=fopen("dt_kruskal.txt","rt");fscanf(f,"%d",&g.nVer);for(int i=0;i<g.nVer;i++){
for(int j=0;j<g.nVer;j++)fscanf(f,"%5d",&g.L[i][j]);
fscanf(f,"\n");}fclose(f);
}
Trang 27
void Output(GRAPH& g){
int i;Sort(g);printf("Danh sach canh sau khi da sap tang:\n");for(i=0;i<g.nDS;i++){
printf("%d-->%d:%d",g.DS[i].Ver1,g.DS[i].Ver2,g.DS[i].w);printf("\n");
}
if(Kruskal(g)==0)printf("\nDo thi khong lien thong\n");
else{
printf("Do thi trong so nho nhat co %d canh:\n",g.nT);for(i=0;i<g.nT;i++){ printf("%d-->%d:trong so %d",g.T[i].Ver1,g.T[i].Ver2,g.T[i].w); printf("\n");}printf("Tong trong so: %d",g.dem);
}}void InitData(GRAPH& g){
g.nT=0;}
void ReadEdgeList(GRAPH& g){
g.nDS=0;for(int i=0; i<g.nVer; i++)
for(int j=i; j<g.nVer; j++){
if(g.L[i][j]!=VOCUC)//||(g.L[j][i])){
g.DS[g.nDS].Ver1=i;g.DS[g.nDS].Ver2=j;g.DS[g.nDS].w=g.L[j][i];g.nDS++;
}}
}
void Sort(GRAPH& g){
ReadEdgeList(g);ARC tam;for(int i=0;i<g.nDS-1;i++)
for(int j=i+1;j<g.nDS;j++)if(g.DS[i].w>g.DS[j].w){
Trang 28
tam=g.DS[i];g.DS[i]=g.DS[j];g.DS[j]=tam;
}}
int Kruskal(GRAPH& g){
int i,j;int Sohieu[MAXVER];InitData(g);//Gan nhanfor(i=0; i<g.nVer; i++)
Sohieu[i]=i;j=0; g.dem=0;do{ //Mang Sohieu[] de kiem tra truong hop tao chu trinh
if(Sohieu[g.DS[j].Ver1]!=Sohieu[g.DS[j].Ver2]){
//Dua canh j vao cay Tg.T[g.nT].Ver1=g.DS[j].Ver1;g.T[g.nT].Ver2=g.DS[j].Ver2;g.T[g.nT].w=g.DS[j].w;g.dem=g.dem+g.T[g.nT].w;//Cap nhat lai so hieuint x=Sohieu[g.DS[j].Ver2];int y=Sohieu[g.DS[j].Ver1];for(int l=0; l<g.nVer; l++){
if(Sohieu[l]==y)Sohieu[l]=x;
}g.nT++;
}j++;
}while ((g.nT<g.nVer)&&(j<g.nDS));
if(g.nT<g.nVer-1) return 0;return 1;
}//Nội dung file dt_prim.txt
730000 7 0 30000 30000 30000 300007 30000 9 30000 2 30000 300000 9 30000 9 34 30000 3000030000 30000 9 30000 6 30000 3000030000 2 34 6 30000 2 1130000 30000 30000 30000 2 30000 130000 30000 30000 30000 11 1 30000
Trang 29