Clasa a XI-a · high schoolCitește în română
Grade 11 algorithmsClasa a XI-a
The grade 11 part of the collection, chapter by chapter. Read the idea, run the code against the examples and track what you've learned.
- 62algorithms
- 7chapters
- 1grade
62 algorithms
Grade 11Clasa a XI-a
0%0%
Backtracking
Metoda backtracking · 12 algorithms
- Generating arrangements (k-permutations)Generarea aranjamentelorPrints, in lexicographic order, all arrangements of n elements taken k at a time: sequences of k distinct values from {1, ..., n} where order…
- Map coloringColorarea hărțilorA map has n countries numbered from 1, and m pairs (a, b) say that countries a and b are neighbours. We color every country with one of the colors…
- Generating combinationsGenerarea combinărilorPrints all k-element subsets of the set {1, ..., n} (combinations of n taken k at a time). To avoid getting the same subset several times, the…
- Paths in a mazeDrumuri într-un labirintThe maze is an n × m matrix of 0 (free) and 1 (wall). We start in the top-left corner (1, 1) and want to reach the bottom-right corner (n, m),…
- The n-queens problemProblema celor n dameWe place n queens on an n × n board so that none attacks another (no pair on the same row, column or diagonal). We put one queen on every row, and…
- Generating balanced parenthesesGenerarea parantezărilor corectePrints, in lexicographic order ('(' before ')'), all balanced strings made of n pairs of round brackets. We keep the number of brackets opened and…
- Partitions of a natural numberPartițiile unui număr naturalPrints all ways of writing n as a sum of non-zero natural numbers, where the order of the terms does not matter. To avoid repeating the same…
- Permutations with neighbours of alternating parityPermutări cu vecini de parități diferitePrints the permutations of the set {1, ..., n} in which any two neighbouring elements have different parities (one even, the other odd). Compared…
- Generating permutationsGenerarea permutărilorPrints, in lexicographic order, all permutations of the set {1, 2, ..., n}. The solution is built in the array x, position by position. At position…
- Paying a sum with given coinsPlata unei sume cu monede dateThere are n coin types with values v[1..n], as many of each as we want. We print all ways of paying exactly the sum S. x[k] is the number of coins…
- Cartesian productProdusul carteziann sets are given; set i is {1, 2, ..., a[i]}. All elements of the Cartesian product are printed, i.e. all sequences (x1, ..., xn) with 1 ≤ xi ≤…
- Generating subsetsGenerarea submulțimilorPrints all non-empty subsets of the set {1, ..., n}, in lexicographic order. The elements of a subset are placed in strictly increasing order (as…
0%
The greedy method
Metoda greedy · 6 algorithms
- Covering a segment with the minimum number of intervalsAcoperirea unui segment cu număr minim de intervaleWe want to cover the segment [A, B] using as few as possible of the n given intervals [s[i], f[i]]. We sort the intervals by their left end. We keep…
- Scheduling shows (activity selection)Planificarea spectacolelorn shows can be held in a hall; show i starts at time s[i] and ends at time f[i]. We want to schedule as many non-overlapping shows as possible (one…
- Paying a sum with the minimum number of banknotesPlata unei sume cu număr minim de bancnoten banknote values are given (we have any number of each) and a sum S. The greedy strategy: pay as much as possible with the largest banknote, then…
- The knapsack problem (fractional version)Problema rucsacului (varianta fracționară)A knapsack holds at most G kilograms. There are n objects; object i has weight g[i] and value v[i], and we may take just a piece (a fraction) of any…
- Maximum sum with k elementsSuma maximă cu k elementeFrom a sequence of n integers we choose exactly k elements (on different positions) with the largest possible sum. The greedy choice is obvious:…
- Minimizing the average waiting timeMinimizarea timpului mediu de așteptaren customers wait at a counter; serving customer i takes t[i] minutes. A customer's waiting time is the sum of the service times of the customers…
0%
Dynamic programming
Programare dinamică · 10 algorithms
- Longest common subsequenceCel mai lung subșir comunTwo words a and b are given. We look for the longest sequence of letters that appears as a subsequence (letters in order, not necessarily adjacent)…
- Edit distanceDistanța de editareWhat is the minimum number of operations needed to turn the word a into the word b? An operation means inserting, deleting or replacing a letter.…
- Maximum-sum path in a matrixDrum de sumă maximă în matriceIn an n × m matrix we start from the corner (1, 1) and reach (n, m) moving only right or down. We want the maximum sum of the elements on the path.…
- Number of paths in a grid with obstaclesNumărul de drumuri într-o grilă cu obstacoleAn n × m grid has free cells (0) and obstacles (1). How many paths lead from (1, 1) to (n, m) if we move only right or down and never enter…
- Minimum number of coinsNumărul minim de monedeThere are n coin types (any number of each) and we want to pay exactly the sum S with as few coins as possible. Greedy can be wrong (for the coins…
- Number of partitions of a numberNumărul partițiilor unui numărIn how many ways can n be written as a sum of non-zero natural numbers, where the order of the terms does not matter? (4 = 4 = 3+1 = 2+2 = 2+1+1 =…
- The knapsack problem (0/1 version)Problema rucsacului (varianta discretă)A knapsack holds at most G kilograms; there are n objects with weights g[i] and values v[i], and an object is taken whole or not at all. Here greedy…
- Longest strictly increasing subsequenceSubșirul strict crescător de lungime maximăFrom a sequence of n numbers we choose a strictly increasing subsequence (elements in their order in the sequence, not necessarily adjacent) that is…
- Maximum sum in a number triangleSuma maximă în triunghiul de numereA triangle has n rows; row i holds i numbers. We start from the top and at every step go either straight down (a[i+1][j]) or down and to the right…
- Number of ways to climb a staircaseNumărul de moduri de a urca o scarăA staircase has n steps; at every move we climb either one step or two. In how many ways can we reach the top? Step i is reached either from step i…
0%
Dynamic allocation: lists, stacks, queues
Alocare dinamică: liste, stive, cozi · 10 algorithms
- Queue implemented with a linked listCoada implementată cu o listă înlănțuităThe queue is kept as a singly linked list with two pointers: prim (where we remove) and ultim (where we add). push links a new node after ultim; pop…
- Queue implemented with an arrayCoada implementată cu un vectorThe queue is a FIFO structure (first in, first out): elements are added at the end and removed from the front, as at a ticket counter. With an array…
- Evaluating an expression in postfix (reverse Polish) notationEvaluarea unei expresii în formă poloneză postfixatăIn postfix notation the operator is written after its operands: (3 + 4) * 2 becomes 3 4 + 2 *, and parentheses are no longer needed. We read the…
- Inserting into a sorted listInserarea într-o listă ordonatăWe read n numbers and insert them one by one into a singly linked list that is always kept in increasing order. If the new value is smaller than the…
- Doubly linked listLista dublu înlănțuităIn a doubly linked list every node stores both the address of the next node (urm) and that of the previous one (ant), so the list can be traversed…
- Singly linked list: create, print, addLista simplu înlănțuită: creare, afișare, adăugareEvery element of the list is a dynamically allocated node (with new) that stores a value (info) and the address of the next node (urm). We keep the…
- Deleting nodes from a singly linked listȘtergerea nodurilor dintr-o listă simplu înlănțuităA list is built from n values, then all nodes containing the value x are deleted. Deleting the first node moves the pointer prim to the next node.…
- Stack implemented with a linked listStiva implementată cu o listă înlănțuităThe top of the stack is the first node of a singly linked list. push creates a new node and links it in front of the top; pop moves the top to the…
- Stack implemented with an arrayStiva implementată cu un vectorThe stack is a LIFO structure (last in, first out): elements are added and removed only at the top. With an array st and an index vf (the number of…
- Checking brackets with a stackVerificarea parantezelor cu o stivăA string made of the brackets ( ) [ ] { } is correct if every opening bracket is closed by one of the same type, in the right order. We walk the…
0%
Undirected graphs
Grafuri neorientate · 10 algorithms
- Connected componentsComponentele conexeA graph is connected if there is a path between any two nodes. A connected component is a maximal connected 'piece' of the graph. We take the nodes…
- Detecting a cycleDetectarea unui cicluA cycle is a simple path whose first node is also its last. We run a DFS traversal and keep for every node its parent (the node we came from). If…
- Shortest path between two nodes (BFS)Lanțul de lungime minimă între două noduri (BFS)The length of a path is its number of edges. Breadth-first search started from x discovers the nodes in order of their distance from x, so the first…
- Checking a bipartite graphVerificarea unui graf bipartitA graph is bipartite if its nodes can be split into two sets A and B so that every edge has one end in A and the other in B. We color the nodes with…
- Adjacency listsListele de adiacențăFor every node we store only the list of its neighbours. The edge [x, y] is added twice: y to the list of x and x to the list of y. The memory used…
- Adjacency matrix and node degreesMatricea de adiacență și gradele nodurilorAn undirected graph with n nodes and m edges can be stored in a matrix a with n rows and n columns: a[i][j] = 1 if the edge [i, j] exists, otherwise…
- Isolated nodes and the complete graphNoduri izolate și graful completAn isolated node has degree 0. A graph is complete if any two distinct nodes are joined by an edge; the complete graph with n nodes has n · (n - 1)…
- Depth-first search (DFS)Parcurgerea în adâncime (DFS)Depth-first search goes as far as it can: from the current node it moves to the first unvisited neighbour, from there to that node's first unvisited…
- Breadth-first search (BFS)Parcurgerea în lățime (BFS)Breadth-first search visits the nodes 'in layers': first the start node, then all its neighbours, then the neighbours' neighbours, and so on. We use…
- Checking a path (chain)Verificarea unui lanțA sequence of nodes x1, x2, ..., xk is a path if any two consecutive nodes are joined by an edge; the length of the path is k - 1 (the number of…
0%
Directed graphs and shortest paths
Grafuri orientate și drumuri minime · 6 algorithms
- Strongly connected componentsComponentele tare conexeA directed graph is strongly connected if for any two nodes x and y there is a path from x to y and a path from y to x. A strongly connected…
- Shortest paths from one node (Dijkstra's algorithm)Drumuri minime de la un nod (algoritmul lui Dijkstra)We want the minimum cost of the path from node s to every other node, when all arc costs are non-negative. d[s] = 0, the rest 'infinity'. At every…
- In-degrees and out-degreesGradele interne și externeIn a directed graph the edges have a direction and are called arcs: the arc (x, y) leaves x and enters y. The out-degree d+(x) is the number of arcs…
- Reachability matrix (Roy-Warshall algorithm)Matricea drumurilor (algoritmul Roy-Warshall)The reachability matrix has d[i][j] = 1 if there is a path (of length at least 1) from i to j and 0 otherwise. We start from the adjacency matrix.…
- Shortest paths between all pairs of nodes (Roy-Floyd)Drumuri minime între toate perechile de noduri (Roy-Floyd)Every arc (x, y) has a cost c ≥ 0. The cost matrix d starts with d[i][i] = 0, d[x][y] = the arc's cost and 'infinity' where there is no arc. For…
- Topological sortSortarea topologicăThe arc (x, y) means 'x must be done before y'. A topological sort is an order of all nodes in which every arc goes from left to right; it exists…
0%
Trees
Arbori · 8 algorithms
- Minimum spanning tree (Kruskal's algorithm)Arborele parțial de cost minim (algoritmul lui Kruskal)Kruskal builds the minimum spanning tree starting from n trees with a single node each. We sort the edges by cost in increasing order (on ties they…
- Minimum spanning tree (Prim's algorithm)Arborele parțial de cost minim (algoritmul lui Prim)In a connected undirected graph with edge costs we look for a spanning tree (n - 1 edges connecting all nodes) with the minimum total cost. Prim…
- Binary search tree: insert, search, sorted printArbore binar de căutare: inserare, căutare, afișare sortatăIn a binary search tree, for every node, all values in the left subtree are smaller than the node's value and those in the right subtree are larger.…
- Children, descendants and ancestors of a nodeFiii, descendenții și ascendenții unui nodThe tree is given by its parent array (t[root] = 0). The children of x are the nodes i with t[i] = x. A node y is a descendant of x if, climbing…
- Diameter of a treeDiametrul unui arboreThe diameter of a tree is the length (number of edges) of the longest path between two nodes. The two-traversal method: we run a BFS from node 1 and…
- Traversals of a binary treeParcurgerile unui arbore binarIn a binary tree every node has at most two children: a left one and a right one. We store it with the arrays st[i] and dr[i] (0 if the child is…
- Parent array: root, leaves, levels, heightVectorul de tați: rădăcină, frunze, niveluri, înălțimeA rooted tree can be stored as a parent array: t[i] is the parent of node i, and for the root t[i] = 0. The root is the node with t = 0. The leaves…
- Checking whether a graph is a treeVerificarea că un graf este arboreA tree is a connected undirected graph without cycles. For a graph with n nodes the following statements are equivalent: it is a tree; it is…