Basic algorithm
Copyright Notice: 9CBS is this BLOG managed service provider. If this paper involves copyright issues, 9CBS does not assume relevant responsibilities, please contact the copyright owner directly with the article Author.
Class = PostText> I. Number of algorithms
1. Seeking two maximum number of conventions
Function GCD (A, B: Integer): Integer;
Begin
IF b = 0
Then gcd: = a
Else GCD: = GCD (B, A MOD B);
END;
2. Seeking two minimum common multiple
Function LCM (A, B: Integer): Integer;
Begin
IF a
THEN SWAP (A, B);
LCM: = A;
While LCM MOD B> 0
DO INC (LCM, A);
END;
3. Justice
A. Decree a number in a small range is the number:
Function Prime (N: Integer): Boolean;
VAR i: integer;
Begin
For i: = 2 to trunc (SQRT (n))
DO
IF n mod i = 0
Then Begin
PRIME: =
False; exit;
END;
PRIME: =
True;
END;
B. Judging whether the number within the longint range is the number of prime numbers (including the number of prime tables within 500,000):
Procedure getprime;
VAR
i, j: longint;
P: array [1..50000] of boolean;
Begin
Fillchar (P, SizeOf (P),
True);
p [1]: =
False;
i: = 2;
While i <50000
Do Begin
IF P [i]
Then Begin
J: = i * 2;
While J <50000
Do Begin
p [j]: =
False;
INC (J, I);
END;
END;
INC (I);
END;
l: = 0;
For i: = 1 to 50000
DO
IF P [i]
Then Begin
INC (L); Pr [L]: = I;
END;
End; {getprime}
Function prime (x: longint): integer;
VAR i: integer;
Begin
PRIME: =
False;
For i: = 1 to L
DO
IF PR [I]> = X
Then Break
Else IF X MOD PR [I] = 0
.
PRIME: =
True;
End; {prime}
Second, the chart algorithm
1. Minimum span
A.Prim Algorithm:
Procedure Prim (V0: Integer);
VAR
Lowcost, Closest: array [1..maxn] of integer;
I, J, K, min: integer;
Begin
For i: = 1 to n
Do Begin
Lowcost [I]: = COST [V0, I];
Closest [i]: = V0;
END;
For i: = 1 to n-1
Do Begin
{Looking for the nearest point of the spangent tree K}
MIN: = Maxlongint;
For j: = 1 to n
DO
IF (Lowcost [J]
Then Begin
MIN: = lowcost [j];
K: = J;
END;
Lowcost [K]: = 0; {Add the vertex k to the spanning tree}
{Generated tree Add a new side K to Closest [K]}
{Corrected Lowcost and CloseSt value}
For j: = 1 to n
DO
IF cost [k, j] Then Begin Lowcost [J]: = COST [K, J]; Closest [J]: = K; END; END; End; {prim} B.kruskal algorithm: (greed) Remove the edges in the figure in order, if the loop is not formed, add the minimum spanning tree. Function Find (v: integer): integer; {Return to the set of vertices v} VAR i: integer; Begin I: = 1; While (i <= n) and (not V In vset [i]) Do INC (i); IF i <= n Then Find: = i Else Find: = 0; END; Procedure kruskal; VAR Tot, I, J: Integer; Begin For i: = 1 to n Do vset [I]: = [i]; {Initialization Definition N Collection, the i-th collections contain an element I} P: = N-1; Q: = 1; Tot: = 0; {p is the number of edges that is still added, Q is the edge set pointer} Sort; {Increment Sort by weight, exist in E [i], e [i] .v1 and e [i] .V2 is the serial number of the two vertices connected to the side I, E [i]. LEN is the length of the first side of the first} While P> 0 Do Begin I: = find (e [q] .v1); j: = find (e [q] .v2); IF i <> j Then Begin INC (TOT, E [q]. Len; VSET [I]: = vset [i] vset [j]; vset [j]: = []; DEC (P); END; INC; END; Writeln (Tot); END; 2. Minimum path A. The label method for solving the shortest path: VAR A: array [1..maxn, 1..maxn] of integer; B: array [1..maxn] of integer; {b [i] pointing the shortest path of the top I to the source point} Mark: array [1..maxn] of boolean; PROCEDURE BHF; VAR BEST, BEST_J: Integer; Begin Fillchar (Mark, Sizeof (Mark), FALSE); Mark [1]: = True; b [1]: = 0; {1 source point} Repeat BEST: = 0; For i: = 1 to n DO IF Mark [i] Then {point for each of the shortest paths have been calculated For j: = 1 to n DO IF (Not Mark [J]) and (a [i, j]> 0) THEN IF (BEST = 0) OR (B [i] a [i, j] Then Begin BEST: = B [i] a [i, j]; best_j: = j; END; IF best> 0 Then Begin B [Best_J]: = BEST; MARK [Best_J]: = True; END; Until Best = 0; End; {bhf} B.FLOYED algorithm solves the shortest path between all vertices: Procedure floyed; Begin For i: = 1 to n DO For j: = 1 to n DO IF a [i, j]> 0 THEN P [i, j]: = i ELSE P [I, J]: = 0; {P [i, j] represents the front discharge point of J to J on the shortest path of j Fork: = 1 to n DO {enumeration intermediate node} For i: = 1 to n DO For j: = 1 to n DO IF a [i, k] a [j, k]
Then Begin a [i, j]: = a [i, k] a [k, j]; P [I, J]: = P [k, j]; END; END; C. Dijkstra algorithm: VAR A: array [1..maxn, 1..maxn] of integer; B, pre: array [1..maxn] of integer; {pre [i] refers to the front disseval point of i on the shortest path. Mark: array [1..maxn] of boolean; Procedure Dijkstra (V0: Integer); Begin Fillchar (Mark, Sizeof (Mark), FALSE); For i: = 1 to n Do Begin D [i]: = a [v0, i]; IF D [i] <> 0 Then pre [I]: = V0 Else pre [I]: = 0; END; Mark [V0]: = True; Repeat {Add a nearest node close to 1 episodes per loop and adjust the parameters of other nodes} MIN: = Maxint; u: = 0; {u Record from 1 episode nearest node} For i: = 1 to n DO IF (Not Mark [i]) and (d [i] Then Begin u: = i; min: = d [i]; END; IF u <> 0 Then Begin Mark [u]: = True; For i: = 1 to n DO IF (Not Mark [I]) and (a [u, i] d [u] Then Begin D [i]: = a [u, i] d [u]; Pre [i]: = u; END; END; Until u = 0; END; 3. Calculate the pass closure PROCEDURE longlink; VAR T: array [1..maxn, 1..maxn] of boolean; Begin Fillchar (T, Sizeof (T), FALSE); Fork: = 1 to n DO For i: = 1 to n DO For j: = 1 to n DO T [I, J]: = T [i, j] or (t [i, k] and t [k, j]); END; 4. Non-map connected component A. Depth priority Procedure DFS (Now, Color: Integer); Begin For i: = 1 to n DO IF a [now, i] and c [i] = 0 Then Begin {dye to node i} C [I]: = Color; DFS (I, Color); END; END; B width priority (seed staining) 5. Critical Path Several definitions: The vertex 1 is the source point, n is a combo. a. Top events earliest time VE [J], VE [J] = Max {VE [J] W [i, j]}, where VE (1) = 0; b. Top events Time VL [J], VL [J] = min {VL [J] - W [i, J]}, where VL (n) = VE (N); c. The earliest start time of the event EE [i], if the side i is represented by d. The last time EL [i] is starting at the end of the event, if the side i is indicated by Solution: a. From the source point to TOPSORT, determine if there is loop and calculate the VE; b. From the exchange points to Tops, seeking VL; EE and EL; 6. Topology sort The point of finding 0 is 0, and the other side of which is connected is deleted, and the process is repeated. For example, the sum of any continuous P items is positive, any Q item and the negative, if there is no existence, output NO. 7. Logging problem Euler loop (DFS) Definition: Only one loop through each side of the figure. (Mon for conditions: Figure is connected with and not quenching) Hamilton loop Definition: The loop is only once through each vertex. A brush MA. Active condition: Figure Tong Tong and the number of odds are 0 or 2. 9. Is there a negative circuit Bellman-Ford algorithm in the figure? X [i], y [i], t [i] indicates the starting point, end point, and weight of the first edge of the clip. A total of n nodes and M strips. Procedure Bellman-ford Begin For i: = 0 to n-1 Do D [I]: = Infinitive; D [0]: = 0; For i: = 1 to n-1 DO For j: = 1 to m Do {enumeration every side} IF D [X [J]] T [J] THEN D [Y [J]]: = D [x [J]] T [J]; For i: = 1 to m DO IF D [X [J]] T [J] Then Return False Else Return True; END; 10. Nth shortest path problem * Second shortest path: Each side of the shortest path, each delete one, then ask the shortest path to the new map, take the shortest one of these paths to the second shortest path. * Similarly, the Nth shortest path can be solved on the basis of solving the N-1 shortest path. Third, backpack problem * Some backpack problems can have greedy solution: calculate PI / Wi data structure: w [i]: the weight of the i-th backpack; p [i]: The value of the i-th backpack; 1.0-1 Backpack: Each backpack can only use once or limited (convertible to once): A. Ask for maximum weight. NOIP2001 packing problem There is a box capacity of V (positive integer, o ≤ V ≤ 20000), and N items (O ≤ N ≤ 30), each item has a volume (positive integer). Requires from N items, if you have a thousand loading boxes, the remaining space of the box is minimized. l search method Procedure Search (K, V: Integer); {Searching the kth item, the remaining space is V} Var i, J: integer; Begin IF v THEN BEST: = V; IF v- (s [n] -s [k-1])> = best THEN EXIT; {s [n] is the weight and} of the previous N items. IF k <= n Then Begin IF v> w [k] THEN Search (k 1, v-w [k]); Search (k 1, v); END; END; l dp F [i, j] Select several pieces of the previous I to put it in a marker that is just J J. is a Boolean. Implementation: Transformation of optimized problems into judgment issues F [i, j] = f [i-1, j-w [i]] (w [i] <= j <= v) boundary: f [0 ,0]: = true. For i: = 1 to n DO For j: = w [i] to v Do F [i, j]: = f [i-1, j-w [i]]; Optimization: The current state is only related to the previous stage state, which can be reduced to one dimension. F [0]: = True; For i: = 1 to n Do Begin F1: = f; For j: = w [i] to v DO IF F [J-W [i]]] THEN F1 [J]: = True; F: = f1; END; B. The maximum value that can be placed. F [i, j] is the maximum value that the previous J backpack can obtain for the capacity of i. F [i, j] = max {f [i - w [j], j-1] p [j], f [i, j-1]} C. Ask the number of applications that is full. DP: Procedure Update; Var J, K: Integer; Begin C: = a; For j: = 0 to n DO IF a [j]> 0 THEN IF J now <= n THEN INC (C [J Now], A [J]); A: = C; END; 2. Repeatable backpack A seeking up to the weight can be placed. F [i, j] Select several pieces of the previous I to put it in a marker that is just J J. is a Boolean. The state transfer equation is F [i, j] = f [i-1, j - w [i] * k] (k = 1 .. J DIV W [i]) B. The maximum value that can be placed. USACO 1.2 Score Inflation Take a competition, the total time T is fixed, there are several optional questions, each of the topics can be selected, each topic has a Ti (answer the time required to answer this question) and a Si (answer this question) The resulting score), now choose a number of questions, the total number of points obtained by the total time of these questions, the maximum score obtained, and the maximum score. * It is easy to think: F [i, j] = max {f [i-k * w [j], j-1] k * p [j]} (0 <= k <= I DIV W [J]) Where F [I, J] indicates that the maximum value that the front J table backpack can achieve when the capacity is i. *achieve: Begin Fillchar (f, sizeof (f), 0); For i: = 1 to m DO For j: = 1 to n DO IF i-quobem [j] .time> = 0 THEN Begin T: = problem [j] .point f [i-quobem [j] .time]; IF T> f [i] THEN F [I]: = T; END; Writeln (f [m]); End. C. Ask the number of applications that is full. Ahoi2001 Problem2 Seeking natural number n Number of nature and the number of expressions. Idea, generate the arrangement of the coefficients of each rigidity, test in one by one, this is a form of a law. Procedure TRY (dep: integer); Var i, J: integer; Begin Cal; {This process calculates the calculation result of the current coefficient, the result is the result} IF now> n {Twilight} IF DEP = L 1 Then Begin generates all coefficient} Cal; IF now = n THEN INC (TOT); EXIT; End; for i: = 0 to n Div PR [DEP] Do Begin XS [dep]: = i; TRY (DEP 1); XS [dep]: = 0; END; END; Idea II, recursive search efficiency is high Procedure TRY (DEP, REST: INTEGER); Var i, j, x: integer; Begin IF (REST <= 0) OR (DEP = L 1) Then Begin IF rest = 0 THEN INC (TOT); EXIT; END; For i: = 0 TO REST DIV PR [DEP] DO TRY (DEP 1, REST-PR [DEP] * i); END; {main: Try (1, n);} Ideas 3: Can be solved using dynamic planning USACo1.2 Money SYSTEM V Item, the backpack capacity is n, and the total number of flasks is found. Transfer equation: Procedure Update; Var J, K: Integer; Begin C: = a; For j: = 0 to n DO IF a [j]> 0 THEN Fork: = 1 to n Div Now DO IF J Now * K <= n THEN INC (C [J Now * K], A [J]); A: = C; END; {main} Begin Read (now); {Reading the weight of the first item} I: = 0; {a [i] is the total number of} when the backpack capacity is i} While i <= n Do Begin a [i]: = 1; INC (i, now); End; {Define the weight a value of the weight of the first item is 1, as a primary value} For i: = 2 to v DO Begin Read (now); Update; {Dynamic Update} END; Writeln (a [n]); Fourth, ordering algorithm 1. Quick sort: Procedure Qsort (L, R: Integer); Var i, j, MID: Integer; Begin I: = L; J: = R; MID: = a [(1 r) Div 2]; {Define the number of the current sequence in the middle position as an intermediate number} Repeat While a [i] < MID Do INC (i); {in the left half is looking for a large number of middle numbers While a [J]> MID Do Dec (j); {{在 半 半 小 小 number} IF i <= j The begin {If you find a group of casters that are inconsistent with the sorting target, exchange them} SWAP (a [i], a [j]); INC (i); dec (j); {continuing to find} END; Until I> J; IF L Then Qsort (L, J); {If there is no boundary of the two numbers, recursive search left and right intervals} IF i THEN QSORT (i, r); End; {sort} B. Insert Sort: Idea: Current a [1] .. a [i-1] has been ranked, now inserting a [i] to make A [1] .. a [i] is orderly. Procedure insert_sort; Var i, J: integer; Begin For i: = 2 to n Do Begin a [0]: = a [i]; J: = I-1; While a [0]
Do Begin a [j 1]: = a [j]; J: = J-1; END; a [j 1]: = a [0]; END; End; {INSET_SORT} C. Select Sort: Procedure sort; Var i, J, K: Integer; Begin For i: = 1 to n-1 DO For j: = i 1 to n DO IF a [i]> a [j] THEN SWAP (a [i], a [j]); END; D. Sprinkle Procedure bubble_sort; Var i, j, k: integer; Begin For i: = 1 to n-1 DO For J: = N DOWNTO I 1 DO