diff --git a/C++/AVLTree.cpp b/C++/AVLTree.cpp new file mode 100644 index 0000000..401b0d4 --- /dev/null +++ b/C++/AVLTree.cpp @@ -0,0 +1,258 @@ +/* + +AVL tree is a self-balancing Binary Search Tree where the difference between +heights of left and right subtrees cannot be more than one for all nodes. + +Tree rotation is an operation that changes the structure without interfering +with the order of the elements on an AVL tree. It moves one node up in the tree +and one node down. It is used to change the shape of the tree, and to decrease its +height by moving smaller subtrees down and larger subtrees up, resulting in improved +performance of many tree operations. The direction of a rotation depends on the side +which the tree nodes are shifted upon whilst others say that it depends on which +child takes the root’s place. This is a C++ Program to Implement AVL Tree. + +Function Descriptions: + +height(avl *) : It calculate the height of the given AVL tree. + +difference(avl *): It calculate the difference between height of sub trees of given tree + +avl *rr_rotat(avl *): A right-right rotation is a combination of right rotation followed by right rotation. + +avl *ll_rotat(avl *): A left-left rotation is a combination of left rotation followed by left rotation. + +avl *lr_rotat(avl*): A left-right rotation is a combination of left rotation followed by right rotation. + +avl *rl_rotat(avl *): It is a combination of right rotation followed by left rotation. + +avl * balance(avl *): It perform balance operation to the tree by getting balance factor + +avl * insert(avl*, int): It perform insert operation. Insert values in the tree using this function. + +show(avl*, int): It display the values of the tree. + +inorder(avl *): Traverses a tree in an in-order manner. + +preorder(avl *): Traverses a tree in a pre-order manner. + +postorder(avl*): Traverses a tree in a post-order manner + +*/ + +#include +#include +#include +#include + +#define pow2(n) (1 << (n)) + +using namespace std; + +struct avl { + int d; + struct avl *l; + struct avl *r; +}*r; + +class avl_tree { + + public: + int height(avl *); + int difference(avl *); + avl *rr_rotat(avl *); + avl *ll_rotat(avl *); + avl *lr_rotat(avl*); + avl *rl_rotat(avl *); + avl * balance(avl *); + avl * insert(avl*, int); + void show(avl*, int); + void inorder(avl *); + void preorder(avl *); + void postorder(avl*); + avl_tree() { + r = NULL; + } +}; + +int avl_tree::height(avl *t) { + int h = 0; + if (t != NULL) { + int l_height = height(t->l); + int r_height = height(t->r); + int max_height = max(l_height, r_height); + h = max_height + 1; + } + return h; +} + +int avl_tree::difference(avl *t) { + int l_height = height(t->l); + int r_height = height(t->r); + int b_factor = l_height - r_height; + return b_factor; +} + +avl *avl_tree::rr_rotat(avl *parent) { + avl *t; + t = parent->r; + parent->r = t->l; + t->l = parent; + cout<<"Right-Right Rotation"; + return t; +} + +avl *avl_tree::ll_rotat(avl *parent) { + avl *t; + t = parent->l; + parent->l = t->r; + t->r = parent; + cout<<"Left-Left Rotation"; + return t; +} + +avl *avl_tree::lr_rotat(avl *parent) { + avl *t; + t = parent->l; + parent->l = rr_rotat(t); + cout<<"Left-Right Rotation"; + return ll_rotat(parent); +} + +avl *avl_tree::rl_rotat(avl *parent) { + avl *t; + t = parent->r; + parent->r = ll_rotat(t); + cout<<"Right-Left Rotation"; + return rr_rotat(parent); +} + +avl *avl_tree::balance(avl *t) { + int bal_factor = difference(t); + if (bal_factor > 1) { + if (difference(t->l) > 0) + t = ll_rotat(t); + else + t = lr_rotat(t); + } else if (bal_factor < -1) { + if (difference(t->r) > 0) + t = rl_rotat(t); + else + t = rr_rotat(t); + } + return t; +} + +avl *avl_tree::insert(avl *r, int v) { + if (r == NULL) { + r = new avl; + r->d = v; + r->l = NULL; + r->r = NULL; + return r; + } else if (v< r->d) { + r->l = insert(r->l, v); + r = balance(r); + } else if (v >= r->d) { + r->r = insert(r->r, v); + r = balance(r); + } return r; +} + +void avl_tree::show(avl *p, int l) { + int i; + if (p != NULL) { + show(p->r, l+ 1); + cout<<" "; + if (p == r) + cout << "Root -> "; + for (i = 0; i < l&& p != r; i++) + cout << " "; + cout << p->d; + show(p->l, l + 1); + } +} + +void avl_tree::inorder(avl *t) { + if (t == NULL) + return; + inorder(t->l); + cout << t->d << " "; + inorder(t->r); +} + +void avl_tree::preorder(avl *t) { + if (t == NULL) + return; + cout << t->d << " "; + preorder(t->l); + preorder(t->r); +} + +void avl_tree::postorder(avl *t) { + if (t == NULL) + return; + postorder(t ->l); + postorder(t ->r); + cout << t->d << " "; +} + +int main() { + int c, i; + avl_tree avl; + + while (1) { + cout << "1.Insert Element into the tree" << endl; + cout << "2.show Balanced AVL Tree" << endl; + cout << "3.InOrder traversal" << endl; + cout << "4.PreOrder traversal" << endl; + cout << "5.PostOrder traversal" << endl; + cout << "6.Exit" << endl; + cout << "Enter your Choice: "; + cin >> c; + + switch (c) { + + case 1: + cout << "Enter value to be inserted: "; + cin >> i; + r = avl.insert(r, i); + break; + + case 2: + if (r == NULL) { + cout << "Tree is Empty" << endl; + continue; + } + cout << "Balanced AVL Tree:" << endl; + avl.show(r, 1); + cout< +#include + +using namespace std; + +class Graph{ + + int V; + list *l; //Array of List, dynamically added + + public : + Graph(int V){ + this -> V = V; + l = new list[V]; + } + + void addEdge(int x, int y){ + l[x].push_back(y); + l[y].push_back(x); + } + void printAdjList(){ + for(int i = 0; i < V; i++){ + cout << "Vertex " << i << " -> "; + for(int nbr: l[i]){ + cout << nbr << ","; + } + cout << endl; + } + } +}; + +int main(){ + + Graph g(4); + g.addEdge(0,1); + g.addEdge(0,2); + g.addEdge(2,3); + g.addEdge(1,2); + g.printAdjList(); + return 0; +} \ No newline at end of file diff --git a/C++/AdjacencyListNode.cpp b/C++/AdjacencyListNode.cpp new file mode 100644 index 0000000..e21edc1 --- /dev/null +++ b/C++/AdjacencyListNode.cpp @@ -0,0 +1,48 @@ +#include +#include +#include +#include +#include + +using namespace std; + +class Graph{ + + unordered_map>> l; + + public: + void addEdge(string x, string y, bool bidir, int wt){ + l[x].push_back(make_pair(y, wt)); + if(bidir){ + l[y].push_back(make_pair(x, wt)); + } + } + + void printAdjList(){ + for(auto p: l){ + string city = p.first; + list > nbrs = p.second; + + cout << city << " -> "; + for(auto nbr : nbrs){ + string dest = nbr.first; + int dist = nbr.second; + + cout << dest << " " << dist << ","; + } + cout << endl; + } + } +}; + +int main(){ + + Graph g; + g.addEdge("A", "B", true, 20); + g.addEdge("B", "D", true, 40); + g.addEdge("A", "C", true, 10); + g.addEdge("C", "D", true, 40); + g.addEdge("A", "D", false, 50); + g.printAdjList(); + return 0; +} \ No newline at end of file diff --git a/C++/BTree.cpp b/C++/BTree.cpp new file mode 100644 index 0000000..d4b5076 --- /dev/null +++ b/C++/BTree.cpp @@ -0,0 +1,668 @@ +#include + +using namespace std; + +// A BTree node +class BTreeNode +{ + int *keys; // An array of keys + int t; // Minimum degree (defines the range for number of keys) + BTreeNode **C; // An array of child pointers + int n; // Current number of keys + bool leaf; // Is true when node is leaf. Otherwise false + +public: + + BTreeNode(int _t, bool _leaf); // Constructor + + // A function to traverse all nodes in a subtree rooted with this node + void traverse(); + + // A function to search a key in subtree rooted with this node. + BTreeNode *search(int k); // returns NULL if k is not present. + + // A function that returns the index of the first key that is greater + // or equal to k + int findKey(int k); + + // A utility function to insert a new key in the subtree rooted with + // this node. The assumption is, the node must be non-full when this + // function is called + void insertNonFull(int k); + + // A utility function to split the child y of this node. i is index + // of y in child array C[]. The Child y must be full when this + // function is called + void splitChild(int i, BTreeNode *y); + + // A wrapper function to remove the key k in subtree rooted with + // this node. + void remove(int k); + + // A function to remove the key present in idx-th position in + // this node which is a leaf + void removeFromLeaf(int idx); + + // A function to remove the key present in idx-th position in + // this node which is a non-leaf node + void removeFromNonLeaf(int idx); + + // A function to get the predecessor of the key- where the key + // is present in the idx-th position in the node + int getPred(int idx); + + // A function to get the successor of the key- where the key + // is present in the idx-th position in the node + int getSucc(int idx); + + // A function to fill up the child node present in the idx-th + // position in the C[] array if that child has less than t-1 keys + void fill(int idx); + + // A function to borrow a key from the C[idx-1]-th node and place + // it in C[idx]th node + void borrowFromPrev(int idx); + + // A function to borrow a key from the C[idx+1]-th node and place it + // in C[idx]th node + void borrowFromNext(int idx); + + // A function to merge idx-th child of the node with (idx+1)th child of + // the node + void merge(int idx); + + // Make BTree friend of this so that we can access private members of + // this class in BTree functions + friend class BTree; +}; + +class BTree +{ + BTreeNode *root; // Pointer to root node + int t; // Minimum degree +public: + + // Constructor (Initializes tree as empty) + BTree(int _t) + { + root = NULL; + t = _t; + } + + void traverse() + { + if (root != NULL) root->traverse(); + } + + // function to search a key in this tree + BTreeNode* search(int k) + { + return (root == NULL)? NULL : root->search(k); + } + + // The main function that inserts a new key in this B-Tree + void insert(int k); + + // The main function that removes a new key in thie B-Tree + void remove(int k); + +}; + +BTreeNode::BTreeNode(int t1, bool leaf1) +{ + // Copy the given minimum degree and leaf property + t = t1; + leaf = leaf1; + + // Allocate memory for maximum number of possible keys + // and child pointers + keys = new int[2*t-1]; + C = new BTreeNode *[2*t]; + + // Initialize the number of keys as 0 + n = 0; +} + +// A utility function that returns the index of the first key that is +// greater than or equal to k +int BTreeNode::findKey(int k) +{ + int idx=0; + while (idxn < t) + fill(idx); + + // If the last child has been merged, it must have merged with the previous + // child and so we recurse on the (idx-1)th child. Else, we recurse on the + // (idx)th child which now has atleast t keys + if (flag && idx > n) + C[idx-1]->remove(k); + else + C[idx]->remove(k); + } + return; +} + +// A function to remove the idx-th key from this node - which is a leaf node +void BTreeNode::removeFromLeaf (int idx) +{ + + // Move all the keys after the idx-th pos one place backward + for (int i=idx+1; in >= t) + { + int pred = getPred(idx); + keys[idx] = pred; + C[idx]->remove(pred); + } + + // If the child C[idx] has less that t keys, examine C[idx+1]. + // If C[idx+1] has atleast t keys, find the successor 'succ' of k in + // the subtree rooted at C[idx+1] + // Replace k by succ + // Recursively delete succ in C[idx+1] + else if (C[idx+1]->n >= t) + { + int succ = getSucc(idx); + keys[idx] = succ; + C[idx+1]->remove(succ); + } + + // If both C[idx] and C[idx+1] has less that t keys,merge k and all of C[idx+1] + // into C[idx] + // Now C[idx] contains 2t-1 keys + // Free C[idx+1] and recursively delete k from C[idx] + else + { + merge(idx); + C[idx]->remove(k); + } + return; +} + +// A function to get predecessor of keys[idx] +int BTreeNode::getPred(int idx) +{ + // Keep moving to the right most node until we reach a leaf + BTreeNode *cur=C[idx]; + while (!cur->leaf) + cur = cur->C[cur->n]; + + // Return the last key of the leaf + return cur->keys[cur->n-1]; +} + +int BTreeNode::getSucc(int idx) +{ + + // Keep moving the left most node starting from C[idx+1] until we reach a leaf + BTreeNode *cur = C[idx+1]; + while (!cur->leaf) + cur = cur->C[0]; + + // Return the first key of the leaf + return cur->keys[0]; +} + +// A function to fill child C[idx] which has less than t-1 keys +void BTreeNode::fill(int idx) +{ + + // If the previous child(C[idx-1]) has more than t-1 keys, borrow a key + // from that child + if (idx!=0 && C[idx-1]->n>=t) + borrowFromPrev(idx); + + // If the next child(C[idx+1]) has more than t-1 keys, borrow a key + // from that child + else if (idx!=n && C[idx+1]->n>=t) + borrowFromNext(idx); + + // Merge C[idx] with its sibling + // If C[idx] is the last child, merge it with with its previous sibling + // Otherwise merge it with its next sibling + else + { + if (idx != n) + merge(idx); + else + merge(idx-1); + } + return; +} + +// A function to borrow a key from C[idx-1] and insert it +// into C[idx] +void BTreeNode::borrowFromPrev(int idx) +{ + + BTreeNode *child=C[idx]; + BTreeNode *sibling=C[idx-1]; + + // The last key from C[idx-1] goes up to the parent and key[idx-1] + // from parent is inserted as the first key in C[idx]. Thus, the loses + // sibling one key and child gains one key + + // Moving all key in C[idx] one step ahead + for (int i=child->n-1; i>=0; --i) + child->keys[i+1] = child->keys[i]; + + // If C[idx] is not a leaf, move all its child pointers one step ahead + if (!child->leaf) + { + for(int i=child->n; i>=0; --i) + child->C[i+1] = child->C[i]; + } + + // Setting child's first key equal to keys[idx-1] from the current node + child->keys[0] = keys[idx-1]; + + // Moving sibling's last child as C[idx]'s first child + if(!child->leaf) + child->C[0] = sibling->C[sibling->n]; + + // Moving the key from the sibling to the parent + // This reduces the number of keys in the sibling + keys[idx-1] = sibling->keys[sibling->n-1]; + + child->n += 1; + sibling->n -= 1; + + return; +} + +// A function to borrow a key from the C[idx+1] and place +// it in C[idx] +void BTreeNode::borrowFromNext(int idx) +{ + + BTreeNode *child=C[idx]; + BTreeNode *sibling=C[idx+1]; + + // keys[idx] is inserted as the last key in C[idx] + child->keys[(child->n)] = keys[idx]; + + // Sibling's first child is inserted as the last child + // into C[idx] + if (!(child->leaf)) + child->C[(child->n)+1] = sibling->C[0]; + + //The first key from sibling is inserted into keys[idx] + keys[idx] = sibling->keys[0]; + + // Moving all keys in sibling one step behind + for (int i=1; in; ++i) + sibling->keys[i-1] = sibling->keys[i]; + + // Moving the child pointers one step behind + if (!sibling->leaf) + { + for(int i=1; i<=sibling->n; ++i) + sibling->C[i-1] = sibling->C[i]; + } + + // Increasing and decreasing the key count of C[idx] and C[idx+1] + // respectively + child->n += 1; + sibling->n -= 1; + + return; +} + +// A function to merge C[idx] with C[idx+1] +// C[idx+1] is freed after merging +void BTreeNode::merge(int idx) +{ + BTreeNode *child = C[idx]; + BTreeNode *sibling = C[idx+1]; + + // Pulling a key from the current node and inserting it into (t-1)th + // position of C[idx] + child->keys[t-1] = keys[idx]; + + // Copying the keys from C[idx+1] to C[idx] at the end + for (int i=0; in; ++i) + child->keys[i+t] = sibling->keys[i]; + + // Copying the child pointers from C[idx+1] to C[idx] + if (!child->leaf) + { + for(int i=0; i<=sibling->n; ++i) + child->C[i+t] = sibling->C[i]; + } + + // Moving all keys after idx in the current node one step before - + // to fill the gap created by moving keys[idx] to C[idx] + for (int i=idx+1; in += sibling->n+1; + n--; + + // Freeing the memory occupied by sibling + delete(sibling); + return; +} + +// The main function that inserts a new key in this B-Tree +void BTree::insert(int k) +{ + // If tree is empty + if (root == NULL) + { + // Allocate memory for root + root = new BTreeNode(t, true); + root->keys[0] = k; // Insert key + root->n = 1; // Update number of keys in root + } + else // If tree is not empty + { + // If root is full, then tree grows in height + if (root->n == 2*t-1) + { + // Allocate memory for new root + BTreeNode *s = new BTreeNode(t, false); + + // Make old root as child of new root + s->C[0] = root; + + // Split the old root and move 1 key to the new root + s->splitChild(0, root); + + // New root has two children now. Decide which of the + // two children is going to have new key + int i = 0; + if (s->keys[0] < k) + i++; + s->C[i]->insertNonFull(k); + + // Change root + root = s; + } + else // If root is not full, call insertNonFull for root + root->insertNonFull(k); + } +} + +// A utility function to insert a new key in this node +// The assumption is, the node must be non-full when this +// function is called +void BTreeNode::insertNonFull(int k) +{ + // Initialize index as index of rightmost element + int i = n-1; + + // If this is a leaf node + if (leaf == true) + { + // The following loop does two things + // a) Finds the location of new key to be inserted + // b) Moves all greater keys to one place ahead + while (i >= 0 && keys[i] > k) + { + keys[i+1] = keys[i]; + i--; + } + + // Insert the new key at found location + keys[i+1] = k; + n = n+1; + } + else // If this node is not leaf + { + // Find the child which is going to have the new key + while (i >= 0 && keys[i] > k) + i--; + + // See if the found child is full + if (C[i+1]->n == 2*t-1) + { + // If the child is full, then split it + splitChild(i+1, C[i+1]); + + // After split, the middle key of C[i] goes up and + // C[i] is splitted into two. See which of the two + // is going to have the new key + if (keys[i+1] < k) + i++; + } + C[i+1]->insertNonFull(k); + } +} + +// A utility function to split the child y of this node +// Note that y must be full when this function is called +void BTreeNode::splitChild(int i, BTreeNode *y) +{ + // Create a new node which is going to store (t-1) keys + // of y + BTreeNode *z = new BTreeNode(y->t, y->leaf); + z->n = t - 1; + + // Copy the last (t-1) keys of y to z + for (int j = 0; j < t-1; j++) + z->keys[j] = y->keys[j+t]; + + // Copy the last t children of y to z + if (y->leaf == false) + { + for (int j = 0; j < t; j++) + z->C[j] = y->C[j+t]; + } + + // Reduce the number of keys in y + y->n = t - 1; + + // Since this node is going to have a new child, + // create space of new child + for (int j = n; j >= i+1; j--) + C[j+1] = C[j]; + + // Link the new child to this node + C[i+1] = z; + + // A key of y will move to this node. Find location of + // new key and move all greater keys one space ahead + for (int j = n-1; j >= i; j--) + keys[j+1] = keys[j]; + + // Copy the middle key of y to this node + keys[i] = y->keys[t-1]; + + // Increment count of keys in this node + n = n + 1; +} + +// Function to traverse all nodes in a subtree rooted with this node +void BTreeNode::traverse() +{ + // There are n keys and n+1 children, travers through n keys + // and first n children + int i; + for (i = 0; i < n; i++) + { + // If this is not leaf, then before printing key[i], + // traverse the subtree rooted with child C[i]. + if (leaf == false) + C[i]->traverse(); + cout << " " << keys[i]; + } + + // Print the subtree rooted with last child + if (leaf == false) + C[i]->traverse(); +} + +// Function to search key k in subtree rooted with this node +BTreeNode *BTreeNode::search(int k) +{ + // Find the first key greater than or equal to k + int i = 0; + while (i < n && k > keys[i]) + i++; + + // If the found key is equal to k, return this node + if (keys[i] == k) + return this; + + // If key is not found here and this is a leaf node + if (leaf == true) + return NULL; + + // Go to the appropriate child + return C[i]->search(k); +} + +void BTree::remove(int k) +{ + if (!root) + { + cout << "The tree is empty\n"; + return; + } + + // Call the remove function for root + root->remove(k); + + // If the root node has 0 keys, make its first child as the new root + // if it has a child, otherwise set root as NULL + if (root->n==0) + { + BTreeNode *tmp = root; + if (root->leaf) + root = NULL; + else + root = root->C[0]; + + // Free the old root + delete tmp; + } + return; +} + +// Driver program to test above functions +int main() +{ + BTree t(3); // A B-Tree with minium degree 3 + + t.insert(1); + t.insert(3); + t.insert(7); + t.insert(10); + t.insert(11); + t.insert(13); + t.insert(14); + t.insert(15); + t.insert(18); + t.insert(16); + t.insert(19); + t.insert(24); + t.insert(25); + t.insert(26); + t.insert(21); + t.insert(4); + t.insert(5); + t.insert(20); + t.insert(22); + t.insert(2); + t.insert(17); + t.insert(12); + t.insert(6); + + cout << "Traversal of tree constructed is\n"; + t.traverse(); + cout << endl; + + t.remove(6); + cout << "Traversal of tree after removing 6\n"; + t.traverse(); + cout << endl; + + t.remove(13); + cout << "Traversal of tree after removing 13\n"; + t.traverse(); + cout << endl; + + t.remove(7); + cout << "Traversal of tree after removing 7\n"; + t.traverse(); + cout << endl; + + t.remove(4); + cout << "Traversal of tree after removing 4\n"; + t.traverse(); + cout << endl; + + t.remove(2); + cout << "Traversal of tree after removing 2\n"; + t.traverse(); + cout << endl; + + t.remove(16); + cout << "Traversal of tree after removing 16\n"; + t.traverse(); + cout << endl; + + return 0; +} \ No newline at end of file diff --git a/C++/BellmanFord.cpp b/C++/BellmanFord.cpp new file mode 100644 index 0000000..4b50e7c --- /dev/null +++ b/C++/BellmanFord.cpp @@ -0,0 +1,83 @@ +#include +#include +using namespace __gnu_pbds; +using namespace std; + +#define ff first +#define ss second +#define int long long +#define pb push_back +#define mp make_pair +#define pii pair +#define vi vector +#define mii map +#define pqb priority_queue +#define pqs priority_queue > +#define setbits(x) __builtin_popcountll(x) +#define zrobits(x) __builtin_ctzll(x) +#define mod 1000000007 +#define inf 1e18 +#define ps(x,y) fixed<>x; while(x--) +mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); + +typedef tree, rb_tree_tag, tree_order_statistics_node_update> pbds; + + +void c_p_c() +{ + ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); +#ifndef ONLINE_JUDGE + freopen("input.txt", "r", stdin); + freopen("output.txt", "w", stdout); +#endif +} + +int32_t main() +{ + int n, m; + cin >> n >> m; + + vector edges(m); + + for(int i = 0; i < m; i++){ + int u, v, w; + cin >> u >> v >> w; + edges[i] = {u, v, w}; + } + + vi dis(n + 1, inf); + + dis[1] = 0; + + for(int i = 0; i < n - 1; i++){ + for(int j = 0; j < m; j++){ + int u, v, w; + u = edges[j][0]; + v = edges[j][1]; + w = edges[j][2]; + + if(dis[v] > dis[u] + w){ + dis[v] = dis[u] + w; + } + } + } + + for(int j = 0; j < m; j++){ + int u, v, w; + u = edges[j][0]; + v = edges[j][1]; + w = edges[j][2]; + + if(dis[v] > dis[u] + w){ + cout << "Negative Cycle Detected"; + return 0; + } + } + + for(int k = 1; k <= n; k++){ + cout << k << " ----> " << dis[k] << '\n'; + } + +} \ No newline at end of file diff --git a/C++/BreadthFirstSearch.cpp b/C++/BreadthFirstSearch.cpp new file mode 100644 index 0000000..2a181f7 --- /dev/null +++ b/C++/BreadthFirstSearch.cpp @@ -0,0 +1,53 @@ +#include +#include +#include +#include + +using namespace std; + +template +class Graph{ + + map> l; + + public: + void addEdge(int x, int y){ + l[x].push_back(y); + l[y].push_back(x); + } + + void bfs(T src){ + + map visited; + queue q; + + q.push(src); + visited[src] = true; + + while(!q.empty()){ + T node = q.front(); + q.pop(); + cout << node << " "; + for(int nbr: l[node]){ + if(!visited[nbr]){ + q.push(nbr); + visited[nbr] = true; + } + } + } + } + +}; + +int main(){ + Graph g; + g.addEdge(0,1); + g.addEdge(1,2); + g.addEdge(2,3); + g.addEdge(3,4); + g.addEdge(4,5); + + g.bfs(0); + + return 0; +} \ No newline at end of file diff --git a/C++/BubbleSort.cpp b/C++/BubbleSort.cpp new file mode 100644 index 0000000..b307044 --- /dev/null +++ b/C++/BubbleSort.cpp @@ -0,0 +1,27 @@ +#include + +using namespace std; + +void bubbleSort(int a[], int n){ + for(int i = 0; i < n - 1; i++){ + for(int j = 0; j < n - i - 1; j++){ + if(a[j] > a[j+1]){ + swap(a[j], a[j+1]); + } + } + } +} + +int main(){ + int n; + cin >> n; + int a[1000]; + for(int i = 0; i < n; i++){ + cin >> a[i]; + } + bubbleSort(a, n); + for(int i = 0; i < n; i++){ + cout << a[i]; + } + return 0; +} \ No newline at end of file diff --git a/C++/BubbleSortWithComparator.cpp b/C++/BubbleSortWithComparator.cpp new file mode 100644 index 0000000..9203999 --- /dev/null +++ b/C++/BubbleSortWithComparator.cpp @@ -0,0 +1,31 @@ +#include + +using namespace std; + +bool compare(int a, int b){ + return a > b; +} + +void bubbleSort(int a[], int n, bool (&cmp)(int a, int b)){ + for(int i = 0; i < n-1; i++){ + for(int j = 0; j < n - i - 1; j++){ + if(cmp(a[j], a[j+1])){ + swap(a[j], a[j+1]); + } + } + } +} + +int main(){ + int n; + cin >> n; + int a[1000]; + for(int i = 0; i < n; i++){ + cin >> a[i]; + } + bubbleSort(a, n, compare); + for(int i = 0; i < n; i++){ + cout << a[i]; + } + return 0; +} \ No newline at end of file diff --git a/C++/BubbleSortWithTime.cpp b/C++/BubbleSortWithTime.cpp new file mode 100644 index 0000000..0911595 --- /dev/null +++ b/C++/BubbleSortWithTime.cpp @@ -0,0 +1,32 @@ +#include +#include +#include +#include + +void bubbleSort(int a[], int n){ + for(int i = 0; i < n - 1; i++){ + for(int j = 0; j < n - i - 1; j++){ + if(a[j] > a[j+1]){ + std::swap(a[j], a[j+1]); + } + } + } +} + +int arr[10000]; + +void generateArray(){ + for(int i = 0; i < 10000; i++){ + arr[i] = rand() % 1000000; + } +} + +int main(){ + generateArray(); + auto start = std::chrono::high_resolution_clock::now(); + bubbleSort(arr, 10000); + auto finish = std::chrono::high_resolution_clock::now(); + std::chrono::duration elapsed = finish - start; + std::cout << "Elapsed Time: " << elapsed.count() << " milliseconds" << std::endl; + return 0; +} \ No newline at end of file diff --git a/C++/CompositeCoding.cpp b/C++/CompositeCoding.cpp new file mode 100644 index 0000000..325171b --- /dev/null +++ b/C++/CompositeCoding.cpp @@ -0,0 +1,150 @@ +/* +Code Forces #630 B +Composite Coloring + +time limit per test: 2 seconds +memory limit per test: 512 megabytes +input: standard input +output: standard output +A positive integer is called composite if it can be represented as a product of two positive integers, +both greater than 1. For example, the following numbers are composite: 6, 4, 120, 27. +The following numbers aren't: 1, 2, 3, 17, 97. + +Alice is given a sequence of n composite numbers a1,a2,…,an. + +She wants to choose an integer m≤11 and color each element one of m colors from 1 to m so that: + +for each color from 1 to m there is at least one element of this color; +each element is colored and colored exactly one color; +the greatest common divisor of any two elements that are colored the same color is greater +than 1, i.e. gcd(ai,aj)>1 for each pair i,j if these elements are colored the same color. +Note that equal elements can be colored different colors — you just have to choose one of +m colors for each of the indices from 1 to n. + +Alice showed already that if all ai≤1000 then she can always solve the task by choosing some m≤11. + +Help Alice to find the required coloring. Note that you don't have to minimize or maximize the +number of colors, you just have to find the solution with some m from 1 to 11. + +Input +The first line contains a single integer t (1≤t≤1000) — the number of test cases. Then the +descriptions of the test cases follow. + +The first line of the test case contains a single integer n (1≤n≤1000) — the amount of numbers in a sequence a. + +The second line of the test case contains n composite integers a1,a2,…,an (4≤ai≤1000). + +It is guaranteed that the sum of n over all test cases doesn't exceed 104. + +Output +For each test case print 2 lines. The first line should contain a single integer m (1≤m≤11) — the number +of used colors. Consider colors to be numbered from 1 to m. The second line should contain any coloring +that satisfies the above conditions. Print n integers c1,c2,…,cn (1≤ci≤m), where ci is the color of the +i-th element. If there are multiple solutions then you can print any of them. Note that you don't have +to minimize or maximize the number of colors, you just have to find the solution with some m from 1 to 11. + +Remember that each color from 1 to m should be used at least once. Any two elements of the same color +should not be coprime (i.e. their GCD should be greater than 1). + +Example: + +input + +3 +3 +6 10 15 +2 +4 9 +23 +437 519 865 808 909 391 194 291 237 395 323 365 511 497 781 737 871 559 731 697 779 841 961 + +output + +1 +1 1 1 +2 +2 1 +11 +4 7 8 10 7 3 10 7 7 8 3 1 1 5 5 9 2 2 3 3 4 11 6 + +Note: +In the first test case, gcd(6,10)=2, gcd(6,15)=3 and gcd(10,15)=5. Therefore, it's valid to +color all elements the same color. Note that there are other colorings which satisfy Alice's +requirement in this test case. + +In the second test case there is only one element of each color, so the coloring definitely +satisfies Alice's requirement. + +*/ + +#include +#include +using namespace __gnu_pbds; +using namespace std; + +#define ff first +#define ss second +#define int long long +#define pb push_back +#define mp make_pair +#define pii pair +#define vi vector +#define mii map +#define pqb priority_queue +#define pqs priority_queue > +#define setbits(x) __builtin_popcountll(x) +#define zrobits(x) __builtin_ctzll(x) +#define mod 1000000007 +#define inf 1e18 +#define ps(x,y) fixed<>x; while(x--) +#define FIO ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0) +mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); + +typedef tree, rb_tree_tag, tree_order_statistics_node_update> pbds; + +int32_t main() +{ + FIO; + vi prm = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31}; + w(t){ + int n; + cin >> n; + mk(arr, n, int); + + for (int i = 0; i < n; ++i) + cin >> arr[i]; + + mk(ans, n, int); + + for (int i = 0; i < n; ++i) + ans[i] = -1; + + int cur_col = 1; + + for (int p : prm){ + bool got = 0; + for (int i = 0; i < n; ++i){ + if (ans[i] != -1) + continue; + + if (arr[i] % p) + continue; + + got = 1; + ans[i] = cur_col; + } + if (got) + cur_col++; + } + + cout << (cur_col - 1) << '\n'; + + for (int i = 0; i < n; ++i) + cout << ans[i] << ' '; + + cout << '\n'; + } + return 0; +} \ No newline at end of file diff --git a/C++/DepthFirstSearch.cpp b/C++/DepthFirstSearch.cpp new file mode 100644 index 0000000..489a27d --- /dev/null +++ b/C++/DepthFirstSearch.cpp @@ -0,0 +1,55 @@ +#include +#include +#include +#include + +using namespace std; + +template +class Graph{ + + map> l; + + public: + void addEdge(int x, int y){ + l[x].push_back(y); + l[y].push_back(x); + } + + void dfs_helper(T src, map &visited){ + cout << src << " "; + visited[src] = true; + for(T nbr: l[src]){ + if(!visited[nbr]){ + dfs_helper(nbr, visited); + } + } + } + + void dfs(T src){ + map visited; + + for(auto p: l){ + T node = p.first; + visited[node] = false; + } + + dfs_helper(src, visited); + + } + +}; + +int main(){ + + Graph g; + g.addEdge(0,1); + g.addEdge(1,2); + g.addEdge(2,3); + g.addEdge(3,4); + g.addEdge(4,5); + + g.dfs(0); + + return 0; +} \ No newline at end of file diff --git a/C++/Euclid.cpp b/C++/Euclid.cpp new file mode 100644 index 0000000..d50b9d7 --- /dev/null +++ b/C++/Euclid.cpp @@ -0,0 +1,47 @@ +/* + +Take the following as input. +A number (N1) +A number (N2) +Write a function which returns the GCD of N1 and N2. Print the value returned. + + + +Input Format +Two integers seperated by a new line. + +Constraints +0 < N1 < 1000000000 +0 < N2 < 1000000000 + +Output Format +Output a single integer which is the GCD of the given integers. + +Sample Input +16 +24 + +Sample Output +8 + +Explanation +The largest number that divides both N1 and N2 is called the GCD of N1 and N2. + +*/ + +#include + +using namespace std; + +int gcd(int a, int b){ + + return (b == 0 ? a : gcd(b, a%b)); + +} + +int main() { + int n1, n2; + cin >> n1 >> n2; + cout << gcd(n1,n2) << endl; + return 0; +} \ No newline at end of file diff --git a/C++/ExercisingWalk.cpp b/C++/ExercisingWalk.cpp new file mode 100644 index 0000000..cd0461d --- /dev/null +++ b/C++/ExercisingWalk.cpp @@ -0,0 +1,142 @@ +/* +Code Forces #630 A +Exercising Walk + +time limit per test: 2 seconds +memory limit per test: 512 megabytes +input: standard input +output: standard output +Alice has a cute cat. To keep her cat fit, Alice wants to design an exercising walk for her cat! + +Initially, Alice's cat is located in a cell (x,y) of an infinite grid. +According to Alice's theory, cat needs to move: + +exactly a steps left: from (u,v) to (u−1,v); +exactly b steps right: from (u,v) to (u+1,v); +exactly c steps down: from (u,v) to (u,v−1); +exactly d steps up: from (u,v) to (u,v+1). + +Note that the moves can be performed in an arbitrary order. +For example, if the cat has to move 1 step left, 3 steps right and 2 steps down, +then the walk right, down, left, right, right, down is valid. + +Alice, however, is worrying that her cat might get lost if it moves far away from her. +So she hopes that her cat is always in the area [x1,x2]×[y1,y2], +i.e. for every cat's position (u,v) of a walk x1≤u≤x2 and y1≤v≤y2 holds. + +Also, note that the cat can visit the same cell multiple times. + +Can you help Alice find out if there exists a walk satisfying her wishes? + +Formally, the walk should contain exactly a+b+c+d unit moves (a to the left, b to the right, +c to the down, d to the up). Alice can do the moves in any order. Her current position (u,v) +should always satisfy the constraints: x1≤u≤x2, y1≤v≤y2. The staring point is (x,y). + +You are required to answer t test cases independently. + +Input +The first line contains a single integer t (1≤t≤103) — the number of testcases. + +The first line of each test case contains four integers a, b, c, d (0≤a,b,c,d≤108, a+b+c+d≥1). + +The second line of the test case contains six integers x, y, x1, y1, x2, y2 (−108≤x1≤x≤x2≤108, −108≤y1≤y≤y2≤108). + +Output +For each test case, output "YES" in a separate line, if there exists a walk satisfying her wishes. +Otherwise, output "NO" in a separate line. + +You can print each letter in any case (upper or lower). + +Example: + +input + +6 +3 2 2 2 +0 0 -2 -2 2 2 +3 1 4 1 +0 0 -1 -1 1 1 +1 1 1 1 +1 1 1 1 1 1 +0 0 0 1 +0 0 0 0 0 1 +5 1 1 1 +0 0 -100 -100 0 100 +1 1 5 1 +0 0 -100 -100 100 0 + +output + +Yes +No +No +Yes +Yes +Yes + +Note: + +In the first test case, one valid exercising walk is +(0,0) → (−1,0) → (−2,0) → (−2,1) → (−2,2) → (−1,2) → (0,2) → (0,1) → (0,0) → (−1,0) + +*/ + +#include +#include +using namespace __gnu_pbds; +using namespace std; + +#define ff first +#define ss second +#define int long long +#define pb push_back +#define mp make_pair +#define pii pair +#define vi vector +#define mii map +#define pqb priority_queue +#define pqs priority_queue > +#define setbits(x) __builtin_popcountll(x) +#define zrobits(x) __builtin_ctzll(x) +#define mod 1000000007 +#define inf 1e18 +#define ps(x,y) fixed<>x; while(x--) +#define FIO ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0) +mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); + +typedef tree, rb_tree_tag, tree_order_statistics_node_update> pbds; + +int32_t main() +{ + FIO; + w(t){ + + int l, r, d, u; + cin >> l >> r >> d >> u; + int x, y, xl, yd, xr, yu; + cin >> x >> y >> xl >> yd >> xr >> yu; + + int ans = 1; + + if (r - l > xr - x || l - r > x - xl) + ans = 0; + + if (u - d > yu - y || d - u > y - yd) + ans = 0; + + if (xl == xr && (l + r) > 0) + ans = 0; + + if (yd == yu && (d + u) > 0) + ans = 0; + + if (ans == 1) + cout << "Yes\n"; + + else + cout << "No\n"; + } + return 0; +} \ No newline at end of file diff --git a/C++/Fibonacci_DP.cpp b/C++/Fibonacci_DP.cpp new file mode 100644 index 0000000..41a86ca --- /dev/null +++ b/C++/Fibonacci_DP.cpp @@ -0,0 +1,62 @@ +// Fiboncci Series using Dynamic Programming + +#include + +using namespace std; + +// Top Down Approach +int fib_TD(int n, int dp[]){ + + if(n == 0 || n==1){ + return n; + } + + if(dp[n] != 0){ + return dp[n]; + } + + int ans; + ans = fib_TD(n - 1, dp) + fib_TD(n - 2, dp); + return dp[n] = ans; +} + +// Bottom Up Approach +int fib_BU(int n){ + int dp[1000] = {0}; + dp[1] = 1; + for(int i = 2; i <= n; i++){ + dp[i] = dp[i - 1] + dp[i - 2]; + } + return dp[n]; +} + +// Bottom Up Space Optimised +int fib_SpaceOpt(int n){ + + if(n == 0 || n==1){ + return n; + } + + int a = 0; + int b = 1; + int c; + + for(int i = 2; i <= n; i++){ + c = a + b; + a = b; + b = c; + } + return c; +} + +int main(){ + int n; + cin >> n; + int dp[1000] = {0}; + + cout << fib_BU(n) << endl; + cout << fib_TD(n, dp) << endl; + cout << fib_SpaceOpt(n) << endl; + + return 0; +} \ No newline at end of file diff --git a/C++/FrogJumps.cpp b/C++/FrogJumps.cpp new file mode 100644 index 0000000..8a1c0ae --- /dev/null +++ b/C++/FrogJumps.cpp @@ -0,0 +1,141 @@ +/* +Code Forces #627 C +Frog Jumps + +time limit per test: 2 seconds +memory limit per test: 256 megabytes +input: standard input +output: standard output + +There is a frog staying to the left of the string s=s1s2…sn consisting of n characters +(to be more precise, the frog initially stays at the cell 0). Each character of s is either 'L' or 'R'. +It means that if the frog is staying at the i-th cell and the i-th character is 'L', +the frog can jump only to the left. If the frog is staying at the i-th cell and the i-th character is 'R', +the frog can jump only to the right. The frog can jump only to the right from the cell 0. + +Note that the frog can jump into the same cell twice and can perform as many jumps as it needs. + +The frog wants to reach the n+1-th cell. The frog chooses some positive integer value d before +the first jump (and cannot change it later) and jumps by no more than d cells at once. +I.e. if the i-th character is 'L' then the frog can jump to any cell in a range [max(0,i−d);i−1], +and if the i-th character is 'R' then the frog can jump to any cell in a range [i+1;min(n+1;i+d)]. + +The frog doesn't want to jump far, so your task is to find the minimum possible value of d +such that the frog can reach the cell n+1 from the cell 0 if it can jump by no more +than d cells at once. It is guaranteed that it is always possible to reach n+1 from 0. + +You have to answer t independent test cases. + +Input +The first line of the input contains one integer t (1≤t≤104) — the number of test cases. + +The next t lines describe test cases. The i-th test case is described as a string s consisting +of at least 1 and at most 2⋅105 characters 'L' and 'R'. + +It is guaranteed that the sum of lengths of strings over all test cases does not exceed 2⋅105 (∑|s|≤2⋅105). + +Output +For each test case, print the answer — the minimum possible value of d such that the frog can +reach the cell n+1 from the cell 0 if it jumps by no more than d at once. + +Example: + +input + +6 +LRLRRLL +L +LLR +RRRR +LLLLLL +R + +output + +3 +2 +3 +1 +7 +1 + +Note +The picture describing the first test case of the example and one of the possible answers: + +In the second test case of the example, the frog can only jump directly from 0 to n+1. + +In the third test case of the example, the frog can choose d=3, jump to the cell 3 from the cell 0 and then to the cell 4 from the cell 3. + +In the fourth test case of the example, the frog can choose d=1 and jump 5 times to the right. + +In the fifth test case of the example, the frog can only jump directly from 0 to n+1. + +In the sixth test case of the example, the frog can choose d=1 and jump 2 times to the right. + +*/ + +#include +#include +using namespace __gnu_pbds; +using namespace std; + +#define ff first +#define ss second +#define int long long +#define pb push_back +#define mp make_pair +#define pii pair +#define vi vector +#define mii map +#define pqb priority_queue +#define pqs priority_queue > +#define setbits(x) __builtin_popcountll(x) +#define zrobits(x) __builtin_ctzll(x) +#define mod 1000000007 +#define inf 1e18 +#define ps(x,y) fixed<>x; while(x--) +mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); + +typedef tree, rb_tree_tag, tree_order_statistics_node_update> pbds; + + +void c_p_c() +{ + ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); +#ifndef ONLINE_JUDGE + freopen("input.txt", "r", stdin); + freopen("output.txt", "w", stdout); +#endif +} + +int32_t main() +{ + c_p_c(); + w(t){ + string s; + cin >> s; + vi v; + v.pb(0); + + int n = s.length(); + + for(int i = 0; i < n; i++){ + if(s[i] == 'R'){ + v.pb(i + 1); + } + } + + v.pb(n + 1); + + int ans = 0; + + for(int i = 0; i < v.size() - 1; i++){ + ans = max(ans, v[i + 1] - v[i]); + } + + cout << ans << '\n'; + } + return 0; +} \ No newline at end of file diff --git a/C++/HeapSort.cpp b/C++/HeapSort.cpp new file mode 100644 index 0000000..1e4ef5c --- /dev/null +++ b/C++/HeapSort.cpp @@ -0,0 +1,51 @@ +#include + +using namespace std; + +void heapify(int arr[], int n, int i) +{ + int largest = i; + int l = 2 * i + 1; + int r = 2 * i + 2; + + if (l < n && arr[l] > arr[largest]) + largest = l; + + if (r < n && arr[r] > arr[largest]) + largest = r; + + if (largest != i) { + swap(arr[i], arr[largest]); + heapify(arr, n, largest); + } +} + +void heapSort(int arr[], int n) +{ + for (int i = n / 2 - 1; i >= 0; i--) + heapify(arr, n, i); + + for (int i = n - 1; i >= 0; i--) { + swap(arr[0], arr[i]); + + heapify(arr, i, 0); + } +} + +void printArray(int arr[], int n) +{ + for (int i = 0; i < n; ++i) + cout << arr[i] << " "; + cout << "\n"; +} + +int main() +{ + int arr[] = { 12, 11, 13, 5, 6, 7 }; + int n = sizeof(arr) / sizeof(arr[0]); + + heapSort(arr, n); + + cout << "Sorted array is \n"; + printArray(arr, n); +} \ No newline at end of file diff --git a/C++/HeightAllTheSame.cpp b/C++/HeightAllTheSame.cpp new file mode 100644 index 0000000..d72fbfb --- /dev/null +++ b/C++/HeightAllTheSame.cpp @@ -0,0 +1,122 @@ +/* +Code Forces #630 E +Height All the Same + +time limit per test: 2 seconds +memory limit per test: 512 megabytes +input: standard input +output: standard output + +Alice has got addicted to a game called Sirtet recently. + +In Sirtet, player is given an n×m grid. Initially ai,j cubes are stacked up in the cell (i,j). +Two cells are called adjacent if they share a side. Player can perform the following operations: + +stack up one cube in two adjacent cells; +stack up two cubes in one cell. +Cubes mentioned above are identical in height. + +Here is an illustration of the game. States on the right are obtained by performing one of the +above operations on the state on the left, and grey cubes are added due to the operation. + + +Player's goal is to make the height of all cells the same (i.e. so that each cell has the same +number of cubes in it) using above operations. + +Alice, however, has found out that on some starting grids she may never reach the goal no matter +what strategy she uses. Thus, she is wondering the number of initial grids such that + +L≤ai,j≤R for all 1≤i≤n, 1≤j≤m; +player can reach the goal using above operations. +Please help Alice with it. Notice that the answer might be large, please output the desired +value modulo 998,244,353. + +Input +The only line contains four integers n, m, L and R (1≤n,m,L,R≤109, L≤R, n⋅m≥2). + +Output +Output one integer, representing the desired answer modulo 998,244,353. + +Examples: + +input + +2 2 1 1 + +output + +1 + +input + +1 2 1 2 + +output + +2 + +Note + +In the first sample, the only initial grid that satisfies the requirements +is a1,1=a2,1=a1,2=a2,2=1. Thus the answer should be 1. + +In the second sample, initial grids that satisfy the requirements are a1,1=a1,2=1 and +a1,1=a1,2=2. Thus the answer should be 2. + +*/ + +#include +#include +using namespace __gnu_pbds; +using namespace std; + +#define ff first +#define ss second +#define int long long +#define pb push_back +#define mp make_pair +#define pii pair +#define vi vector +#define mii map +#define pqb priority_queue +#define pqs priority_queue > +#define setbits(x) __builtin_popcountll(x) +#define zrobits(x) __builtin_ctzll(x) +#define mod 1000000007 +#define inf 1e18 +#define ps(x,y) fixed<>x; while(x--) +#define FIO ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0) +mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); + +typedef tree, rb_tree_tag, tree_order_statistics_node_update> pbds; + +int32_t main() +{ + FIO; + int n, m, l, r; + cin >> n >> m >> l >> r; + + int t = r - l + 1; + int e = r / 2 - (l - 1) / 2; + int o = t - e; + + if ((n * m) & 1) + cout << pwmd(t, n * m) << '\n'; + + else { + int sub = pwmd(e + o, n * m) - pwmd(abs(e - o), n * m); + sub += mod; + sub %= mod; + + sub = (sub * pwmd(2, mod - 2)) % mod; // x^-1%mod == (x^(mod-2))%mod + + int tot = pwmd(t, n * m); + + int ans = (tot - sub + mod) % mod; + + cout << ans << '\n'; + } + return 0; +} \ No newline at end of file diff --git a/C++/HelpRahul.cpp b/C++/HelpRahul.cpp new file mode 100644 index 0000000..cb1ead4 --- /dev/null +++ b/C++/HelpRahul.cpp @@ -0,0 +1,76 @@ +/* + +Rahul had a sorted array of numbers from which he had to find a given number quickly. +His friend by mistake rotated the array. Now Rahul doesn't have time to sort the elements again. +Help him to quickly find the given number from the rotated array. + +Hint - Think Binary Search! + +Input Format +The first line contains N - the size of the array. +The next N lines contain the numbers of the array.The next line contains the item to be searched. + +Constraints +Output Format +Output the index of number in the array to be searched. Output -1 if the number is not found. + +Sample Input +5 +4 +5 +1 +2 +3 +2 +Sample Output + +3 +Explanation +The given rotated array is [4, 5, 1, 2, 3]. The element to be searched is 2 whose index is 3. + +*/ + +#include + +using namespace std; + +int findKey(int a[], int n, int key){ + int start = 0; + int end = n - 1; + while(start <= end){ + int mid = (start + end)/2; + if(a[mid] == key){ + return mid; + } + else if(a[start] <= a[mid]){ + if(key >= a[start] && key <= a[mid]){ + end = mid - 1; + } + else { + start = mid + 1; + } + } + else { + if(key >= a[mid] && key <= a[end]){ + start = mid + 1; + } + else { + end = mid -1; + } + } + } + return -1; +} + +int main(){ + int n; + cin >> n; + int a[1000000]; + for(int i = 0; i < n; i++){ + cin >> a[i]; + } + int key; + cin >> key; + cout << findKey(a, n, key) << endl; + return 0; +} \ No newline at end of file diff --git a/C++/HouseAllocation.cpp b/C++/HouseAllocation.cpp new file mode 100644 index 0000000..867a2cd --- /dev/null +++ b/C++/HouseAllocation.cpp @@ -0,0 +1,121 @@ +/* +Google Kickstart 2020 Round A - House Allocation + +There are N houses for sale. The i-th house costs Ai dollars to buy. You have a budget of B dollars to spend. + +What is the maximum number of houses you can buy? + +Input +The first line of the input gives the number of test cases, T. +T test cases follow. Each test case begins with a single line containing the two integers N and B. +The second line contains N integers. The i-th integer is Ai, the cost of the i-th house. + +Output +For each test case, output one line containing Case #x: y, where x is the test case number +(starting from 1) and y is the maximum number of houses you can buy. + +Limits +Time limit: 15 seconds per test set. +Memory limit: 1GB. +1 ≤ T ≤ 100. +1 ≤ B ≤ 105. +1 ≤ Ai ≤ 1000, for all i. + +Test set 1 +1 ≤ N ≤ 100. + +Test set 2 +1 ≤ N ≤ 105. + +Sample: + +Input + +3 +4 100 +20 90 40 90 +4 50 +30 30 10 10 +3 300 +999 999 999 + +Output + +Case #1: 2 +Case #2: 3 +Case #3: 0 + + +In Sample Case #1, you have a budget of 100 dollars. You can buy the 1st and 3rd houses for 20 + 40 = 60 dollars. +In Sample Case #2, you have a budget of 50 dollars. You can buy the 1st, 3rd and 4th houses for 30 + 10 + 10 = 50 dollars. +In Sample Case #3, you have a budget of 300 dollars. You cannot buy any houses (so the answer is 0). + +Note: Unlike previous editions, in Kick Start 2020, all test sets are visible verdict test sets, +meaning you receive instant feedback upon submission. + +Analysis +We want to buy as many as possible houses. Intuitively, we can keep buying the cheapest house. +The rationale is to save money at each step so we could buy more in the end. One way to implement +this strategy is to sort all the houses by prices from low to high and then buy houses one by one until we run out of money. + +The sorting part has O(N log N) time complexity and the processing part has O(N) time complexity. +Using counting sort could reduce the sorting complexity to O(N) since the range of the prices is [1, 1000]. +The overall time complexity is O(N). + +Let's prove the correctness of this greedy algorithm. Let the solution produced by the greedy algorithm be +A = {a1, a2, ..., ak} and an optimal solution O = {o1, o2, ..., om}. + +If O and A are the same, we are done with the proof. Let's assume that there is at least one element oj in O that is not present in A. +Because we always take the smallest element from the original set, we know that any element that is not in A is greater +than or equal to any ai in A. We could replace oj with the absent element in A without worsening the solution, because +there will always be element in A that is not in O. We then increased number of elements in common between A and O, +hence we can repeat this operation only finite number of times. We could repeat this process until all the elements in O are +elements in A. Therefore, A is as good as any optimal solution. + +*/ + +#include +using namespace std; + +#define FIO ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0) +#define int long long + +const int N = 1e5 + 5; + +int n, b; +int a[N]; + +int32_t main(){ + FIO; + + int t; + cin >> t; + + int tc = 0; + + while(t--){ + + tc++; + cin >> n >> b; + + for(int i = 1; i <= n; i++){ + cin >> a[i]; + } + + sort(a + 1, a + n + 1); + int ans = 0; + + for(int i = 1; i <= n; i++){ + if(b >= a[i]){ + ans++; + b -= a[i]; + } + } + + cout << "Case #" << tc << ": " << ans << endl; + + } + + return 0; +} + diff --git a/C++/InbuiltSort.cpp b/C++/InbuiltSort.cpp new file mode 100644 index 0000000..ccf95ce --- /dev/null +++ b/C++/InbuiltSort.cpp @@ -0,0 +1,24 @@ +#include +#include + +using namespace std; + +bool compare(int a, int b){ + return a < b; +} + +int main(){ + int n; + cin >> n; + int a[1000]; + for(int i = 0; i < n; i++){ + cin >> a[i]; + } + + sort(a, a + n, compare); + + for(int i = 0; i < n; i++){ + cout << a[i]; + } + return 0; +} \ No newline at end of file diff --git a/C++/IncredibleHulk.cpp b/C++/IncredibleHulk.cpp new file mode 100644 index 0000000..ab985eb --- /dev/null +++ b/C++/IncredibleHulk.cpp @@ -0,0 +1,72 @@ +/* + +The Planet Earth is under a threat from the aliens of the outer space and the Marvel Avengers team is busy fighting against them. +Meanwhile, The Incredible Hulk has to defeat an enemy who is N steps above the level where he is standing (assume it as the 0th level). +Hulk, because of his incredible jumping ability can take jumps in power of 2. +In order to defeat the enemy as quickly as possible he has to reach the Nth step in minimum moves possible. +Help Hulk to find the same and contribute in saving the Mother Earth. + +Input Format +The first line contains the number of test cases T. T test cases follow: The first line of each test case contains a number N. + +Constraints +1 <= T <= 10 +1 <= N <= 10^5 + +Output Format +Output T lines, containing the minimum number of moves required by Hulk to reach the Nth step + +Sample Input +3 +3 +4 +5 + +Sample Output +2 +1 +2 + +Explanation +Let total steps is n, find the nearest integer which is of power 2 and less then n. +let it would be k. now remaining steps to cover is n-k and result = 1 + min steps for (n-k) remaining steps. + +*/ + +#include + +using namespace std; + +int countBits(int n){ + int a = 0; + while(n > 0){ + a = a + (n & 1); + n = n >> 1; + } + return a; +} + +int countBitsFast(int n){ + int a = 0; + while(n > 0){ + n = n & (n-1); + a++; + } + return a; +} + +int main(){ + + int t; + cin >> t; + int n; + int arr[100]; + for(int i = 0; i < t; i++){ + cin >> n; + arr[i] = __builtin_popcount(n); + } + for(int i = 0; i < t; i++){ + cout << arr[i] << endl; + } + return 0; +} \ No newline at end of file diff --git a/C++/InsertionSort.cpp b/C++/InsertionSort.cpp new file mode 100644 index 0000000..fce10fb --- /dev/null +++ b/C++/InsertionSort.cpp @@ -0,0 +1,32 @@ +#include + +using namespace std; + +void insertionSort(int a[], int n){ + int i,j,key; + for (i = 1; i < n; i++) + { + key = a[i]; + j = i - 1; + while (j >= 0 && a[j] > key) + { + a[j + 1] = a[j]; + j = j - 1; + } + a[j + 1] = key; + } +} + +int main(){ + int n; + cin >> n; + int a[1000]; + for(int i = 0; i < n; i++){ + cin >> a[i]; + } + insertionSort(a, n); + for(int i = 0; i < n; i++){ + cout << a[i]; + } + return 0; +} \ No newline at end of file diff --git a/C++/KCompleteWord.cpp b/C++/KCompleteWord.cpp new file mode 100644 index 0000000..1f58179 --- /dev/null +++ b/C++/KCompleteWord.cpp @@ -0,0 +1,136 @@ +/* +Code Forces #630 C +K-Complete Word + +time limit per test: 2 seconds +memory limit per test: 512 megabytes +input: standard input +output: standard output + +Word s of length n is called k-complete if + +s is a palindrome, i.e. si=sn+1−i for all 1≤i≤n; +s has a period of k, i.e. si=sk+i for all 1≤i≤n−k. +For example, "abaaba" is a 3-complete word, while "abccba" is not. + +Bob is given a word s of length n consisting of only lowercase Latin letters and an integer k, +such that n is divisible by k. He wants to convert s to any k-complete word. + +To do this Bob can choose some i (1≤i≤n) and replace the letter at position i with some other lowercase Latin letter. + +So now Bob wants to know the minimum number of letters he has to replace to convert s to any k-complete word. + +Note that Bob can do zero changes if the word s is already k-complete. + +You are required to answer t test cases independently. + +Input +The first line contains a single integer t (1≤t≤105) — the number of test cases. + +The first line of each test case contains two integers n and k (1≤k +#include +using namespace __gnu_pbds; +using namespace std; + +#define ff first +#define ss second +#define int long long +#define pb push_back +#define mp make_pair +#define pii pair +#define vi vector +#define mii map +#define pqb priority_queue +#define pqs priority_queue > +#define setbits(x) __builtin_popcountll(x) +#define zrobits(x) __builtin_ctzll(x) +#define mod 1000000007 +#define inf 1e18 +#define ps(x,y) fixed<>x; while(x--) +#define FIO ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0) +mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); + +typedef tree, rb_tree_tag, tree_order_statistics_node_update> pbds; + +int32_t main() +{ + FIO; + w(t){ + int n, k; + cin >> n >> k; + string s; + cin >> s; + + int ans = 0; + + for (int i = 0; i < k / 2; ++i)s{ + int cnt[26] = {}; + for (int st = 0; st + k - 1 < n; st += k){ + int i1 = st + i; + int i2 = st + (k - 1 - i); + + cnt[s[i1] - 'a']++; + cnt[s[i2] - 'a']++; + } + + int req = 2 * (n / k); + int mx = *max_element(cnt, cnt + 26); + ans += req - mx; + } + + if (k & 1){ + int cnt[26] = {}; + for (int i = k / 2; i < n; i += k){ + cnt[s[i] - 'a']++; + } + + int req = n / k; + int mx = *max_element(cnt, cnt + 26); + ans += req - mx; + } + + cout << ans << '\n'; + } + return 0; +} \ No newline at end of file diff --git a/C++/LinearSearchwWithTime.cpp b/C++/LinearSearchwWithTime.cpp new file mode 100644 index 0000000..6f732f2 --- /dev/null +++ b/C++/LinearSearchwWithTime.cpp @@ -0,0 +1,33 @@ +#include +#include +#include +#include + +int arr[10000]; +int searchElement = 0; + +void generateArray(){ + for(int i = 0; i < 10000; i++){ + arr[i] = rand() % 1000000; + } + searchElement = arr[8000]; + +} + +void LinearSearch(int ele){ + for(int i = 0; i < 10000; i++){ + if(ele == arr[i]){ + std::cout << "Element Found" << std::endl; + } + } +} + +int main(){ + auto start = std::chrono::high_resolution_clock::now(); + generateArray(); + LinearSearch(searchElement); + auto finish = std::chrono::high_resolution_clock::now(); + std::chrono::duration elapsed = finish - start; + std::cout << "Elapsed Time: " << elapsed.count() << " milliseconds" << std::endl; + return 0; +} \ No newline at end of file diff --git a/C++/MagicalPark.cpp b/C++/MagicalPark.cpp new file mode 100644 index 0000000..2ab74c5 --- /dev/null +++ b/C++/MagicalPark.cpp @@ -0,0 +1,101 @@ +/* + +Piyush is lost in a magical park which contains N rows and M columns.In order to get out of park safely and return home, +he needs atleast K amount of strength.Given a N by M pattern, your task is to find weather Piyush can ever escape the park. +Piyush enters the park with strength S. The park is filled with some obstacles denoted by ‘.’ , some magical beans denoted by ‘*’ and some blockades denoted as ‘#’. +If he encounters an obstacle (.) , strength decreases by 2. If he encounters a magic bean (' * ') , his strength increases by 5. +Piyush can only walk row wise, so he starts from left of a row and moves towards right and he does this for every row. However when he encounters a blockade (#) , +he cannot go any further in his current row and simply jumps to the start of a new line without losing any strength. +Piyush requires a strength of 1 for every step. His strength should always be greater than K while traversing or else Piyush will get lost. +Assume that Piyush can shift immediately from last of one row to the start of next one without loss of any strength, +help out Piyush to escape the park. His escape is successful if he is able to return home with atleast K strength. + +Input Format +First line of input contains four integers – N,M,K and S. Next N lines contains M space separated characters which can be '.', '*' or '#'. + +Constraints +1 <= N,M,K,S <= 100 + +Output Format +Print "Yes" or "No" depending on whether Piyush can escape or not. If the answer is "Yes", also print the amount of strength he escaped with. + +Sample Input +4 4 5 20 +. . * . +. # . . +* * . . +. # * * + +Sample Output +Yes +13 + +Explanation +Piyush starts with strength S=20. +For first row, he encounters a obstacle ‘.’ and his strength reduces by 3 ( 2+1 ( 1 for taking the step) ). Similarly after the second obstacle , +his strength reduces by 3 again and becomes S=14. Then he encounters a '*' , and his strength increases by 5 but decreases by 1 for taking the step. +Then his strength reduces by 2 (Not 3 as he will jump with no extra strength from here) after the last '.' . At the end of the first row his strength is S=16. + +In the second row, he encounters a ‘.’ and his strength reduces by 3( 2+1 for the '.' ). +Then he encounters a '#' and without losing any extra strength simply jumps to the first cell of the next row. +Similarly, his strength at the beginning of the third row is 13 and after completing it, his strength is 16. +In the fourth row, he first encounters a '.' and his strength reduces to 13. +Then he encounters a '#' at the second position and jumps to the next row. Since this is the last row, when he jumps he escapes from the park . +His strength left is 13. Since this is clearly greater than K=5, his escape was successful. +Piyush escaped with final strength = 13. + +*/ + +#include + +using namespace std; + +void magical_park(char a[][100], int m, int n, int k, int s){ + bool success = true; + + for(int i = 0; i < m; i++){ + for(int j = 0; j < n; j++){ + char ch = a[i][j]; + + if(s < k){ + success = false; + break; + } + if(ch == '*'){ + s = s + 5; + } + else if(ch == '.'){ + s = s - 2; + } + else{ + break; + } + + if(j != n-1){ + s--; + } + } + } + if(success){ + cout << "Yes" << endl; + cout << s << endl; + } + else { + cout << "No" << endl; + } +} + +int main() { + + int m, n, k, s; + cin >> m >> n >> k >> s; + char park[100][100]; + for (int i = 0; i < m; i++){ + for(int j = 0; j < n; j++){ + cin >> park[i][j]; + } + } + magical_park(park, m, n, k, s); + + return 0; +} \ No newline at end of file diff --git a/C++/MaximumWhiteSubtree.cpp b/C++/MaximumWhiteSubtree.cpp new file mode 100644 index 0000000..e8518f7 --- /dev/null +++ b/C++/MaximumWhiteSubtree.cpp @@ -0,0 +1,169 @@ +/* +Code Forces #627 F +Maximum White Subtree + +time limit per test: 2 seconds +memory limit per test: 256 megabytes +input: standard input +output: standard output + +You are given a tree consisting of n vertices. A tree is a connected undirected graph with n−1 edges. +Each vertex v of this tree has a color assigned to it (av=1 if the vertex v is white and 0 if the vertex v is black). + +You have to solve the following problem for each vertex v: what is the maximum difference +between the number of white and the number of black vertices you can obtain if you choose some +subtree of the given tree that contains the vertex v? The subtree of the tree is the connected +subgraph of the given tree. More formally, if you choose the subtree that contains cntw white +vertices and cntb black vertices, you have to maximize cntw−cntb. + +Input +The first line of the input contains one integer n (2≤n≤2⋅105) — the number of vertices in the tree. + +The second line of the input contains n integers a1,a2,…,an (0≤ai≤1), where ai is the color of the i-th vertex. + +Each of the next n−1 lines describes an edge of the tree. Edge i is denoted by two integers ui and vi, +the labels of vertices it connects (1≤ui,vi≤n,ui≠vi). + +It is guaranteed that the given edges form a tree. + +Output +Print n integers res1,res2,…,resn, where resi is the maximum possible difference between the number +of white and black vertices in some subtree that contains the vertex i. + +Examples: + +input + +9 +0 1 1 1 0 0 0 0 1 +1 2 +1 3 +3 4 +3 5 +2 6 +4 7 +6 8 +5 9 + +output + +2 2 2 2 2 1 1 0 2 + +input + +4 +0 0 1 0 +1 2 +1 3 +1 4 + +output + +0 -1 1 -1 + +Note +The first example is shown below: + +The black vertices have bold borders. + +In the second example, the best subtree for vertices 2,3 and 4 are vertices 2,3 and 4 correspondingly. +And the best subtree for the vertex 1 is the subtree consisting of vertices 1 and 3. + +*/ + +#include +#include +using namespace __gnu_pbds; +using namespace std; + +#define ff first +#define ss second +#define int long long +#define pb push_back +#define mp make_pair +#define pii pair +#define vi vector +#define mii map +#define pqb priority_queue +#define pqs priority_queue > +#define setbits(x) __builtin_popcountll(x) +#define zrobits(x) __builtin_ctzll(x) +#define mod 1000000007 +#define inf 1e18 +#define ps(x,y) fixed<>x; while(x--) +#define pw(b,p) pow(b,p) + 0.1 +mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); + +typedef tree, rb_tree_tag, tree_order_statistics_node_update> pbds; + + +void c_p_c() +{ + ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); +#ifndef ONLINE_JUDGE + freopen("input.txt", "r", stdin); + freopen("output.txt", "w", stdout); +#endif +} + +int n; +int a[200001]; +vi adj[200001]; +int dp1[200001]; +int dp2[200001]; + +void dfs1(int nd = 1, int pr = 0){ + + dp1[nd] = a[nd] == 1 ? 1 : -1; + + for (auto ch : adj[nd]){ + + if (ch == pr) + continue; + + dfs1(ch, nd); + dp1[nd] += max(0ll, dp1[ch]); + } +} + +void dfs2(int nd = 1, int pr = 0){ + + dp2[nd] = dp1[nd]; + + if (pr){ + int val = dp2[pr] - max(0ll, dp1[nd]); + dp2[nd] += max(0ll, val); + } + + for (auto ch : adj[nd]){ + if (ch == pr) + continue; + + dfs2(ch, nd); + } +} + +int32_t main() +{ + c_p_c(); + cin >> n; + + for (int i = 1; i <= n; ++i) + cin >> a[i]; + + for (int i = 0; i < n - 1; ++i){ + int u, v; cin >> u >> v; + adj[u].pb(v); + adj[v].pb(u); + } + + dfs1(); + dfs2(); + + for (int i = 1; i <= n; ++i) + cout << dp2[i] << ' '; + + return 0; +} \ No newline at end of file diff --git a/C++/MergeSort.cpp b/C++/MergeSort.cpp new file mode 100644 index 0000000..96034ac --- /dev/null +++ b/C++/MergeSort.cpp @@ -0,0 +1,57 @@ +#include + +using namespace std; + +void merge(int *a, int s, int e){ + int mid = (s + e)/2; + + int i = s; + int j = mid + 1; + int k = s; + + int temp[1000]; + + while(i <= mid && j <= e){ + if(a[i] < a[j]){ + temp[k++] = a[i++]; + } + else { + temp[k++] = a[j++]; + } + } + while(i <= mid){ + temp[k++] = a[i++]; + } + while(j <= e){ + temp[k++] = a[j++]; + } + + for(int i = s; i <= e; i++){ + a[i] = temp[i]; + } +} + +void mergeSort(int a[], int s, int e){ + if(s >= e){ + return; + } + int mid = (s + e)/2; + mergeSort(a, s, mid); + mergeSort(a, mid+1, e); + + merge(a, s, e); +} + +int main(){ + int n; + cin >> n; + int a[1000]; + for(int i = 0; i < n; i++){ + cin >> a[i]; + } + mergeSort(a, 0, n-1); + for(int i = 0; i < n; i++){ + cout << a[i]; + } + return 0; +} \ No newline at end of file diff --git a/C++/MinimumCoins_DP.cpp b/C++/MinimumCoins_DP.cpp new file mode 100644 index 0000000..6902251 --- /dev/null +++ b/C++/MinimumCoins_DP.cpp @@ -0,0 +1,72 @@ +#include +#include +#include + +using namespace std; + +// Top Down Approach +int minCoins_TD(int n, int coins[], int t, int dp[]){ + + if(n == 0){ + return 0; + } + + if(dp[n] != 0){ + return dp[n]; + } + + int ans = INT_MAX; + + for(int i = 0; i < t; i++){ + if(n - coins[i] >= 0){ + int subprob = minCoins_TD(n - coins[i], coins, t, dp); + ans = min(ans, subprob + 1); + } + } + + return dp[n] = ans; + +} + +// Bottom Up Approach +int minCoins_BU(int n, int coins[], int t){ + + int dp[100] = {0}; + + for(int i = 1; i <= n; i++){ + dp[i] = INT_MAX; + for(int j = 0; j < t; j++){ + if(i-coins[j] >= 0){ + int subprob = dp[i - coins[j]]; + dp[i] = min(dp[i], subprob + 1); + } + } + } + + return dp[n]; + +} + +int main(){ + + int n; + int t; + int coins[10]; + + cout << "Enter the Amount" << endl; + cin >> n; + cout << "Enter the number of coins" << endl; + cin >> t; + cout << "Enter the coins" << endl; + for(int i = 0; i < t; i++){ + cin >> coins[i]; + } + + int dp[100] = {0}; + + cout << "The minimum no. of coins are: " << endl; + cout << minCoins_TD(n, coins, t, dp) << endl; + cout << minCoins_BU(n, coins, t) << endl; + + return 0; +} \ No newline at end of file diff --git a/C++/MinimumStepsToOne_DP.cpp b/C++/MinimumStepsToOne_DP.cpp new file mode 100644 index 0000000..9e86b8a --- /dev/null +++ b/C++/MinimumStepsToOne_DP.cpp @@ -0,0 +1,81 @@ +/* + Minimum Steps To One + + n ----> 1 + + n => n/3 iff n % 3 == 0 + n => n/2 iff n % 2 == 0 + n => n - 1 + +*/ + +#include +#include +#include + +using namespace std; + +// Top Down Approach +int minSteps_TD(int n, int dp[]){ + + if(n == 1){ + return 0; + } + + // If n is already computed + if(dp[n]!=0){ + return dp[n]; + } + + // if n is not known + int op1, op2, op3; + op1 = op2 = op3 = INT_MAX; + + if(n % 3 == 0){ + op1 = minSteps_TD(n/3, dp); + } + if(n % 2 == 0){ + op2 = minSteps_TD(n/2, dp); + } + op3 = minSteps_TD(n-1, dp); + + int ans = min(min(op1, op2), op3) + 1; + + return dp[n] = ans; + +} + +// Bottom Up Approach +int minSteps_BU(int n){ + + int dp[100] = {0}; + + for(int i = 2; i <= n; i++){ + + int op1, op2, op3; + op1 = op2 = op3 = INT_MAX; + + if(n % 3 == 0){ + op1 = dp[i/3]; + } + if(n % 2 == 0){ + op2 = dp[i/2]; + } + op3 = dp[i-1]; + + dp[i] = min(min(op1, op2), op3) + 1; + } + return dp[n]; +} + +int main(){ + + int n; + cin >> n; + int dp[100] = {0}; + + cout << minSteps_TD(n, dp) << endl; + cout << minSteps_BU(n) << endl; + + return 0; +} \ No newline at end of file diff --git a/C++/PairOfTopics.cpp b/C++/PairOfTopics.cpp new file mode 100644 index 0000000..267161d --- /dev/null +++ b/C++/PairOfTopics.cpp @@ -0,0 +1,123 @@ +/* +Code Forces #627 D +Pair of Topics + +time limit per test: 2 seconds +memory limit per test: 256 megabytes +input: standard input +output: standard output + +The next lecture in a high school requires two topics to be discussed. +The i-th topic is interesting by ai units for the teacher and by bi units for the students. + +The pair of topics i and j (ibi+bj (i.e. it is more interesting for the teacher). + +Your task is to find the number of good pairs of topics. + +Input +The first line of the input contains one integer n (2≤n≤2⋅105) — the number of topics. + +The second line of the input contains n integers a1,a2,…,an (1≤ai≤109), +where ai is the interestingness of the i-th topic for the teacher. + +The third line of the input contains n integers b1,b2,…,bn (1≤bi≤109), +where bi is the interestingness of the i-th topic for the students. + +Output +Print one integer — the number of good pairs of topic. + +Examples: + +input + +5 +4 8 2 6 2 +4 5 4 1 3 + +output + +7 + +input + +4 +1 3 2 4 +1 3 2 4 + +output + +0 + +*/ + +#include +#include +using namespace __gnu_pbds; +using namespace std; + +#define ff first +#define ss second +#define int long long +#define pb push_back +#define mp make_pair +#define pii pair +#define vi vector +#define mii map +#define pqb priority_queue +#define pqs priority_queue > +#define setbits(x) __builtin_popcountll(x) +#define zrobits(x) __builtin_ctzll(x) +#define mod 1000000007 +#define inf 1e18 +#define ps(x,y) fixed<>x; while(x--) +mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); + +typedef tree, rb_tree_tag, tree_order_statistics_node_update> pbds; + + +void c_p_c() +{ + ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); +#ifndef ONLINE_JUDGE + freopen("input.txt", "r", stdin); + freopen("output.txt", "w", stdout); +#endif +} + +int32_t main() +{ + c_p_c(); + int n; + cin >> n; + mk(a, n, int); + mk(b, n, int); + mk(c, n, int); + + for(int i = 0; i < n; i++){ + cin >> a[i]; + } + + for(int i = 0; i < n; i++){ + cin >> b[i]; + } + + for(int i = 0; i < n; i++){ + c[i] = b[i] - a[i]; + } + + sort(c, c+n); + + int ans = 0; + + for(int i = 0; i < n; i++){ + auto it = lower_bound(c+i+1, c+n, -c[i]); + int id = it - c; + ans += id - (i+1); + } + + cout << ans << '\n'; + + return 0; +} \ No newline at end of file diff --git a/C++/PigeonHolePrinciple.cpp b/C++/PigeonHolePrinciple.cpp new file mode 100644 index 0000000..7f7e4e4 --- /dev/null +++ b/C++/PigeonHolePrinciple.cpp @@ -0,0 +1,66 @@ +/* + +You are given N elements, a1,a2,a3….aN. Find the number of good sub-arrays. +A good sub-array is a sub-array [ai,ai+1,ai+2….aj] such that (ai+ai+1+ai+2+….+aj) is divisible by N. + +Input Format +The first line contains the number of test cases T. +First line of each test case contains an integer N denoting the number of elements. +Second line of each test case contains N integers, a1, a2, a3….aN, where ai denotes the ith element of the array. + +Constraints +1<=T<=10 +1<=N<=10^5 +|ai|<=10^9 + +Output Format +Output a single integer denoting the number of good sub-arrays. + +Sample Input +2 +5 +1 1 1 1 1 +5 +5 5 5 5 5 + +Sample Output +1 +15 + +Explanation +In first test case, there is only one sub-array [1, 1, 1, 1, 1], such that 1+1+1+1+1=5, which is divisible by N=5 + +*/ + +#include +#include + +using namespace std; + +long a[1000005], freq[1000005]; + +int main() { + int t; + cin >> t; + while(t--){ + int n; + cin >> n; + memset(freq, 0, sizeof(freq)); + freq[0] = 1; + int sum = 0; + for(int i = 0; i < n; i++){ + cin >> a[i]; + sum = sum + a[i]; + sum = sum % n; + sum = (sum + n) % n; + freq[sum]++; + } + long ans = 0; + for(int i = 0; i < n; i++){ + long m = freq[i]; + ans += (m * (m-1))/2; + } + cout << ans << endl; + } + return 0; +} \ No newline at end of file diff --git a/C++/Plates.cpp b/C++/Plates.cpp new file mode 100644 index 0000000..11af393 --- /dev/null +++ b/C++/Plates.cpp @@ -0,0 +1,161 @@ +/* +Google Kickstart 2020 Round A - Plates + +Dr. Patel has N stacks of plates. Each stack contains K plates. +Each plate has a positive beauty value, describing how beautiful it looks. + +Dr. Patel would like to take exactly P plates to use for dinner tonight. +If he would like to take a plate in a stack, he must also take all of the plates above it in that stack as well. + +Help Dr. Patel pick the P plates that would maximize the total sum of beauty values. + +Input +The first line of the input gives the number of test cases, T. T test cases follow. +Each test case begins with a line containing the three integers N, K and P. Then, N lines follow. +The i-th line contains K integers, describing the beauty values of each stack of plates from top to bottom. + +Output +For each test case, output one line containing Case #x: y, where x is the test case number +(starting from 1) and y is the maximum total sum of beauty values that Dr. Patel could pick. + +Limits +Time limit: 20 seconds per test set. +Memory limit: 1GB. +1 ≤ T ≤ 100. +1 ≤ K ≤ 30. +1 ≤ P ≤ N * K. +The beauty values are between 1 and 100, inclusive. + +Test set 1 +1 ≤ N ≤ 3. + +Test set 2 +1 ≤ N ≤ 50. + +Sample + +Input + +2 +2 4 5 +10 10 100 30 +80 50 10 50 +3 2 3 +80 80 +15 50 +20 10 + +Output + +Case #1: 250 +Case #2: 180 + + +In Sample Case #1, Dr. Patel needs to pick P = 5 plates: +He can pick the top 3 plates from the first stack (10 + 10 + 100 = 120). +He can pick the top 2 plates from the second stack (80 + 50 = 130) . +In total, the sum of beauty values is 250. + +In Sample Case #2, Dr. Patel needs to pick P = 3 plates: +He can pick the top 2 plates from the first stack (80 + 80 = 160). +He can pick no plates from the second stack. +He can pick the top plate from the third stack (20). +In total, the sum of beauty values is 180. + +Note: Unlike previous editions, in Kick Start 2020, all test sets are visible verdict test sets, +meaning you receive instant feedback upon submission. + +Analysis +From the constraints, we can see that regardless of the test set, 1 ≤ K ≤ 100. i.e., 1 ≤ P ≤ 100*N. + +Test set 1 +For this test set, we see that 1 ≤ N ≤ 3. So, we can check for every possible combination of taken plates +across all stacks and output the maximum sum. For example, if N = 3 and for any given values of K and P, +generate all possible triples (S1, S2, S3) such that S1+S2+S3 = P and 0 ≤ Si ≤ K. +Note: Si is the number of plates picked from the i-th stack. +This can be done via recursion and the total time complexity is O(KN) which abides by the time limits. + +Test set 2 +The solution we had for test set 1 doesn't scale given that N now is at most 100. +In order to tackle this test set, we use Dynamic Programming along with some precomputation. + +First, let's consider an intermediate state dp[i][j] which denotes the maximum sum that can be obtained using +the first i stacks when we need to pick j plates in total. Therefore, dp[N][P] would give us the maximum sum +using the first N stacks if we need to pick P plates in total. In order to compute dp[][] efficiently, we need +to be able to efficiently answer the question: What is the sum of the first x plates from stack i? +We can precompute this once for all N stacks. Let sum[i][x] denote the sum of first x plates from stack i. + +Next, we iterate over the stacks and try to answer the question: What is the maximum sum if we had to pick +j plates in total using the i stacks we've seen so far? This would give us dp[i][j]. However, we need to also +decide, among those j plates, how many come from the i-th stack? i.e., Let's say we pick x plates from the i-th +stack, then dp[i][j] = max(dp[i][j], sum[i][x]+dp[i-1][j-x]). Therefore, in order to pick j plates in total from +i stacks, we can pick anywhere between [0, 1, ..., j] plates from the i-th stack and [j, j-1, ..., 0] plates from +the previous i-1 stacks respectively. Also, we need to do this for all values of 1 ≤ j ≤ P. + +The flow would look like: +for i [1, N]: + for j [0, P]: +  dp[i][j] := 0 +   for x [0, min(j, K)]: +    dp[i][j] = max(dp[i][j], sum[i][x]+dp[i-1][j-x]) + +If we observe closely, this is similar to the 0-1 Knapsack Problem with some added complexity. +To conclude, the overall time complexity would be O(N*P*K). + +*/ +#include +using namespace std; + +#define FIO ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0) +#define int long long + +const int N = 51; +const int P = 51 * 30; +int cache[N][P]; + +int n, k, p; +int a[N][31]; +int pref[N][31]; + +int rec(int idx, int taken){ + + if(taken == p) + return 0; + + if(idx > n || taken > p) + return -1e9; + + if(cache[idx][taken] != -1) + return cache[idx][taken]; + + int ans = -1e9; + + for(int i = 0;i <= k; i++){ + ans = max(ans, pref[idx][i] + rec(idx + 1, taken + i)); + } + + return cache[idx][taken] = ans; +} + +int32_t main(){ + + FIO; + int t; + cin >> t; + int tc = 0; + while(t--){ + tc++; + + cin >> n >> k >> p; + for(int i = 1; i <= n; i++){ + for(int j = 1; j <= k; j++){ + cin >> a[i][j]; + pref[i][j] = pref[i][j - 1] + a[i][j]; + } + } + memset(cache, -1, sizeof(cache)); + int ans = rec(1, 0); + cout << "Case #" << tc << ": " << ans << '\n'; + } + return 0; +} \ No newline at end of file diff --git a/C++/PrimeSieve.cpp b/C++/PrimeSieve.cpp new file mode 100644 index 0000000..36185fa --- /dev/null +++ b/C++/PrimeSieve.cpp @@ -0,0 +1,33 @@ +#include + +using namespace std; + +void prime_sieve(int *p){ + + for(int i = 3; i <= 1000000; i+=2){ + p[i] = 1; + } + + for(long long i = 3; i <= 1000000; i+=2){ + if(p[i] == 1){ + for(long long j = 2*i; j <= 1000000; j = j + i){ + p[j] = 0; + } + } + } + p[2] = 1; + p[1] = p[0] = 0; +} + +int main(){ + int n; + cin >> n; + int p[1000000] = {0}; + prime_sieve(p); + + for(int i = 0; i <= n; i++){ + if(p[i] == 1){ + cout << i << " "; + } + } +} \ No newline at end of file diff --git a/C++/PrimeVisits.cpp b/C++/PrimeVisits.cpp new file mode 100644 index 0000000..e5b7f08 --- /dev/null +++ b/C++/PrimeVisits.cpp @@ -0,0 +1,72 @@ +/* + +PMO gives two random numbers a & b to the Prime Minister. PM Modi wants to visit all countries between a and b (inclusive), +However due to shortage of time he can't visit each and every country , So PM Modi decides to visit only those countries, +for which country number has two divisors. So your task is to find number of countries Mr. Modi will visit. + +Input Format +The first line contains N , no of test cases. The next N lines contain two integers a and b denoting the range of country numbers. + +Constraints +a<=1000000 & b<=1000000. +N<=1000 + +Output Format +Output contains N lines each containing an answer for the test case. + +Sample Input +2 +1 10 +11 20 + +Sample Output +4 +4 + +Explanation +PM Modi chooses countries with numbers 2,3,5 and 7 for the first testcase. +For the second testcase , he chooses countries with numbers 11,13,17 and 19. + +*/ + +#include + +using namespace std; + +void prime_sieve(int *p){ + + for(int i = 3; i <= 1000000; i+=2){ + p[i] = 1; + } + + for(long long i = 3; i <= 1000000; i+=2){ + if(p[i] == 1){ + for(long long j = 2*i; j <= 1000000; j = j + i){ + p[j] = 0; + } + } + } + p[2] = 1; + p[1] = p[0] = 0; +} + +int main(){ + int p[1000005] = {0}; + prime_sieve(p); + + int csum[1000005] = {0}; + for(int i = 1; i <= 1000000; i++){ + csum[i] = csum[i-1] + p[i]; + } + + int q; + cin >> q; + while(q--){ + int a, b; + cin >> a >> b; + cout << csum[b] - csum[a-1] << endl; + } + + return 0; + +} \ No newline at end of file diff --git a/C++/PriorityQueue.cpp b/C++/PriorityQueue.cpp new file mode 100644 index 0000000..709463e --- /dev/null +++ b/C++/PriorityQueue.cpp @@ -0,0 +1,38 @@ +#include +#include + +using namespace std; + +void showpq(priority_queue gq) +{ + priority_queue g = gq; + while (!g.empty()) + { + cout << '\t' << g.top(); + g.pop(); + } + cout << '\n'; +} + +int main () +{ + priority_queue gquiz; + gquiz.push(10); + gquiz.push(30); + gquiz.push(20); + gquiz.push(5); + gquiz.push(1); + + cout << "The priority queue gquiz is : "; + showpq(gquiz); + + cout << "\ngquiz.size() : " << gquiz.size(); + cout << "\ngquiz.top() : " << gquiz.top(); + + + cout << "\ngquiz.pop() : "; + gquiz.pop(); + showpq(gquiz); + + return 0; +} \ No newline at end of file diff --git a/C++/QuickSort.cpp b/C++/QuickSort.cpp new file mode 100644 index 0000000..6debbbc --- /dev/null +++ b/C++/QuickSort.cpp @@ -0,0 +1,42 @@ +#include + +using namespace std; + +int partition(int *a, int s, int e){ + int i = s - 1; + int j = s; + + int pivot = a[e]; + for( ; j <= e - 1; j++){ + if(a[j] <= pivot){ + i = i + 1; + swap(a[i], a[j]); + } + } + swap(a[i + 1], a[e]); + return (i + 1); +} + +void quickSort(int *a, int s, int e){ + if(s >= e){ + return; + } + + int p = partition(a, s, e); + quickSort(a, s, p - 1); + quickSort(a, p + 1, e); +} + +int main(){ + int n; + cin >> n; + int a[1000]; + for(int i = 0; i < n; i++){ + cin >> a[i]; + } + quickSort(a, 0, n-1); + for(int i = 0; i < n; i++){ + cout << a[i]; + } + return 0; +} \ No newline at end of file diff --git a/C++/README.md b/C++/README.md new file mode 100644 index 0000000..d87a02c --- /dev/null +++ b/C++/README.md @@ -0,0 +1,3 @@ +# Competitve-Coding + +Just a rudimentary practice repository for competitive coding and brush up of basics diff --git a/C++/RotateArray.cpp b/C++/RotateArray.cpp new file mode 100644 index 0000000..8cca959 --- /dev/null +++ b/C++/RotateArray.cpp @@ -0,0 +1,91 @@ +/* +Given a 2D array of size N x N. Rotate the array 90 degrees anti-clockwise. + +Input Format +First line contains a single integer N. Next N lines contain N space separated integers. + +Constraints +N < 1000 + +Output Format +Print N lines with N space separated integers of the rotated array. + +Sample Input +4 +1 2 3 4 +5 6 7 8 +9 10 11 12 +13 14 15 16 + +Sample Output +4 8 12 16 +3 7 11 15 +2 6 10 14 +1 5 9 13 + +Explanation +Rotate the array 90 degrees anticlockwise. +*/ + +#include +#include + +using namespace std; + +void rotate(int a[][1000], int n){ + // Reverse + for(int i = 0; i < n; i++){ + int start_col = 0; + int end_col = n-1; + while(start_col < end_col){ + swap(a[i][start_col], a[i][end_col]); + start_col++; + end_col--; + } + } + + // Transpose + for(int i = 0; i < n; i++){ + for(int j = 0; j < n; j++){ + if(i < j){ + swap(a[i][j], a[j][i]); + } + } + } +} + +void rotate_stl(int a[][1000], int n){ + for(int i = 0; i < n; i++){ + reverse(a[i], a[i] + n); + } + + for(int i = 0; i < n; i++){ + for(int j = 0; j < n; j++){ + if(i < j){ + swap(a[i][j], a[j][i]); + } + } + } +} + +int main(){ + int a[1000][1000]; + int n; + cin >> n; + + for(int i = 0; i < n; i++){ + for(int j = 0; j < n; j++){ + cin >> a[i][j]; + } + } + + rotate(a, n); + for(int i = 0; i < n; i++){ + for(int j = 0; j < n; j++){ + cout << a[i][j] << " "; + } + cout << endl; + } + + return 0; +} diff --git a/C++/SelectionSort.cpp b/C++/SelectionSort.cpp new file mode 100644 index 0000000..3493dc1 --- /dev/null +++ b/C++/SelectionSort.cpp @@ -0,0 +1,31 @@ +#include + +using namespace std; + +void selectionSort(int a[], int n){ + for(int i = 0; i < n - 1; i++){ + int min_index = i; + for(int j = i + 1; j <= n - 1; j++){ + if(a[j] < a[min_index]){ + min_index = j; + } + } + swap(a[i], a[min_index]); + } + + +} + +int main(){ + int n; + cin >> n; + int a[1000]; + for(int i = 0; i < n; i++){ + cin >> a[i]; + } + selectionSort(a, n); + for(int i = 0; i < n; i++){ + cout << a[i]; + } + return 0; +} \ No newline at end of file diff --git a/C++/SleepingSchedule.cpp b/C++/SleepingSchedule.cpp new file mode 100644 index 0000000..9df635e --- /dev/null +++ b/C++/SleepingSchedule.cpp @@ -0,0 +1,138 @@ +/* +Code Forces #627 E +Sleeping Schedule + +time limit per test: 2 seconds +memory limit per test: 256 megabytes +input: standard input +output: standard output + +Vova had a pretty weird sleeping schedule. There are h hours in a day. +Vova will sleep exactly n times. The i-th time he will sleep exactly after ai hours from the time he woke up. +You can assume that Vova woke up exactly at the beginning of this story (the initial time is 0). +Each time Vova sleeps exactly one day (in other words, h hours). + +Vova thinks that the i-th sleeping time is good if he starts to sleep between hours l and r inclusive. + +Vova can control himself and before the i-th time can choose between two options: +go to sleep after ai hours or after ai−1 hours. + +Your task is to say the maximum number of good sleeping times Vova can obtain if he acts optimally. + +Input +The first line of the input contains four integers n,h,l and r (1≤n≤2000,3≤h≤2000,0≤l≤r +#include +using namespace __gnu_pbds; +using namespace std; + +#define ff first +#define ss second +#define int long long +#define pb push_back +#define mp make_pair +#define pii pair +#define vi vector +#define mii map +#define pqb priority_queue +#define pqs priority_queue > +#define setbits(x) __builtin_popcountll(x) +#define zrobits(x) __builtin_ctzll(x) +#define mod 1000000007 +#define inf 1e18 +#define ps(x,y) fixed<>x; while(x--) +#define pw(b,p) pow(b,p) + 0.1 +mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); + +typedef tree, rb_tree_tag, tree_order_statistics_node_update> pbds; + + +void c_p_c() +{ + ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); +#ifndef ONLINE_JUDGE + freopen("input.txt", "r", stdin); + freopen("output.txt", "w", stdout); +#endif +} + +int dp[2001][2001]; +int a[2001]; + +int32_t main() +{ + c_p_c(); + int n, h, l, r; + cin >> n >> h >> l >> r; + + dp[0][0] = 0; + + for (int i = 1; i < h; ++i) + dp[0][i] = -1; + + + for (int i = 1; i <= n; ++i) + cin >> a[i]; + + + for (int i = 0; i < n; ++i){ + for (int hr = 0; hr < h; ++hr){ + dp[i + 1][hr] = -1; + } + + for (int hr = 0; hr < h; ++hr){ + if (dp[i][hr] == -1) + continue; + + int h1 = (hr + a[i + 1] - 1 + h) % h; + int h2 = (hr + a[i + 1]) % h; + + dp[i + 1][h1] = max(dp[i + 1][h1], dp[i][hr] + (l <= h1 && h1 <= r)); + dp[i + 1][h2] = max(dp[i + 1][h2], dp[i][hr] + (l <= h2 && h2 <= r)); + } + } + + int ans = 0; + + for (int i = 0; i < h; ++i) + if (dp[n][i] != -1) + ans = max(ans, dp[n][i]); + + cout << ans << '\n'; + return 0; +} \ No newline at end of file diff --git a/C++/SortStrings.cpp b/C++/SortStrings.cpp new file mode 100644 index 0000000..fc7bed7 --- /dev/null +++ b/C++/SortStrings.cpp @@ -0,0 +1,142 @@ +/* + +Given a list of 'n' strings S0,S1,S2,……,Sn-1, each consisting of digits and spaces, +the number of spaces is the same for each entry, the goal is to implement a variation of a sort command. +None of the strings contains consecutive spaces. Also, no string starts with a space nor ends with it. +Spaces are used to divide string into columns, which can be used as keys in comparisons. + +The program has to support the required parameters: + +key: integer denoting the column used as a key in comparisons. The left-most column is denoted by 1. + +reversed: boolean variable indicating whether to reverse the result of comparisons. + +comparison-type: either lexicographic or numeric. +Lexicographic means that we use Lexicographical order where for example (122 < 13). +Numeric means that we compare the strings by their numerical values, so (13 < 122). +If the comparison type is 'numeric' and numeric values of keys of Si and Sj are equal for i < j, +then Si is considered strictly smaller than Sj because it comes first. + +Input Format +In the first line, there is a single integer 'n' denoting the number of strings to sort. +In the i-th of the following n lines there is a string Si. In the last line, +there are 3 space-separated values, denoting the values of variables 'key','reversed' , comparison-type. + +Constraints +1 <= n <= 10^5 +1 <= |Si| <= 50 +1 <= key <= number of spaces in each string + 1 + +reversed = { true or false } + +comparison-type = {lexicographical , numeric } + +None of the strings contains consecutive spaces. + +No string starts with a space nor ends with it. + +All column values in all the strings are unique. + +Output Format +Print exactly n lines. In the i-th of them, print the i-th string in the resulting order. + +Sample Input +3 +92 022 +82 12 +77 13 +2 false numeric + +Sample Output +82 12 +77 13 +92 022 + +Explanation +The key for ordering is 2, reversal is false and ordering is numeric. +Therefore, the keys 022, 12 and 13 should be ordered as 12, 13 and 022. +Therefore, the final output is 82 12, 77 13 and 92 022. + +*/ + +#include +#include +#include + +using namespace std; + +string extractStringAtKey(string str, int key){ + char *s = strtok((char *)str.c_str(), " "); + while(key > 1){ + s = strtok(NULL, " "); + key--; + } + return (string)s; +} + +int convertToInt(string s){ + int ans = 0; + int p = 1; + for(int i = s.length()-1; i >= 0; i--){ + ans = ans + ((s[i] - '0')*p); + p = p * 10; + } + return ans; +} + +bool numericCompare(pair s1, pair s2){ + string k1, k2; + k1 = s1.second; + k2 = s2.second; + + return convertToInt(k1) < convertToInt(k2); +} + +bool lexicoCompare(pair s1, pair s2){ + string k1, k2; + k1 = s1.second; + k2 = s2.second; + + return k1 < k2; +} + +int main(){ + int n; + cin >> n; + cin.get(); + + string a[100]; + for(int i = 0; i < n; i++){ + getline(cin, a[i]); + } + + int key; + string reversal, ordering; + cin >> key >> reversal >> ordering; + + pair strPair[100]; + + for(int i = 0; i < n; i++){ + strPair[i].first = a[i]; + strPair[i].second = extractStringAtKey(a[i], key); + } + + if(ordering == "numeric"){ + sort(strPair, strPair + n, numericCompare); + } else { + sort(strPair, strPair + n, lexicoCompare); + } + + if(reversal == "true"){ + for(int i = 0; i < n/2; i++){ + swap(strPair[i], strPair[n - i - 1]); + } + } + + for(int i = 0; i < n; i++){ + cout << strPair[i].first << endl; + } + + return 0; + +} \ No newline at end of file diff --git a/C++/Swastika.cpp b/C++/Swastika.cpp new file mode 100644 index 0000000..0d4dad8 --- /dev/null +++ b/C++/Swastika.cpp @@ -0,0 +1,94 @@ +/* + +Take as input N, an odd number (>=5) . Print the following pattern as given below for N = 7. + +* **** +* * +* * +******* + * * + * * +**** * + +Input Format +Enter value of N ( >=5 ) + +Constraints +5 <= N <= 99 + +Output Format +Print the required pattern. + +Sample Input +7 + +Sample Output +* **** +* * +* * +******* + * * + * * +**** * + +Explanation +Catch the pattern for the corresponding input and print it accordingly. + +*/ + +#include + +using namespace std; + +int main() { + int n; + cin >> n; + + //First Component + cout << "*"; + for(int i = 1; i <= (n-3)/2; i++){ + cout << " "; + } + for(int i = 1; i <= (n+1)/2; i++){ + cout << "*"; + } + cout << endl; + + //Second Component + for(int i = 1; i <= (n-3)/2; i++){ + cout << "*"; + for(int j = 1; j <= (n-3)/2; j++){ + cout << " "; + } + cout << "*" << endl; + } + + //Third Component + for(int i = 1; i <= n; i++){ + cout << "*"; + } + cout << endl; + + //Fourth Component + for(int i = 1; i <= (n-3)/2; i++){ + for (int j = 1; j <= ((n-3)/2)+1; j++){ + cout << " "; + } + cout << "*"; + for(int k = 1; k <= (n-3)/2; k++){ + cout << " "; + } + cout << "*" << endl; + } + + //Fifth Component + for(int i = 1; i <= (n+1)/2; i++){ + cout << "*"; + } + for(int i = 1; i <= (n-3)/2; i++){ + cout << " "; + } + cout << "*" << endl; + + return 0; +} \ No newline at end of file diff --git a/C++/TemplateCode.cpp b/C++/TemplateCode.cpp new file mode 100644 index 0000000..a4b6280 --- /dev/null +++ b/C++/TemplateCode.cpp @@ -0,0 +1,41 @@ +#include +#include +using namespace __gnu_pbds; +using namespace std; + +#define ff first +#define ss second +#define int long long +#define pb push_back +#define mp make_pair +#define pii pair +#define vi vector +#define mii map +#define pqb priority_queue +#define pqs priority_queue > +#define setbits(x) __builtin_popcountll(x) +#define zrobits(x) __builtin_ctzll(x) +#define mod 1000000007 +#define inf 1e18 +#define ps(x,y) fixed<>x; while(x--) +mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); + +typedef tree, rb_tree_tag, tree_order_statistics_node_update> pbds; + + +void c_p_c() +{ + ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); +#ifndef ONLINE_JUDGE + freopen("input.txt", "r", stdin); + freopen("output.txt", "w", stdout); +#endif +} + +int32_t main() +{ + c_p_c(); + return 0; +} \ No newline at end of file diff --git a/C++/TemplateCodeTwo.cpp b/C++/TemplateCodeTwo.cpp new file mode 100644 index 0000000..3177283 --- /dev/null +++ b/C++/TemplateCodeTwo.cpp @@ -0,0 +1,32 @@ +#include +#include +using namespace __gnu_pbds; +using namespace std; + +#define ff first +#define ss second +#define int long long +#define pb push_back +#define mp make_pair +#define pii pair +#define vi vector +#define mii map +#define pqb priority_queue +#define pqs priority_queue > +#define setbits(x) __builtin_popcountll(x) +#define zrobits(x) __builtin_ctzll(x) +#define mod 1000000007 +#define inf 1e18 +#define ps(x,y) fixed<>x; while(x--) +#define FIO ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0) +mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); + +typedef tree, rb_tree_tag, tree_order_statistics_node_update> pbds; + +int32_t main() +{ + FIO; + return 0; +} \ No newline at end of file diff --git a/C++/TrailingZeroes.cpp b/C++/TrailingZeroes.cpp new file mode 100644 index 0000000..c07690e --- /dev/null +++ b/C++/TrailingZeroes.cpp @@ -0,0 +1,43 @@ +/* + +Given an integer n, write a function that returns count of trailing zeroes in n!. +Input Format +A single integer N. + +Constraints +1 <= N <= 10^9 + +Output Format +A single integer denoting the count of trailing zeroes in N! + +Sample Input +5 + +Sample Output +1 + +Explanation +Factorial of 5 is 120 which has one trailing 0. + +*/ + +#include + +using namespace std; + +int findZeroes(int n){ + int ans = 0; + int p = 5; + while((n/p) > 0){ + ans = ans + (n/p); + p = p*5; + } + return ans; +} + +int main(){ + long long int n; + cin >> n; + cout << findZeroes(n) << endl; + return 0; +} \ No newline at end of file diff --git a/C++/TravelingSalesman.cpp b/C++/TravelingSalesman.cpp new file mode 100644 index 0000000..f130fd6 --- /dev/null +++ b/C++/TravelingSalesman.cpp @@ -0,0 +1,53 @@ +#include +#include + +using namespace std; + +#define INT_MAX 999999 + +int n = 4; + +int dp[16][4]; + +int dist[10][10] = { + {0, 20, 42, 25}, + {20, 0, 30, 34}, + {42, 30, 0, 10}, + {25, 34, 10, 0} +}; + +int VISITED_ALL = (1 << n) - 1; + +int tsp(int mask, int pos){ + + if(mask == VISITED_ALL){ + return dist[pos][0]; + } + + if(dp[mask][pos] != -1){ + return dp[mask][pos]; + } + + int ans = INT_MAX; + + for(int city = 0; city < n; city++){ + if((mask&(1< +#include +using namespace __gnu_pbds; +using namespace std; + +#define ff first +#define ss second +#define int long long +#define pb push_back +#define mp make_pair +#define pii pair +#define vi vector +#define mii map +#define pqb priority_queue +#define pqs priority_queue > +#define setbits(x) __builtin_popcountll(x) +#define zrobits(x) __builtin_ctzll(x) +#define mod 1000000007 +#define inf 1e18 +#define ps(x,y) fixed<>x; while(x--) +#define FIO ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0) +mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); + +typedef tree, rb_tree_tag, tree_order_statistics_node_update> pbds; + +int32_t main() +{ + FIO; + int k; + cin >> k; + + if (!k){ + cout << 1 << ' ' << 1 << '\n' << 100 << '\n'; + } else { + cout << 3 << ' ' << 3 << '\n'; + int all_one = (1 << 18) - 1; + int pw17 = 1 << 17; + + cout << all_one << ' ' << all_one << ' ' << pw17 << '\n'; + cout << all_one << ' ' << k << ' ' << pw17 + k << '\n'; + cout << pw17 << ' ' << pw17 + k << ' ' << k << '\n'; + } + return 0; +} \ No newline at end of file diff --git a/C++/Wine.cpp b/C++/Wine.cpp new file mode 100644 index 0000000..a237b10 --- /dev/null +++ b/C++/Wine.cpp @@ -0,0 +1,28 @@ +#include +#include + +using namespace std; + +int profit(int wines[], int i, int j, int k, int dp[][100]){ + + if(i > j){ + return 0; + } + + if(dp[i][j] != 0){ + return dp[i][j]; + } + + int op1 = wines[i]*k + profit(wines, i+1, j, k+1, dp); + int op2 = wines[j]*k + profit(wines, i, j-1, k+1, dp); + return dp[i][j] = max(op1, op2); +} + +int main(){ + int wines[] = {2, 3, 5, 1, 4}; + int dp[100][100] = {0}; + int n = sizeof(wines)/sizeof(int); + int k = 1; + cout << profit(wines, 0, n-1, k, dp); + return 0; +} \ No newline at end of file diff --git a/C++/YetAnotherPalindrome.cpp b/C++/YetAnotherPalindrome.cpp new file mode 100644 index 0000000..020c35d --- /dev/null +++ b/C++/YetAnotherPalindrome.cpp @@ -0,0 +1,155 @@ +/* +Code Forces Round #627 B +Yet Another Palindrome Problem + +time limit per test: 2 seconds +memory limit per test: 256 megabytes +input: standard input +output: standard output +You are given an array a consisting of n integers. + +Your task is to determine if a has some subsequence of length at least 3 that is a palindrome. + +Recall that an array b is called a subsequence of the array a if b can be obtained by removing +some (possibly, zero) elements from a (not necessarily consecutive) without changing the order +of remaining elements. For example, [2], [1,2,1,3] and [2,3] are subsequences of [1,2,1,3], +but [1,1,2] and [4] are not. + +Also, recall that a palindrome is an array that reads the same backward as forward. +In other words, the array a of length n is the palindrome if ai=an−i−1 for all i from 1 to n. +For example, arrays [1234], [1,2,1], [1,3,2,2,3,1] and [10,100,10] are palindromes, +but arrays [1,2] and [1,2,3,1] are not. + +You have to answer t independent test cases. + +Input +The first line of the input contains one integer t (1≤t≤100) — the number of test cases. + +Next 2t lines describe test cases. The first line of the test case contains one +integer n (3≤n≤5000) — the length of a. The second line of the test case contains +n integers a1,a2,…,an (1≤ai≤n), where ai is the i-th element of a. + +It is guaranteed that the sum of n over all test cases does not exceed 5000 (∑n≤5000). + +Output +For each test case, print the answer — "YES" (without quotes) if a has some subsequence of length +at least 3 that is a palindrome and "NO" otherwise. + +Example: + +input + +5 +3 +1 2 1 +5 +1 2 2 3 2 +3 +1 1 2 +4 +1 2 2 1 +10 +1 1 2 2 3 3 4 4 5 5 + +output + +YES +YES +NO +YES +NO + +Note +In the first test case of the example, +the array a has a subsequence [1,2,1] which is a palindrome. + +In the second test case of the example, +the array a has two subsequences of length 3 which are palindromes: [2,3,2] and [2,2,2]. + +In the third test case of the example, +the array a has no subsequences of length at least 3 which are palindromes. + +In the fourth test case of the example, +the array a has one subsequence of length 4 which is a palindrome: +[1,2,2,1] (and has two subsequences of length 3 which are palindromes: both are [1,2,1]). + +In the fifth test case of the example, +the array a has no subsequences of length at least 3 which are palindromes. + +*/ + +#include +#include +using namespace __gnu_pbds; +using namespace std; + +#define ff first +#define ss second +#define int long long +#define pb push_back +#define mp make_pair +#define pii pair +#define vi vector +#define mii map +#define pqb priority_queue +#define pqs priority_queue > +#define setbits(x) __builtin_popcountll(x) +#define zrobits(x) __builtin_ctzll(x) +#define mod 1000000007 +#define inf 1e18 +#define ps(x,y) fixed<>x; while(x--) +#define pw(b,p) pow(b,p) + 0.1 +mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); + +typedef tree, rb_tree_tag, tree_order_statistics_node_update> pbds; + + +void c_p_c() +{ + ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); +#ifndef ONLINE_JUDGE + freopen("input.txt", "r", stdin); + freopen("output.txt", "w", stdout); +#endif +} + +int32_t main() +{ + c_p_c(); + w(t){ + + int n; + cin >> n; + mk(arr, n + 1, int); + + for (int i = 1; i <= n; ++i){ + cin >> arr[i]; + } + + string ans = "NO"; + + map idv; + + for (int i = 1; i <= n; ++i) + idv[arr[i]].pb(i); + + for (auto el : idv){ + if (el.ss.size() >= 3){ + ans = "YES"; + break; + } + } + + for (auto el : idv){ + if (el.ss.size() == 2 && el.ss[0] != el.ss[1] - 1){ + ans = "YES"; + break; + } + } + + cout << ans << '\n'; + } + return 0; +} \ No newline at end of file diff --git a/C++/YetAnotherTetrisProblem.cpp b/C++/YetAnotherTetrisProblem.cpp new file mode 100644 index 0000000..ec7c814 --- /dev/null +++ b/C++/YetAnotherTetrisProblem.cpp @@ -0,0 +1,142 @@ +/* +Code Forces Round #627 A +Yet Another Tetris Problem + +time limit per test: 2 seconds +memory limit per test: 256 megabytes +input: standard input +output: standard output +You are given some Tetris field consisting of n columns. The initial height of the i-th column of the field is ai blocks. +On top of these columns you can place only figures of size 2×1 +(i.e. the height of this figure is 2 blocks an the width of this figure is 1 block). Note that you cannot rotate these figures. + +Your task is to say if you can clear the whole field by placing such figures. + +More formally, the problem can be described like this: + +The following process occurs while at least one ai is greater than 0: + +You place one figure 2×1 (choose some i from 1 to n and replace ai with ai+2); +then, while all ai are greater than zero, replace each ai with ai−1. +And your task is to determine if it is possible to clear the whole field (i.e. finish the described process), +choosing the places for new figures properly. + +You have to answer t independent test cases. + +Input +The first line of the input contains one integer t (1≤t≤100) — the number of test cases. + +The next 2t lines describe test cases. The first line of the test case contains one integer n (1≤n≤100) — +the number of columns in the Tetris field. The second line of the test case contains n integers a1,a2,…,an (1≤ai≤100), +where ai is the initial height of the i-th column of the Tetris field. + +Output +For each test case, print the answer — "YES" (without quotes) if you can clear the whole Tetris field and "NO" otherwise. + +Example: + +input + +4 +3 +1 1 3 +4 +1 1 2 1 +2 +11 11 +1 +100 + +output + +YES +NO +YES +YES + +Note + +The first test case of the example field is shown below: + +Gray lines are bounds of the Tetris field. Note that the field has no upper bound. + +One of the correct answers is to first place the figure in the first column. +Then after the second step of the process, the field becomes [2,0,2]. +Then place the figure in the second column and after the second step of the process, the field becomes [0,0,0]. + +And the second test case of the example field is shown below: + +It can be shown that you cannot do anything to end the process. + +In the third test case of the example, you first place the figure in the second column after the second step of the process, +the field becomes [0,2]. Then place the figure in the first column and after the second step of the process, the field becomes [0,0]. + +In the fourth test case of the example, place the figure in the first column, +then the field becomes [102] after the first step of the process, +and then the field becomes [0] after the second step of the process. + +*/ + +#include +#include +using namespace __gnu_pbds; +using namespace std; + +#define ff first +#define ss second +#define int long long +#define pb push_back +#define mp make_pair +#define pii pair +#define vi vector +#define mii map +#define pqb priority_queue +#define pqs priority_queue > +#define setbits(x) __builtin_popcountll(x) +#define zrobits(x) __builtin_ctzll(x) +#define mod 1000000007 +#define inf 1e18 +#define ps(x,y) fixed<>x; while(x--) +mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); + +typedef tree, rb_tree_tag, tree_order_statistics_node_update> pbds; + + +void c_p_c() +{ + ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); +#ifndef ONLINE_JUDGE + freopen("input.txt", "r", stdin); + freopen("output.txt", "w", stdout); +#endif +} + +int32_t main() +{ + c_p_c(); + w(t){ + int n; + cin >> n; + mk(arr, n+1, int); + int cnt[2] = {}; + + for(int i = 1; i <= n; i++){ + cin >> arr[i]; + } + + for(int i = 1; i <= n; i++){ + cnt[arr[i]%2]++; + } + + if(cnt[0] && cnt[1]){ + cout << "NO\n"; + } + else{ + cout << "YES\n"; + } + + } + return 0; +} \ No newline at end of file diff --git a/C++/multithreading.cpp b/C++/multithreading.cpp new file mode 100644 index 0000000..641a7c9 --- /dev/null +++ b/C++/multithreading.cpp @@ -0,0 +1,80 @@ +#include +#include +using namespace std; + +// A dummy function +void foo(int Z) +{ + for (int i = 0; i < Z; i++) { + cout << "Thread using function pointer as callable\n"; + } +} + +// A callable object +class thread_obj { +public: + void operator()(int x) + { + for (int i = 0; i < x; i++) + cout << "Thread using function object as callable\n"; + } +}; + +int main() +{ + cout << "Threads 1 and 2 and 3 operating independently" << endl; + + // This thread is launched by using + // function pointer as callable + thread th1(foo, 3); + + // This thread is launched by using + // function object as callable + thread th2(thread_obj(), 3); + + // Define a Lambda Expression + auto f = [](int x) { + for (int i = 0; i < x; i++) + cout << "Thread using lambda expression as callable\n"; + }; + + // This thread is launched by using + // lamda expression as callable + thread th3(f, 3); + + // Wait for the threads to finish + // Wait for thread t1 to finish + th1.join(); + + // Wait for thread t2 to finish + th2.join(); + + // Wait for thread t3 to finish + th3.join(); + + return 0; +} + + + +/* + Note: + To compile programs with std::thread support use + + g++ -std=c++11 -pthread + + + Output: + + Threads 1 and 2 and 3 operating independently + Thread using function pointer as callable + Thread using lambda expression as callable + Thread using function pointer as callable + Thread using lambda expression as callable + Thread using function object as callable + Thread using lambda expression as callable + Thread using function pointer as callable + Thread using function object as callable + Thread using function object as callable + +*/ \ No newline at end of file