Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 40

DSĐLK

HASH
#include <iostream>
using namespace std;
#define M 10

struct Node
{
int key;
Node *next;
};

typedef Node *HashTable[M];

void InitHashTable(HashTable &HT)


{
for (int i = 0; i < M; i++)
HT[i] = NULL;
}

int Hash(int k)
{
return k % M;
}

void AddTail(Node *&l, int k)


{
Node *newNode = new Node{k, NULL};
if (l == NULL)
{
l = newNode;
}
else
{
Node* p = l;
while (p != NULL && p->next != NULL)
p = p->next;
p->next = newNode;
}
}

void InsertNode(HashTable &HT, int k)


{
int i = Hash(k);
AddTail(HT[i], k);
}

void DeleteHead(Node *&l)


{
if (l != NULL)
{
Node *p = l;
l = l->next;
delete p;
}
}

void DeleteAfter(Node *&q)


{
Node *p = q->next;
if (p != NULL)
{
q->next = p->next;
delete p;
}
}

void DeleteNode(HashTable &HT, int k)


{
int i = Hash(k);
Node *p = HT[i];
Node *q = p;
while (p != NULL && p->key != k)
{
q = p;
p = p->next;
}
if (p == NULL)
cout << k << " not found!" << endl;
else if (p == HT[i])
DeleteHead(HT[i]);
else
DeleteAfter(q);
}

Node *SearchNode(HashTable HT, int k)


{
int i = Hash(k);
Node *p = HT[i];
while (p != NULL && p->key != k)
p = p->next;
if (p == NULL)
return NULL;
return p;
}

void Traverse(Node *p)


{
while (p != NULL)
{
cout << p->key << ' ';
p = p->next;
}
cout << endl;
}

void TraverseHashTable(HashTable HT)


{
for (int i = 0; i < M; i++)
{
cout << "Bucket " << i << ": ";
Traverse(HT[i]);
}
}

int main()
{
HashTable mHashTable;
InitHashTable(mHashTable);

InsertNode(mHashTable, 0);
InsertNode(mHashTable, 1);
InsertNode(mHashTable, 2);
InsertNode(mHashTable, 3);
InsertNode(mHashTable, 10);
InsertNode(mHashTable, 13);
InsertNode(mHashTable, 9);
InsertNode(mHashTable, 11);

cout << "HashTable:\n";


TraverseHashTable(mHashTable);

DeleteNode(mHashTable, 3);
DeleteNode(mHashTable, 13);
DeleteNode(mHashTable, 9);
cout << "HashTable after Delete:\n";
TraverseHashTable(mHashTable);

Node *result = SearchNode(mHashTable, 10);


if (result == NULL)
cout << "Not found!";
else
cout << "Found!";

std::cout << std::endl;


system("pause");
return 0;
}

PRIORITY LINKED LIST C++


// Priority Queue Implementation.

#include <bits/stdc++.h>
using namespace std;

class Node {

// Data members of Node class.


public:
string data;
int priority;
Node* next;

// New node constructor.


Node(string data, int priority)
{
this->data = data;
this->priority = priority;
this->next = NULL;
}
};

class PriorityQueue {
Node* head;

public:
PriorityQueue()
{
head = new Node("Head", INT_MIN);
}
void pop()
{
// List is empty.
if(head->next == NULL)
return;

// Storing the first node in a temporary variable.


Node* temp = head->next;
// Shifting Next pointer of head node.
head->next = head->next->next; 

// Free the first node.


free(temp);
}

void push(string tskNumber, int priority)


{
Node* newnode = new Node(tskNumber, priority);
Node* temp = head;
if(isEmpty())
{
head->next = newnode;
}
else
{
while(temp->next && temp->next->priority<=priority)
{
temp = temp->next;
}
newnode->next = temp->next;
temp->next = newnode;
}
}

void print()
{
Node* temp = head;
while( temp->next )
{
temp = temp->next;
cout << temp->data << "  Priority:" << temp->priority <<endl;
}
}

void peek()
{
// Priority Queue is empty.
if(isEmpty())
{
cout<<"Nothing left to peek!\n";
}
else
{
cout << head->next->data << endl;
}
}

bool isEmpty()
{
// 'head' is pointing to a NULL pointer.
if(!head->next)
return true;
else
return false;
}

};

int main() 
{

// Dynamic Binding to the PriorityQueue class.


PriorityQueue* tasks = new PriorityQueue(); 
int numTasks;
cout << "Number of tasks?\n";
cin >> numTasks;

for(int i=0; i < numTasks; i++)


{
string tskName;
int priority;
cin >> tskName >> priority;
tasks->push( tskName, priority );
}

// Let's see the new order of tasks with their priorities.


cout << "\nOrder of tasks and their respective priority:\n";
tasks->print();

// Let's pop elements one by one and check the front of our Priority Queue.
cout<<"Time to Pop:\n";
do
{
cout << "Task at top: ";
tasks->peek();
tasks->pop();
} while( !tasks->isEmpty() );

}
PQ USING HEAP
// C++ code to implement priority-queue
// using array implementation of
// binary heap

#include <bits/stdc++.h>
using namespace std;

int H[50];
int size = -1;

// Function to return the index of the


// parent node of a given node
int parent(int i)
{

return (i - 1) / 2;
}

// Function to return the index of the


// left child of the given node
int leftChild(int i)
{

return ((2 * i) + 1);


}

// Function to return the index of the


// right child of the given node
int rightChild(int i)
{

return ((2 * i) + 2);


}

// Function to shift up the node in order


// to maintain the heap property
void shiftUp(int i)
{
while (i > 0 && H[parent(i)] < H[i]) {

// Swap parent and current node


swap(H[parent(i)], H[i]);

// Update i to parent of i
i = parent(i);
}
}

