ACM Learning Report
It's the end of the semester, from the winter vacation began to contact ACM to the present graph theory, already know a lot of algorithms, such as: greedy, dynamic planning, search, and graph theory, now the ACM program design This course to summarize.
The winter vacation studied STL's related content, namely the use of different containers. The container is the template that holds the data, the distance type is Queue,vector, the stack, the set,multisets, the map and so on. Vector is the most basic class model of the array, and there are 4 kinds of vector's constructor function.
1. The default constructor constructs an empty vector with an initial length of 0, such as vector<int> v1 most commonly applied
2. A constructor with a single integer parameter that describes the initial size of the vector.
3. Copy the constructor and construct a new vector as a copy of the existing vector.
4. Hit the constructor of the two constant parameter to produce a vector of the interval.
Map and Multimap
Map is a mapping container, consisting of a key value and a mapping data. The data structure in map is implemented by red-black tree, the key value of the inserted element is not allowed to be duplicated, and the data of the element can be retrieved by the key value. If you need to use a pair to store the data, the map is a good choice. The collection is faster than a vector on the insert and delete operations, which is to find or add the element at the end is slower.
Multimap is basically the same as map, except that Multimap allows the insertion of duplicate key-value elements. Because the existence of duplicate key values is allowed, multimap element insertions, deletions, and lookups are different from map. The Map and multimap the search time compared to the traversal when processing the data search.
Set and multiset template parameters:
Template<class key, class compare, class allocator=allocator>
The first argument key is the type of the key that is stored, the second parameter is the type of the comparison function that is defined for the sorted value, and the third parameter is the type of the implemented storage-specifier.
Mappings and multiple mappings:
Mapping and multi-mapping are based on the existence of key, providing fast and high-speed retrieval of data of type T.
The first algorithm to study this semester is the greedy algorithm. Greedy algorithm is to find out the optimal solution of the current state, my personal understanding is to separate a big problem, divide a big problem into small problems, and then find the optimal solution of each small problem, then the optimal solution of the small problem is the optimal solution of the big problem. The whole greedy algorithm has no fixed idea, just chooses a suitable greedy strategy in each problem, and uses the greedy strategy to solve a problem.
Remember the first to push the table, think of a half-day or a simulation method to solve the problem, how to think can not think how a greedy method, when seen more than 40 lines of greedy algorithm solution, feel very shocked. At first, because last semester selected 4 courses =, this semester required more, the first few weeks only one afternoon is empty, feel there is not enough time to study the algorithm, the first seven weeks of life is not as good as death ...
The greedy algorithm involves three types of questions: knapsack problem, interval problem and Huffman tree problem.
One of the knapsack problem is the teacher said the most, knapsack problem is a classic one is to put things in the backpack, just to meet the current maximum benefit of the selection of good. Feel some knapsack problem is quite simple, rare also not AH =.
The second chapter after the greedy algorithm is deep search and breadth search.
Depth-First search: Deep limited Search is in the search tree each layer is always first to expand only a child node, the continuous depth of the network to know that can not continue to position, if the node is not, only from the current node to return to the previous level node, along the other point to search for results. Simple understanding is to start from the point of the accident, continue to go deep, if you can not continue to move back one step, try another road, until the target location. This approach, even if successful, does not necessarily find the optimal path, but the advantage is that there are fewer places to remember.
Breadth-First search:
In depth-first search, nodes with a greater depth are searched first. If the algorithm in the search to the level of the node to search, the node of this layer does not have a search complete, the lower node can not be processed, that is, the smaller the depth of the node is expanded first, that is, the first search node can be searched first, this search method for breadth-first search. Breadth first is starting from the initial point, all the possible paths to go once, if there is no target location, then all can go to the location, to see if there is no target location, if not, then try all 3 steps can reach the location. In this way, you can find a shortest path.
In the meantime we are using the dichotomy method to find the values that apply to the approximation of the monotone function to solve a point. If the concave or convex function is encountered, the dichotomy method is not very practical, so it is necessary to use the 3-point method to find the concave or convex points to achieve the goal of extremum. Practice: Set the range to [L,r], First take [L,r] midpoint Mid, then take [mid,r] midpoint mmid, by comparing F (mid) and F (mmid) size to narrow the range. When the last l=r-1, compare the values of these two points, we find the answer.
1, when F (mid) > F (mmid), we can conclude that mmid must be on the right side of the white point.
Mmid: Assuming that the left side of the white point, mid also must be on the left side of the white point, and by F (mid) > F (mmid) can be introduced Mmid < Mid, with known contradictions, it is assumed that is not established.
Therefore, you can narrow the range by R = Mmid.
2, when F (mid) < F (mmid), we can conclude that the mid must be on the left side of the white point.
To disprove: If the mid is on the right side of the white point, then Mmid must also be on the right side of the white point, and by F (mid) < F (Mmid) can launch mid > Mmid, with known contradictions, it is assumed not to be established. In the same vein, L = Mid can be reduced by this time.
Basic concepts of graphs:
Figure: Two-tuple <V,E> called graph. V is the node (node) point (vertex) set. E is the set of edges between nodes in the diagram.
Simple diagram
Ring: The edge of the endpoint coincident to a point.
Heavy edges: Two edges connect the same pair of vertices.
Simple diagram: graphs without loops and heavy edges.
Non-direction and forward graphs
If the edges are bidirectional, then the graph is called a non-directional graph.
If the edges are unidirectional, the graph is called a directional graph.
Connectivity of
In undirected graphs, if there is a path between the two vertices, the two vertices are said to be connected.
In a direction graph, if there is a path between the two vertices, they are said to be strongly connected.
If any of the two vertices of a graph are connected, the graph is said to be connected.
The degree of the vertex
In a graph, the number of edges connected by a vertex is called the degree of that vertex.
In a forward graph, the number of edges from one vertex is called the vertex, and the number of sides to the vertex is called its degree of penetration.
The maximum degree of a vertex is called the degree of the graph.
Road and Circuit
A sequence of vertices and edges that joins two vertices is called a road. Except for the start and end vertices, the other vertices are not the same, which is called a simple path. A simple path with the same starting and terminating vertices is called a circle.
The basic idea of prim algorithm:
Add a single point to the spanning tree. In those one power outage in the spanning tree, the other end point no longer builds the tree, the other end point no longer generates the edges in the tree, to persuade the smallest side, and add him and the other endpoint into the spanning tree.
Repeat the previous step until all the vertices have entered the spanning tree.
The basic idea of Kruskal algorithm:
To all sides from small to large order
A temptation joins the edge and his endpoint into the spanning tree, and if no circle is added to the edge, the edge is added to the spanning tree by his endpoint; Knowing that there is a n-1 edge in the spanning tree, it terminates. The time complexity of the algorithm needs to be considered.
Dijkstra algorithm
Basic idea: Set up a set of s to hold the vertices that have found the shortest path, the initial state of S contains only the source point V, to the vi∈v-s, assuming the forward edge from the source point V to VI is the shortest path. Each subsequent to a shortest path V, ..., VK, will be VK into the collection s, and the path V, ..., VK, vi compared with the original hypothesis, the shortest path length is taken. Repeat the process until all vertices in the set V are joined to the set S.
Design Data Structures:
storage structure of graphs: adjacency matrix storage structure with weights
array Dist[n]: each component Dist[i] represents the length of the shortest path that is currently found from the start point V to the endpoint VI. The initial state is: if there is an arc from V to VI, then dist[i] is the right value of the arc, otherwise the dist[i] is ∞.
array Path[n]:path[i] is a string that represents the shortest path from the starting point V to the endpoint VI that is currently found. The initial state is: if the arc from V to VI, then path[i] is vvi; otherwise path[i] empty string.
array S[n]: stores the source point and the resulting end point, which is initially configured to have only one source Point v.
Pseudo code
1. Initialize the array dist, path, and S;
2. While (number of elements in S <n)
2.1 in Dist[n] to find the minimum value, its subscript is k;
2.2 Output DIST[J] and path[j];
2.3 Modifying the array dist and path;
2.4 Add the vertex VK to the array s;
Limitations
Dijkstra's flaw is that it cannot handle negative-weight loops: Dijkstra no longer updates the marked points, so even a negative right causes the shortest distance change to recalculate the calculated results.
Graph Algorithm :
Tree definition and basic terminology: a tree is a finite set of n (n≥0) nodes. If n = 0, it is called
is an empty tree, and if n > 0, it satisfies the following two conditions:
(1) There is only one specific node called root (Root);
(2) The remaining nodes can be divided into m (m≥0) non-intersecting finite sets.
T1, T2,t3, ..., Tm, each of which is itself a tree, and called the root of the subtree (subtree).
Diagram definition and basic terminology: graph (graph) is a complex nonlinear data structure consisting of a collection of vertices and a set of relationships (also called arcs or edges) between vertex sets and vertices. Can be expressed as:
G= (V, {VR})
Where V is a poor non-empty set of vertices, and VR is a poor set of relationships between vertices, also called arcs or edge sets. Arcs are ordered pairs of vertices, and edges are unordered pairs of vertices.
How to store graphs --adjacency matrices: adjacency matrix Use Cases
1. Data size is small n <= 1000,m the bigger the better
2. Dense graphs preferably with adjacency matrices
3. No multiple edges appear in the diagram
How to store graphs -adjacency table:
Adjacency Table Use Occasions
1. The number of vertices is many n>1000, but the number of sides is not many.
2. The complexity of many algorithms is also related to the number of edges when the adjacency table is used for storage.
3. Connectivity problems in many cases, the number of edges is not many, and the adjacency table is used to store
and look up the episode: 1. Mark the set of the element with the smallest number, define an array n], where Set[i] represents the set where element I resides;
2. Each set is represented by a "rooted tree"
Define Array SET[1..N]
Set[i] = i, then I represents this collection, and is the root of the collection corresponding tree
Set[i] = j, J<>i, then J is the parent node of I.
Avoid worst case scenarios
1. Method: Merge a small depth tree into a tree with a large depth
2. Implementation: Assuming that the depth of the two trees is H1 and H2 respectively, then the height of the merged tree H is:
Max (H1,H2), if H1<>h2.
H1+1, if H1=h2.
Effect: After any sequence of merge operations, the maximum height of a tree containing K nodes does not exceed
Path compression:
1. Thought: Each time the search, if the path is longer, then modify the information so that the next time you find faster
2. Steps:
The first step is to find the root node.
The second step is to modify all nodes on the lookup path to point to the root node.
Dynamic planning
In the multi-stage decision-making process, the problem can be decomposed into several interrelated stages in chronological order, making decision at each stage, and all decision-making is a general decision sequence. Decisions need to be made at each stage to achieve the best possible results for the entire process.
The optimal combinatorial problem of dynamic programming has the following characteristics:
Optimal substructure : The optimal solution of a problem consists of the solution of a sub-problem, which is also optimal for a pair problem.
Sub-problem overlap: a recursive algorithm of the problem is not new when each recursive step produces branching sub-problem, but the relative part of the problem is solved and solved. When a recursive algorithm accesses the same sub-problem again and again, we say that the problem has the characteristics of overlapping sub-problems.
The dynamic programming algorithm usually does the following 3 steps:
An optimal substructure is used to define a recursive equation for the target value of a section. Dynamic planning is a bottom-up solution to each newly created sub-problem and saves it in a table, finds it in a table when needed, and can complete the search within Changshu time. The corresponding optimal solution is constructed according to the value of the calculated optimal solution.
The knapsack problem dynamic programming solution, the most basic knapsack question, the characteristic is: each kind of item only one piece, may choose to put or not to put.
Basic ideas
define the state with a sub-question: F[i][v] Indicates the maximum value that a backpack of the first I item can get into a container of V. The state transfer equation is:
F[i][v]=max{f[i-1][v],f[i-1][v-c[i]]+w[i]}
"Put the first I item into a backpack with a capacity of V" This sub-problem, if only consider the strategy of article I items (put or may wish), then can be converted into a 1 items involved in the first I-problem. If you do not put the article I item, then the problem is converted to "the first I-1 items into the remaining capacity of v-c[i] backpack", at this time can obtain the maximum value is f[i-1][v-c[i]], plus by putting in the value of the item I get w[i].
Initializing detail issues
There are two different ways to ask questions about the knapsack problem of finding the best solution. Some topics require "just fill the backpack" when the optimal solution, and some of the problems are not required to fill the backpack. One difference is that the method of red thread of the two methods is somewhat different at the time of initial initialization.
If the first method of asking is to fill a backpack, then at the time of initialization except F[0] is 0 other F "1.v" are-∞, so that the final f[n] is an exact full pack of the best solution. If it is not required to fill the backpack, just hope that the price as large as possible, the initialization should be f[o. V] all set to 0.
It can be understood that the initialized F-array is in fact the legal state when no item can be placed in the backpack. If the backpack is full, then only the capacity of 0 of the backpack may be worth 0 of nothing "just full", the other capacity of the backpack are not legal solution, plague undefined state, their value should be-∞, if the backpack is not to be filled, then any capacity of the backpack has a legal solution " The value of this solution is 0, so the value of the state at the time of the accident is all 0. This technique can be generalized to other types of knapsack problems, and it is no longer possible to explain the initialization before state transfer.
Define interval DP:
The problem of interval dynamic programming is to be considered, and their optimal values are the best worth of the extremely smaller interval, which is a kind of dividing thought, dividing an interval problem into a smaller interval until an interval of an element enumerates their combinations, seeking the optimal value after merging.
Set f[i,j]=0
Each time a variable K (i<=k<=j-1) is used to divide the interval into [i,k] and [k+1,j] two segments
For P:=1 to n do//p is the interval length, as a stage.
For I:=1 to n do//i is the beginning of the exhaustive range
Begin
J:i+p-1;//J is the end of the interval so that all the intervals are exhausted.
If J>n then break;//this if is critical.
For K:=i to J-1 do//State transfer, go to launch f[i,j]
F[I,J]=MAX{F[I,K]+F[K+1,J]+W[I,J]}
End;
The above is my ACM summary.
ACM Learning Report