Tailieu DSA
Tailieu DSA
Tailieu DSA
HASH
#include <iostream>
using namespace std;
#define M 10
struct Node
{
int key;
Node *next;
};
int Hash(int k)
{
return k % M;
}
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);
DeleteNode(mHashTable, 3);
DeleteNode(mHashTable, 13);
DeleteNode(mHashTable, 9);
cout << "HashTable after Delete:\n";
TraverseHashTable(mHashTable);
#include <bits/stdc++.h>
using namespace std;
class Node {
class PriorityQueue {
Node* head;
public:
PriorityQueue()
{
head = new Node("Head", INT_MIN);
}
void pop()
{
// List is empty.
if(head->next == NULL)
return;
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()
{
// 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;
return (i - 1) / 2;
}
// Update i to parent of i
i = parent(i);
}
}
// Left Child
int l = leftChild(i);
// Right Child
int r = rightChild(i);
if (p > oldp) {
shiftUp(i);
}
else {
shiftDown(i);
}
}
// Function to get value of the current
// maximum element
int getMax()
{
return H[0];
}
// 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 */
int i = 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;
}
// chuyen phan tu nhu nhat len dau doan dang duoc xet
if (min_id != i)
Swap(a[i], a[min_id]);
}
}
//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;
// 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)
//7.Merge Sort
void merge(int *a, int l, int m, int r)
{
int n1 = m - l + 1;
int n2 = r - m;
// 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);
}
delete[] f;
delete[] b;
}
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);
}
if (a[max_pos] == Min)
return;
//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;
};
// 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);
}
}
// 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);
}
}
}
}
// 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);
}
// 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);
AVL
//AVL
struct AVLNode
{
int p, q, r;
AVLNode* pLeft;
AVLNode* 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;
}
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;
};
return (node);
}
// Update root
root->right = head;
// Update head
head = root;
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;
}
printInorder(node->left);
printInorder(node->right);
}
/* Driver code*/
int main()
{
/* Create following tree as first balanced BST
100
/\
50 300
/\
20 70 */
// Function Call
Node* mergedTree = mergeTrees(root1, root2, 5, 3);
return 0;
}
GRAPH
//GRAPH
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);
}
// adjacency matrix
vector<vector<int> > adj;
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);
// Perform DFS
dfs(0, visited);
}
vector<vector<int>> adj;
int vis;
while (!q.empty()) {
vis = q[0];
// 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);
//PRIM
#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
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;
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;
return dp[idx];
}
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];
Graph::Graph(int V)
{
this->V = V;
adj = new list<int>[V];
}
while (!queue.empty())
{
// Dequeue a vertex from queue and print it
s = queue.front();
queue.pop_front();
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;
}