// Function to shift down the node in


// order to maintain the heap property
void shiftDown(int i)
{
int maxIndex = i;

// Left Child
int l = leftChild(i);

if (l <= size && H[l] > H[maxIndex]) {


maxIndex = l;
}

// Right Child
int r = rightChild(i);

if (r <= size && H[r] > H[maxIndex]) {


maxIndex = r;
}

// If i not same as maxIndex


if (i != maxIndex) {
swap(H[i], H[maxIndex]);
shiftDown(maxIndex);
}
}

// Function to insert a new element


// in the Binary Heap
void insert(int p)
{
size = size + 1;
H[size] = p;

// Shift Up to maintain heap property


shiftUp(size);
}

// Function to extract the element with


// maximum priority
int extractMax()
{
int result = H[0];

// Replace the value at the root


// with the last leaf
H[0] = H[size];
size = size - 1;

// Shift down the replaced element


// to maintain the heap property
shiftDown(0);
return result;
}

// Function to change the priority


// of an element
void changePriority(int i, int p)
{
int oldp = H[i];
H[i] = p;

if (p > oldp) {
shiftUp(i);
}
else {
shiftDown(i);
}
}
// Function to get value of the current
// maximum element
int getMax()
{

return H[0];
}

// Function to remove the element


// located at given index
void remove(int i)
{
H[i] = getMax() + 1;

// Shift the node to the root


// of the heap
shiftUp(i);

// Extract the node


extractMax();
}

// Driver Code
int main()
{

/* 45
/ \
31 14
/ \ / \
13 20 7 11
/ \
12 7
Create a priority queue shown in
example in a binary max heap form.
Queue will be represented in the
form of array as:
45 31 14 13 20 7 11 12 7 */

// Insert the element to the


// priority queue
insert(45);
insert(20);
insert(14);
insert(12);
insert(31);
insert(7);
insert(11);
insert(13);
insert(7);

int i = 0;

// Priority queue before extracting max


cout << "Priority Queue : ";
while (i <= size) {
cout << H[i] << " ";
i++;
}
cout << "\n";

// Node with maximum priority


cout << "Node with maximum priority : "
<< extractMax() << "\n";

// Priority queue after extracting max


cout << "Priority queue after "
<< "extracting maximum : ";
int j = 0;
while (j <= size) {
cout << H[j] << " ";
j++;
}

cout << "\n";

// Change the priority of element


// present at index 2 to 49
changePriority(2, 49);
cout << "Priority queue after "
<< "priority change : ";
int k = 0;
while (k <= size) {
cout << H[k] << " ";
k++;
}

cout << "\n";

// Remove element at index 3


remove(3);
cout << "Priority queue after "
<< "removing the element : ";
int l = 0;
while (l <= size) {
cout << H[l] << " ";
l++;
}
return 0;
}

SEARCH
int InterPolationSearch(int arr[], int n, int x)
{
  int left = 0;
  int right = n-1;
  while (left <= right && x >= arr[left] && x <= arr[right])
  {
    double val1 = (double) (x - arr[left]) / (arr[right]-arr[left]);
    int val2 = (right-left);
    int Search = left + val1*val2;
  
    if (arr[Search] == x)
      return Search;
  
    if (arr[Search] < x)
      left = Search + 1;
    else
      right = Search - 1;
  }
  return -1;
}

SORT
#include "sort.h"
#include <iostream>
#include <algorithm>
#include <math.h>
using namespace std;

// hoan vi 2 so nguyen
void Swap(int &x, int &y)
{
int temp = x;
x = y;
y = temp;
}

// in mang
void PrintArray(int *a, int n)
{
for (int i = 0; i < n; ++i)
cout << a[i] << " ";
cout << endl;
}

// 1: Selection Sort (da hoc)


void SelectionSort(int *a, int n)
{
int min_id; // luu vi tri cua phan tu nho nhat cua doan chua xet
for (int i = 0; i < n; ++i)
{
min_id = i;
for (int j = i + 1; j < n; ++j)
if (a[j] < a[min_id])
min_id = j; // luu lai vi tri phan tu nho nhat trong doan dang xet de tiep tuc xet

// chuyen phan tu nhu nhat len dau doan dang duoc xet
if (min_id != i)
Swap(a[i], a[min_id]);
}
}

// 2: Insertion Sort (da hoc)


void InsertionSort(int *a, int n)
{
for (int i = 1; i < n; ++i)
{
int temp = a[i]; // luu gia tri de sau chen dung vi tri
int j = i - 1; // xet cac phan tu phia sau de chen

// chuyen cac phan tu lon hon temp len 1 vi tri


while (j >= 0 && a[j] > temp)
{
a[j + 1] = a[j];
j--;
}
a[j + 1] = temp;
}
}

// 3: BubbleSort cai tien 2 (da hoc thay Phuong)


void BubbleSort(int *a, int n)
{
int k = n - 1; // lu lai vi tri doi cho cuoi cung cua lan duyet
bool check = false;
for (int i = n - 1; i >= 0; --i)
{
check = false;
i = k;
for (int j = 0; j < i; ++j)
if (a[j] > a[j + 1])
{
swap(a[j + 1], a[j]);
check = true; //co su dung sap xep
k = j + 1;
}

//neu ko co sap xep la mang da dung


if (check == false)
break;
}
}

//4: Shaker Sort cai tien cua BubbleSort (thay phuong huong dan)
void ShakerSort(int *a, int n)
{
int l = 1, r = n - 1, k = n - 1;
do
{
// dua phan tu lon nhat ve cuoi
for (int j = r; j >= l; j--)
if (a[j - 1] > a[j])
{
swap(a[j - 1], a[j]);
k = j;
}
l = k + 1;

// dua phan tu nho nhat ve dau


for (int j = l; j <= r; j++)
if (a[j] < a[j - 1])
{
swap(a[j], a[j - 1]);
k = j;
}
r = k - 1;

} while (l <= r);


}

