Divide and conquer algorithm for the matching problem of screw and nut

Divide and conquer algorithm for the matching problem of screw and nut

1. Problem description:

There are a screw of different sizes and n nuts that match it. You can try whether a screw and a nut match. There are three results: (1) the screw is too large; (2) the match is successful; (3) the nut is too large . Please design a divide and conquer algorithm to complete the matching of all screws and nuts

2. Algorithm solution:

1. Algorithm idea:

Boundary condition : When there is only one screw and one nut, match the screw and nut.

Divide : Randomly select a screw x from the cup set, match x with all nuts, put the nut with too large screw into G1, put the nut with too large nut into G2, and find the one that matches x successfully The nut is denoted as y. Match all cups except y and x, put the screw whose nut is too large into B1, and put the screw whose matching result is that the screw is too large into B2.

Conquer : Recursively match B1 and G1, B2 and G2.

Merge : Return the matching results of B1 and G1, B2 and G2 and (x, y).

2. Algorithm pseudo code:

Match(B, G)
Input: Screw set B, nut set G, |B|=|G|=n, each screw in B matches only one nut in G
Output: ((x, y)| x ∈B, y∈G, x and y match successfully}

  1. if |B|=1
  2. return BG;
  3. Initialize B1, B2, G1, G2, M=; y=NIL;
  4. Randomly select an element x in the screw set B;
  5. for G
  6. The matching result of if g and x is "the screw is too big"
  7. Let G1=G1{g};
  8. else if g and x match the result as "nut is too big"
  9. G2=G2{g};
  10. else {
  11. y=g;
  12. M=M{(x, y)};
  13. }
  14. for B/{x}
  15. The matching result of if y and b is "nut too large"
  16. B1=B1{b};
  17. else if g and x match the result as "the screw is too big"
  18. B2=B2{b};
  19. if B1
  20. M=MMatch(B1, G1);
  21. if B2
  22. M=MMatch(B2, G2);
  23. return M;

3. Analysis of algorithm time complexity:

Remember the algorithm time complexity T(n). The cost of matching x with all nuts is O(n); the cost of matching y with all nuts except x is O(n); In summary, the division cost is O(n). The cost of Conquer is T(|B1|)+T(n-1-|B1|), where the probability that |B1| is 0, 1,..., n-1 is 1/n. Combine (Merge) does not count the cost (the time complexity of the algorithm is measured by the number of matching attempts). The overall cost is the same as that of quicksort, the worst case is O(n2); the expectation is O(nlogn).

Guess you like

Origin blog.csdn.net/weixin_43824348/article/details/110264619