In the ant climbing algorithm, only the time for the ant to exit is obtained, but the time for each ant to exit is not obtained. There is no fixed algorithm here. The Code is as follows:
# Include <iostream> Using STD: cout; Using STD: Endl; Using STD: swap; int left [29]; int right [29]; void fun () // first, determine whether the two ants are in the same position. If the two ants are in the same position, switch the direction of the two ants {for (INT I = 1; I! = 29; ++ I) if (left [I] & right [I]) Swap (left [I], right [I]);} void F () // determine whether to pass by. After passing by, exchange the order between the two ants {for (INT I = 1; I! = 29; ++ I) if (left [I] & right [I + 1]) {// swap (left [I], right [I]); // The comments are incorrect. // swap (left [I + 1], right [I + 1]); // swap (left [I], right [I + 1]); // correct switching method} void move () {for (INT I = 1; I! = 29; ++ I) {left [I-1] = left [I]; right [29-I] = right [29-1-I];} int main () {right [3] = 1; right [11] = 2; left [7] = 3; left [17] = 4; left [23] = 5; // right [5] = 1; // left [6] = 2; int COUNT = 0; For (INT I = 1; count! = 5; ++ I) {fun (); move (); F (); If (left [0] & ++ count) cout <left [0] <"No. Ant crawls out of \ n in the second" <I <"; if (right [28] & ++ count) cout <right [28] <"No. Ant crawls out of \ n" in seconds <I <";} return 0 ;}
The Code uses a simulation method to count the time when each ant goes out. If you only calculate the time when it goes out without considering which ant is, you can use the method in the book "The beauty of programming.