// 5: ShellSort
void ShellSort(int *a, int n)
{
int k;
//k la so lan chia mang duoc tach ra de lam
k = log(n) / log(2); // tach theo n/2 nên k = log2(n)

int *h = new int[k];


h[k - 1] = 1;

for (int i = k - 1; i > 0; i--)


{
//h[] la mang cac khoang cach trong moi lan phan tach
h[i - 1] = h[i] * 2 + 1;
}

// sap xep cac doan da phan hoach


for (int step = k - 1; step > 0; step--)
{
int tmp = h[step];

//sap xep mang con bang InsertionSort


for (int i = tmp; i < n; i++)
{
int temp = a[i];
int j = i - tmp;
while (temp < a[j] && j >= 0)
{
a[j + tmp] = a[j];
j = j - tmp;
}
a[j + tmp] = temp;
}
}
}

// 6: HeapSort: Duoc thay Phuong huong dan y tuong


void sift(int a[], int left, int right)
{
int i = left;
int j = 2 * i + 1;
int x = a[i];
while (j <= right)
{
if (j < right)
//max heap
if (a[j] < a[j + 1]) //min heap: a[j]>a[j+1] j++;
j = j + 1;
if (x >= a[j]) //x<= a[j]
break;
a[i] = a[j];
i = j;
j = 2 * i + 1;
}
a[i] = x;
}

// ham heap sort chinh


void HeapSort(int a[], int n)
{
int left = (n - 1) / 2;
int right = n - 1;
while (left >= 0)
{
sift(a, left, right);
left--;
}
//tao ra heap
while (right > 0)
{
swap(a[0], a[right]);
right--;
sift(a, 0, right);
}
}

//7.Merge Sort
void merge(int *a, int l, int m, int r)
{
int n1 = m - l + 1;
int n2 = r - m;

// Tao 2 mang luu 2 mang duoc chia


int *L = new int[n1]; // luu doan l -> m
int *R = new int[n2]; // luu doan m+ 1 r

// sao chep du lieu tuong ung vao 2 mang


for (int i = 0; i < n1; i++)
L[i] = a[l + i];
for (int j = 0; j < n2; j++)
R[j] = a[m + 1 + j];

// Tron 2 mang con lai de duoc mang sap xep

// vi tri dau tien cua con L


int i = 0;
// Vi tri dau tien cua mang con R
int j = 0;
// vi tri dau cua mang sau khi hop nhat
int k = l;

while (i < n1 && j < n2)


{
if (L[i] <= R[j])
{
a[k] = L[i];
i++;
}
else
{
a[k] = R[j];
j++;
}
k++;
}

// copy doan con lai cua L neu chua duoc tron vao
while (i < n1)
{
a[k] = L[i];
i++;
k++;
}

// copy doan con lai cua L neu chua duoc tron vao
while (j < n2)
{
a[k] = R[j];
j++;
k++;
}
}

//
void MergeSort(int *a, int l, int r)
{
if (l >= r)
{
return; // mang da sap xep xong
}
int m = (l + r - 1) / 2;
// chia doi mang lien tuc de tron
MergeSort(a, l, m);
MergeSort(a, m + 1, r);
merge(a, l, m, r);
}

//8.Quick Sort (duoc hoc luc cap 2)


void QuickSort(int *a, int l, int r)
{
int x = (l + r) / 2;
int pivot = a[x]; // chon phan tu o giua lam pivot
int i, j;
i = l;
j = r;
do
{
while (a[i] < pivot)
i++; // neu nho hon pivot thi xet so ke tiep
while (a[j] > pivot)
j--; // neu lon hon pivot thi lui ve truoc de xet
if (i <= j)
{
Swap(a[i], a[j]);
i++;
j--;
}
} while (i < j);
if (l < j)
QuickSort(a, l, j); // goi lai de xet
if (i < r)
QuickSort(a, i, r); // goi lai de xet
}

//9.Counting Sort (Thay Phuong day)


void CountingSort(int *a, int n)
{

int *b = new int[n];


int Max = a[0];
for (int i = 0; i < n; i++)
{
if (a[i] > Max)
Max = a[i];
}

int *f = new int[Max + 1]{0};

for (int i = 0; i < n; i++)


f[a[i]]++;

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


f[i] += f[i - 1];
for (int i = n - 1; i >= 0; i--)
{
b[f[a[i]] - 1] = a[i];
f[a[i]]--;
}
for (int i = 0; i < n; i++)
a[i] = b[i];

delete[] f;
delete[] b;
}

//10.Radix Sort (Thay Phuong day)

// lay chu so hang k (don vi: k =1 ..->)


int digit(int n, int k)
{
int temp = n % (int)pow(10, k);
return temp / pow(10, k - 1);
}

// CountingSort cua tung chu so cua cac phan tu a


void sort(int a[], int n, int k)
{
int *b = new int[n];
int *f = new int[10]{0}; // luu tan xuat cua cac chu so

for (int i = 0; i < n; i++)


f[digit(a[i], k)]++;

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


f[i] += f[i - 1];
for (int i = n - 1; i >= 0; i--)
{
int temp = digit(a[i], k);
b[f[temp] - 1] = a[i];
f[temp]--;
}
for (int i = 0; i < n; i++)
a[i] = b[i];

delete[] f;
delete[] b;
}
void RadixSort(int a[], int n)
{
int max = a[0], maxk = 0;
for (int i = 1; i < n; i++)
{
if (max < a[i])
max = a[i];
}
while (max != 0)
{
max = max / 10;
maxk++;
}
for (int i = 1; i <= maxk; i++)
sort(a, n, i);
}

// 11: FlashSort (Thay phuong day)


void FlashSort(int *a, int n)
{
//Giai doan 1:
// tu chon so phan lop la (0.43 * n) (thay noi chon nhu nay chay nhanh nhat)
int Min = a[0];
int max_pos = 0;
int m = int(0.43 * n);

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


{
if (a[i] < Min)
Min = a[i];
if (a[i] > a[max_pos])
max_pos = i;
}

if (a[max_pos] == Min)
return;

int *L = new int[m];


for (int i = 0; i < m; i++)
L[i] = 0;

double Temp = (double)(m - 1) / (a[max_pos] - Min);


for (int i = 0; i < n; i++)
{
int k = int(Temp * (a[i] - Min));
++L[k];
}
for (int i = 1; i < m; i++)
L[i] += L[i - 1];
swap(a[max_pos], a[0]);
//Phan vung thu m-1 chi chua max (co the co nhieu a[i] = max)
//L[k] se chi vao bien ben phai cua phan lop thu k
//Giai doan 2:
int j = 0;
int k = m - 1;
int cnt = 0;
int Save = 0;
while (cnt < n - 1)
{
while (j > L[k] - 1)
{
j++;
k = int(Temp * (a[j] - Min));
}
Save = a[j];
if (k < 0)
break;
while (j != L[k])
{
k = int(Temp * (Save - Min));
Swap(Save, a[--L[k]]);
cnt++;
}
}

//Giai doan 3
//Phan lop thu m-1 da duoc xap
//Phan lop k: L[k]->L[k+1]-1
//dung insertionSort sap thu phai -> trai
int l, r, mid, tmp;
for (int i = 1; i < n; i++)
{
l = 0;
r = i - 1;
tmp = a[i];
while (l <= r)
{
mid = (r + l) / 2;
if (a[mid] > tmp)
r = mid - 1;
else
l = mid + 1;
}
for (j = i - 1; j >= l; j--)
a[j + 1] = a[j];
a[l] = tmp;
}

delete[] L;
}

BST
//BST function
Typedef struct NODE* Ref;
struct NODE {
int key;
NODE* pLeft, * pRight;
};

1. Initialize a NODE from a given value:


NODE* createNode(int data) {
NODE* p = new NODE;
p->key = data;
p->pLeft = p->pRight = NULL;
return p;
}
// 2. Add a NODE with given value into a given Binary Search Tree:
void Insert(NODE*& pRoot, int x) {
if (pRoot == NULL) {
pRoot = createNode(x);
return;
}
if (x < pRoot->key) Insert(pRoot->pLeft, x);
else if (x > pRoot->key) Insert(pRoot->pRight, x);

// 3. Pre-order Traversal:
void NLR(NODE* pRoot) {
if (pRoot == NULL) return;
cout << pRoot->key << " ";
NLR(pRoot->pLeft);
NLR(pRoot->pRight);
}

// 4. In-order Traversal:
void LNR(NODE* pRoot) {
if (pRoot == NULL) return;
LNR(pRoot->pLeft);
cout << pRoot->key << " ";
LNR(pRoot->pRight);
}

// 5. Post-order Traversal:
void LRN(NODE* pRoot) {
if (pRoot == NULL) return;
LRN(pRoot->pLeft);
LRN(pRoot->pRight);
cout << pRoot->key << " ";
}

// 6. Level-order Traversal:
void LevelOrder(NODE* pRoot) {
if (pRoot == NULL) return;
queue<NODE*> q;
q.push(pRoot);
while (!q.empty()) {
NODE* p = q.front();
q.pop();
cout << p->key << " ";
if (p->pLeft != NULL) q.push(p->pLeft);
if (p->pRight != NULL) q.push(p->pRight);
}

// 7. Calculate the height of a given Binary Tree;


int Height(NODE* pRoot) {
if (pRoot == NULL) return -1;
int hLeft = Height(pRoot->pLeft);
int hRight = Height(pRoot->pRight);
return 1 + max(hLeft, hRight);

}
// 8. Count the number of NODE from a given Binary Tree:
int countNode(NODE* pRoot) {
if (pRoot == NULL) return 0;
return 1 + countNode(pRoot->pLeft) + countNode(pRoot->pRight);

// 9. Calculate the total value of all NODEs from a given Binary Tree:
int sumNode(NODE* pRoot) {
if (pRoot == NULL) return 0;
return pRoot->key + sumNode(pRoot->pLeft) + sumNode(pRoot->pRight);
}

// 10. Find and return a NODE with given value from a given Binary Search Tree:
NODE* Search(NODE* pRoot, int x) {
if (pRoot == NULL) return NULL;
if (pRoot->key == x) return pRoot;
if (x < pRoot->key) return Search(pRoot->pLeft, x);
return Search(pRoot->pRight, x);
}

// 11. Remove a NODE with given value from a given Binary Search Tree:
void Remove(NODE*& pRoot, int x) {
if (pRoot == NULL) return;
if (x < pRoot->key) Remove(pRoot->pLeft, x);
else if (x > pRoot->key) Remove(pRoot->pRight, x);
else {
if (pRoot->pLeft == NULL && pRoot->pRight == NULL) {
delete pRoot;
pRoot = NULL;
}
else if (pRoot->pLeft == NULL) {
NODE* p = pRoot;
pRoot = pRoot->pRight;
delete p;
}
else if (pRoot->pRight == NULL) {
NODE* p = pRoot;
pRoot = pRoot->pLeft;
delete p;
}
else {
NODE* p = pRoot->pRight;
while (p->pLeft != NULL) p = p->pLeft;
pRoot->key = p->key;
Remove(pRoot->pRight, p->key);
}
}
}

// 12. Initialize a Binary Search Tree from a given array:


NODE* createTree(int a[], int n) {
NODE* pRoot = NULL;
for (int i = 0; i < n; i++) Insert(pRoot, a[i]);
return pRoot;

}
// 13. Completely remove a given Binary Search Tree:
void removeTree(NODE*& pRoot) {
if (pRoot == NULL) return;
removeTree(pRoot->pLeft);
removeTree(pRoot->pRight);
delete pRoot;
pRoot = NULL;
}

// 14. Calculate the height of aNODEwith given value:(return -1 if value not exist)
int heightNode(NODE* pRoot, int value) {
if (pRoot == NULL) return -1;
if (pRoot->key == value) return Height(pRoot);
if (value < pRoot->key) return heightNode(pRoot->pLeft, value);
return heightNode(pRoot->pRight, value);
}

// 15. * Calculate the level of a given NODE:


int Level(NODE* pRoot, NODE* p) {
if (pRoot == NULL) return -1;
if (pRoot == p) return 1;
int levelLeft = Level(pRoot->pLeft, p);
if (levelLeft != -1) return 1 + levelLeft;
int levelRight = Level(pRoot->pRight, p);
if (levelRight != -1) return 1 + levelRight;
return -1;

// 16. * Count the number leaves from a given Binary Tree:


int countLeaf(NODE* pRoot) {
if (pRoot == NULL) return 0;
if (pRoot->pLeft == NULL && pRoot->pRight == NULL) return 1;
return countLeaf(pRoot->pLeft) + countLeaf(pRoot->pRight);

// 17. * Count the number ofNODEfrom a given Binary Search Tree which key value is less than a given value:
int countLess(NODE* pRoot, int x) {
if (pRoot == NULL) return 0;
if (pRoot->key < x) return 1 + countLess(pRoot->pLeft, x) + countLess(pRoot->pRight, x);
return countLess(pRoot->pLeft, x);

// 18. * Count the number ofNODEfrom a given Binary Search Tree which key value is greater than agiven value:
int countGreater(NODE* pRoot, int x) {
if (pRoot == NULL) return 0;
if (pRoot->key > x) return 1 + countGreater(pRoot->pLeft, x) + countGreater(pRoot->pRight, x);
return countGreater(pRoot->pRight, x);

// 19. * Determine if a given Binary Tree is Binary Search Tree:


bool isBST(NODE* pRoot) {
if (pRoot == NULL) return true;
if (pRoot->pLeft != NULL && pRoot->pLeft->key > pRoot->key) return false;
if (pRoot->pRight != NULL && pRoot->pRight->key < pRoot->key) return false;
return isBST(pRoot->pLeft) && isBST(pRoot->pRight);
}

// 20. * Determine if a given Binary Tree is a Full Binary Search Tree:


bool isFullBST(NODE* pRoot) {
if (pRoot == NULL) return true;
if (pRoot->pLeft == NULL && pRoot->pRight == NULL) return true;
if (pRoot->pLeft != NULL && pRoot->pRight != NULL) return isFullBST(pRoot->pLeft) && isFullBST(pRoot-
>pRight);
return false;
}

AVL
//AVL
struct AVLNode
{
int p, q, r;
AVLNode* pLeft;
AVLNode* pRight;
};

// tao node moi


AVLNode* createNode(int pInp, int qInp, int rInp)
{
AVLNode* newNode = new AVLNode;
// gan cac gia tri cho node moi
newNode->p = pInp;
newNode->q = qInp;
newNode->r = rInp;
newNode->pLeft = newNode->pRight = NULL;
return newNode;
}

// ham so sanh 2 hon so


int Compare(int p, int q, int r, int x, int y, int z)
{
if ((double)((p * r + q) / r) > (double)((x * z + y) / z))
return 1;
if ((double)((p * r + q) / r) < (double)((x * z + y) / z))
return -1;
return 0;
}

// tim so lon nhat


int Max(int a, int b)
{
return (a > b) ? a : b;
}

// tinh chieu cao


int Height(AVLNode* root)
{
if (root != NULL)
return Max(Height(root->pLeft), Height(root->pRight)) + 1;
return 0;
}
// tim he so can bang
int getBalance(AVLNode* root)
{
if (root == NULL)
return 0;
return Height(root->pLeft) - Height(root->pRight);
}

// xoay trai
AVLNode* leftRotate(AVLNode*& root)
{
AVLNode* p = root->pRight;
root->pRight = p->pLeft;
p->pLeft = root;

return p;
}

// xoay phai
AVLNode* rightRotate(AVLNode*& root)
{
AVLNode* p = root->pLeft;
root->pLeft = p->pRight;
p->pRight = root;

return p;
}

// chen them 1 node


void Insert(AVLNode*& root, int pInp, int qInp, int rInp)
{
if (root == NULL)
root = createNode(pInp, qInp, rInp);
int compare = Compare(pInp, qInp, rInp, root->p, root->q, root->r);
if (compare == -1)
Insert(root->pLeft, pInp, qInp, rInp);
else if (compare == 1)
Insert(root->pRight, pInp, qInp, rInp);
else
return;

int balance = getBalance(root);


// Th: LL
if (balance > 1 && Compare(pInp, qInp, rInp, root->pLeft->p, root->pLeft->q, root->pLeft->r) == -1)
root = rightRotate(root);
// TH: RR
if (balance < -1 && Compare(pInp, qInp, rInp, root->pRight->p, root->pRight->q, root->pRight->r) == 1)
root = leftRotate(root);
// TH: LR
if (balance > 1 && Compare(pInp, qInp, rInp, root->pLeft->p, root->pLeft->q, root->pLeft->r) == 1)
{
root->pLeft = leftRotate(root->pLeft);
root = rightRotate(root);
}
// TH: RL
if (balance < -1 && Compare(pInp, qInp, rInp, root->pRight->p, root->pRight->q, root->pRight->r) == -1)
{
root->pRight = rightRotate(root->pRight);
root = leftRotate(root);
}
}

void del(AVLNode*& root, AVLNode*& Temp)


{
if (root->pRight != NULL)
del(root->pRight, Temp);
else
{
Temp->p = root->p;
Temp->q = root->q;
Temp->r = root->r;
Temp = root;
root = root->pLeft;
}
}

// xoa 1 node co gia tri (p, q, r)


void Remove(AVLNode*& root, int pInp, int qInp, int rInp)
{
if (root == NULL)
return;
int compare = Compare(pInp, qInp, rInp, root->p, root->q, root->r);
if (compare == -1)
Remove(root->pLeft, pInp, qInp, rInp);
else if (compare == 1)
Remove(root->pRight, pInp, qInp, rInp);
else
{
AVLNode* qq = root;
if (qq->pRight == NULL)
root = qq->pLeft;
else if (qq->pLeft == NULL)
root = root->pRight;
else
del(root->pLeft, qq);
delete qq;
}
if (root == NULL)
return;

int balance = getBalance(root);


// TH: LL
if (balance > 1 && getBalance(root->pLeft) >= 0)
root = rightRotate(root);
// TH: RR
if (balance < -1 && getBalance(root->pRight) >= 0)
root = leftRotate(root);
// TH: LR
if (balance > 1 && getBalance(root->pLeft) < 0)
{
root->pLeft = leftRotate(root->pLeft);
root = rightRotate(root);
}
// TH: RL
if (balance < -1 && getBalance(root->pRight) > 0)
{
root->pRight = rightRotate(root->pRight);
root = leftRotate(root);
}
}

// tao cay AVL tu mang gia tri


AVLNode* CreateTree(vector<int> pList, vector<int> qList, vector<int> rList)
{
AVLNode* root = NULL;
for (int i = 0; i < pList.size(); i++)
Insert(root, pList[i], qList[i], rList[i]);
return root;
}

// duyet cay AVL theo muc


void LevelOrder(AVLNode* root)
{
if (root == NULL)
return;
else
{
// AVLNode* cur = root;
vector<AVLNode*> queue;
queue.push_back(root);
while (!queue.empty())
{
int p = queue.front()->p;
int q = queue.front()->q;
int r = queue.front()->r;
AVLNode* cur = queue.front();
queue.erase(queue.begin()); // xoa node dau vua duoc lay ra

cout << "(" << p << ", " << q << ", " << r << ") ";

if (cur->pLeft != NULL)
queue.push_back(cur->pLeft);
if (cur->pRight != NULL)
queue.push_back(cur->pRight);
}
}
cout << endl;
}

//=================//
//check avl
bool AVL(AVLNode* root) {
int lh;
int rh;
if (root == NULL)
return 1;
lh = Height(root->pLeft); // left height
rh = Height(root->pRight); // right height
if (abs(lh - rh) <= 1 && AVL(root->pLeft) && AVL(root->pRight)) return 1;
return 0;
}

MERGE
//Merge two BST
/* A binary tree node has data,
a pointer to left child
and a pointer to right child */
class Node {
public:
int data;
Node* left;
Node* right;
};

// Function to return a new Node


Node* newNode(int data)
{
Node* node = new Node();
node->data = data;
node->left = NULL;
node->right = NULL;

return (node);
}

// Function to convert bst to


// a doubly linked list
void bstTodll(Node* root, Node*& head)
{
// if root is NULL
if (!root)
return;

// Convert right subtree recursively


bstTodll(root->right, head);

// Update root
root->right = head;

// if head is not NULL


if (head) {

// Update left of the head


head->left = root;
}

// Update head
head = root;

// Convert left subtree recursively


bstTodll(root->left, head);
}

// Function to merge two sorted linked list


Node* mergeLinkedList(Node* head1, Node* head2)
{

/*Create head and tail for result list*/


Node* head = NULL;
Node* tail = NULL;

while (head1 && head2) {


if (head1->data < head2->data) {

if (!head)
head = head1;
else {

tail->right = head1;
head1->left = tail;
}

tail = head1;
head1 = head1->right;
}

else {

if (!head)
head = head2;
else {
tail->right = head2;
head2->left = tail;
}

tail = head2;
head2 = head2->right;
}
}

while (head1) {
tail->right = head1;
head1->left = tail;
tail = head1;
head1 = head1->right;
}

while (head2) {
tail->right = head2;
head2->left = tail;
tail = head2;
head2 = head2->right;
}

// Return the created DLL


return head;
}

// function to convert list to bst


Node* sortedListToBST(Node*& head, int n)
{
// if no element is left or head is null
if (n <= 0 || !head)
return NULL;

// Create left part from the list recursively


Node* left = sortedListToBST(head, n / 2);

Node* root = head;


root->left = left;
head = head->right;

// Create left part from the list recursively


root->right = sortedListToBST(head, n - (n / 2) - 1);

// Return the root of BST


return root;
}

// This function merges two balanced BSTs


Node* mergeTrees(Node* root1, Node* root2, int m, int n)
{
// Convert BSTs into sorted Doubly Linked Lists

Node* head1 = NULL;


bstTodll(root1, head1);
head1->left = NULL;

Node* head2 = NULL;


bstTodll(root2, head2);
head2->left = NULL;

// Merge the two sorted lists into one


Node* head = mergeLinkedList(head1, head2);

// Construct a tree from the merged lists


return sortedListToBST(head, m + n);
}

void printInorder(Node* node)


{
// if current node is NULL
if (!node) {
return;
}

printInorder(node->left);

// Print node of current data


cout << node->data << " ";

printInorder(node->right);
}

/* Driver code*/
int main()
{
/* Create following tree as first balanced BST
100
/\
50 300
/\
20 70 */

Node* root1 = newNode(100);


root1->left = newNode(50);
root1->right = newNode(300);
root1->left->left = newNode(20);
root1->left->right = newNode(70);
/* Create following tree as second balanced BST
80
/\
40 120
*/
Node* root2 = newNode(80);
root2->left = newNode(40);
root2->right = newNode(120);

// Function Call
Node* mergedTree = mergeTrees(root1, root2, 5, 3);

cout << "Following is Inorder traversal of the merged "


"tree \n";
printInorder(mergedTree);

return 0;
}

GRAPH
//GRAPH

//read and write file

vector< vector<int> > fileIn(const char* filename)


{
vector< vector<int> > arr;
ifstream in(filename);
if (in)
{
for (string line; getline(in, line); )
{
stringstream ss(line);
vector<int> row;
for (int i; ss >> i; ) row.push_back(i);
arr.push_back(row);
}
}
else
{
cerr << "Boo! No such file\n";
}
return arr;
}

int main()
{
const char* FILE_NAME = "in.txt";
vector< vector<int> > A = fileIn(FILE_NAME);
// for ( auto & row : A )
// {
// for ( auto e : row ) cout << e << '\t';
// cout << '\n';
// }

ofstream out("out.txt");
for (auto& row : A)
{
for (auto e : row)
out << e << " ";
out << "\n";
}
}

//
bool isBowtie(vector<vector<bool>> adj)
{
int n = adj.size();
if (n != 5) // so dinh khac 5 la sai
return false;
int deg2 = 0, deg4 = 0; // deg2 la so dinh co deg la 2, deg 4 tuong tu co deg la 4
for (int i = 0; i < n; i++)
{
if (adj[i][i] == 1)
return false; // do thi co khuyen
int cnt = 0;
for (int j = 0; j < n; j++)
cnt += adj[i][j];
if (cnt == 4)
deg4++;
else if (cnt == 2)
deg2++;
}
return (deg4 == 1 && deg2 == 4);
}

//DFS adjacency matrix


#include <bits/stdc++.h>
using namespace std;

// adjacency matrix
vector<vector<int> > adj;

// function to add edge to the graph


void addEdge(int x, int y)
{
adj[x][y] = 1;
adj[y][x] = 1;
}

// function to perform DFS on the graph


void dfs(int start, vector<bool>& visited)
{

// Print the current node


cout << start << " ";

// Set current node as visited


visited[start] = true;

// For every node of the graph


for (int i = 0; i < adj[start].size(); i++) {
// If some node is adjacent to the current node
// and it has not already been visited
if (adj[start][i] == 1 && (!visited[i])) {
dfs(i, visited);
}
}
}

int main()
{
// number of vertices
int v = 5;

// number of edges
int e = 4;

// adjacency matrix
adj = vector<vector<int> >(v, vector<int>(v, 0));

addEdge(0, 1);
addEdge(0, 2);
addEdge(0, 3);
addEdge(0, 4);

// Visited vector to so that


// a vertex is not visited more than once
// Initializing the vector to false as no
// vertex is visited at the beginning
vector<bool> visited(v, false);

// Perform DFS
dfs(0, visited);
}

//BFS using matrix


#include<bits/stdc++.h>
using namespace std;

vector<vector<int>> adj;

// function to add edge to the graph


void addEdge(int x, int y)
{
adj[x][y] = 1;
adj[y][x] = 1;
}

// Function to perform BFS on the graph


void bfs(int start)
{
// Visited vector to so that
// a vertex is not visited more than once
// Initializing the vector to false as no
// vertex is visited at the beginning
vector<bool> visited(adj.size(), false);
vector<int> q;
q.push_back(start);
// Set source as visited
visited[start] = true;

int vis;
while (!q.empty()) {
vis = q[0];

// Print the current node


cout << vis << " ";
q.erase(q.begin());

// For every adjacent vertex to the current vertex


for (int i = 0; i < adj[vis].size(); i++) {
if (adj[vis][i] == 1 && (!visited[i])) {

// Push the adjacent node to the queue


q.push_back(i);

// Set
visited[i] = true;
}
}
}
}

// Driver code
int main()
{
// number of vertices
int v = 5;

// adjacency matrix
adj = vector<vector<int>>(v, vector<int>(v, 0));

addEdge(0, 1);
addEdge(0, 2);
addEdge(1, 3);

// perform bfs on the graph


bfs(0);
}

//PRIM
#include <stdio.h>

#include <algorithm>
#include <iostream>
#include <queue>
#include <vector>
using namespace std;

typedef pair<int, int> ii;


const int N = 100005, oo = 0x3c3c3c3c;
int n, m, d[N];
vector<int> a[N], b[N];

int prim(int u) {
int Sum = 0;
priority_queue<ii> qu;
for (int i = 1; i <= n; i++) d[i] = oo;
qu.push(ii(0, u));
d[u] = 0;

while (qu.size()) {
ii Pop = qu.top();
qu.pop();
int u = Pop.second, du = -Pop.first;
if (du != d[u]) continue;
Sum += d[u];
d[u] = 0;

for (int i = 0; i < a[u].size(); ++i) {


int v = a[u][i];
if (d[v] > b[u][i]) {
d[v] = b[u][i];
qu.push(ii(-d[v], v));
}
}
}
return Sum;
}

int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= m; i++) {
int x, y, z;
scanf("%d%d%d", &x, &y, &z);
a[x].push_back(y);
b[x].push_back(z);
a[y].push_back(x);
b[y].push_back(z);
}
cout << prim(1) << endl;
}

TSP
#include<iostream>
using namespace std;
#define MAX 9999
int n = 4; // Number of the places want to visit
//Next distan array will give Minimum distance through all the position
int distan[10][10] = {
{0, 10, 15, 20},
{10, 0, 35, 25},
{15, 35, 0, 30},
{20, 25, 30, 0}
};
int completed_visit = (1 << n) - 1;
int DP[16][4];
int TSP(int mark, int position) {
if (mark == completed_visit) { // Initially checking whether all
// the places are visited or not
return distan[position][0];
}
if (DP[mark][position] != -1) {
return DP[mark][position];
}
//Here we will try to go to every other places to take the minimum
// answer
int answer = MAX;
//Visit rest of the unvisited cities and mark the . Later find the
//minimum shortest path
for (int city = 0;city < n;city++) {
if ((mark & (1 << city)) == 0) {
int newAnswer = distan[position][city] + TSP(mark | (1 << city), city);
answer = min(answer, newAnswer);
}
}
return DP[mark][position] = answer;
}
int main() {
/* initialize the DP array */
for (int i = 0;i < (1 << n);i++) {
for (int j = 0;j < n;j++) {
DP[i][j] = -1;
}
}
cout << "Minimum Distance Travelled by you is " << TSP(1, 0);
return 0;
}

COUNT PATH
#include<iostream>
using namespace std;

bool check[100001];
int a[1001][1001];
int dp[100001];
int n, m, s , t;

int cal(int idx)


{
if (idx == t) return dp[idx] = 1;
if (check[idx] == true) return dp[idx];
check[idx] = true;

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


if (a[idx][i] == 1)
dp[idx] += cal(i);

return dp[idx];
}

void trace(int idx)


{
if (idx == t)
{
cout << t << "\n";
return;
}
for (int i = 1; i <= n; i++)
if (a[idx][i] == 1 && dp[i] != 0)
{

cout << idx << " ";


trace(i);
}
}

int main()
{
cin >> n >> m >> s >> t;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++) cin >> a[i][j];

cout << cal(s) << "\n";


trace(s);
}
ĐẾM SỐ TP LIÊN THÔNG
int TPLien_Thong(int** A, int n) {
char* DanhDau = new char[n];
char ThanhCong;
int Dem = 0, i, j, MLT = 0;
for (i = 0; i < n; i++) //Khởi tạo mọi đỉnh chưa được đánh dấu
DanhDau[i] = 0;
do {
j = 0;
while (DanhDau[j] == 1) //B1: Tìm 1 đỉnh chưa được đánh dấu
j++;
DanhDau[j] = 1; //Đánh dấu đỉnh tìm được
Dem++; //Tăng số đỉnh được đánh dấu lên 1
MLT++; //Tăng miền liên thông lên 1
do {
ThanhCong = 0; //Giả sử không còn khả năng loang
for (i = 0; i < n; i++)
if (DanhDau[i] == 1)
for (j = 0; j < n; j++)
if (DanhDau[j] == 0 && A[i][j] > 0) {
DanhDau[j] = 1;
ThanhCong = 1; //Còn khả năng loang
Dem++;
if (Dem == n) return MLT;
}
} while (ThanhCong == 1); //Lặp khi còn khả năng loang
} while (Dem < n); //Lặp khi còn tồn tại đỉnh chưa được dánh dấu
return MLT;
}

KIEM TRA CO DUONG DI GIUA HAI DINH KHONG


// C++ program to check if there is exist a path between two vertices
// of a graph.
#include<iostream>
#include <list>
using namespace std;

// This class represents a directed graph using adjacency list


// representation
class Graph
{
int V; // No. of vertices
list<int>* adj; // Pointer to an array containing adjacency lists
public:
Graph(int V); // Constructor
void addEdge(int v, int w); // function to add an edge to graph
bool isReachable(int s, int d);
};

Graph::Graph(int V)
{
this->V = V;
adj = new list<int>[V];
}

void Graph::addEdge(int v, int w)


{
adj[v].push_back(w); // Add w to v’s list.
}

// A BFS based function to check whether d is reachable from s.


bool Graph::isReachable(int s, int d)
{
// Base case
if (s == d)
return true;

// Mark all the vertices as not visited


bool* visited = new bool[V];
for (int i = 0; i < V; i++)
visited[i] = false;

// Create a queue for BFS


list<int> queue;

// Mark the current node as visited and enqueue it


visited[s] = true;
queue.push_back(s);

// it will be used to get all adjacent vertices of a vertex


list<int>::iterator i;

while (!queue.empty())
{
// Dequeue a vertex from queue and print it
s = queue.front();
queue.pop_front();

// Get all adjacent vertices of the dequeued vertex s


// If a adjacent has not been visited, then mark it visited
// and enqueue it
for (i = adj[s].begin(); i != adj[s].end(); ++i)
{
// If this adjacent node is the destination node, then
// return true
if (*i == d)
return true;
// Else, continue to do BFS
if (!visited[*i])
{
visited[*i] = true;
queue.push_back(*i);
}
}
}

// If BFS is complete without visiting d


return false;
}

// Driver program to test methods of graph class


int main()
{
// Create a graph given in the above diagram
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);

int u = 1, v = 3;
if (g.isReachable(u, v))
cout << "\n There is a path from " << u << " to " << v;
else
cout << "\n There is no path from " << u << " to " << v;

u = 3, v = 1;
if (g.isReachable(u, v))
cout << "\n There is a path from " << u << " to " << v;
else
cout << "\n There is no path from " << u << " to " << v;

return 0;
}

You might also like