The problem is seen on the http://baijiahao.baidu.com/s?id=1572912276737234&wfr=spider&for=pc, because the code is written more beautiful, so this record, you can read it later. Problem Description:
Boys and girls standing in the procession, the boy with symbol B said, the girl with the symbol G, we want to adjust the team for boys on one side of the girl, and can only be adjacent to the location of the boys or girls swap positions, for the exchange of the least number of times to exchange.
GGBBG (initial) GGBGB (swap) gggbb (swap two times, and meet the requirements). The result of this return is 2. idea:
First of all, people only ask to find the number of times, does not require the realization of exchange.
Obviously we have to consider whether the boys on the left or the girls on the left, such as GGGGBBBG, this is obviously the number of girls on the left side of the exchange will be less. And BBBBGGB is obviously boys on the left of the exchange less often, so we all need to consider, and finally take a small value.
RESG and Resb are used to record the number of exchanges between girls on the left and boys on the left. And whether it's a boy or a girl if they want to implement on the left side, you have to look at the number of people that are already lined up, because you can only exchange adjacent positions. Lg,lb for girls and boys on the left row position, initially 0. Code:
parsing:
For example GGBBG, if the girl on the left, 0 places do not have to exchange, res=0 satisfied, lg++, because the No. 0 position has been lined up, the same thing if the boys to the left, you get position 2, find position 2 Exchange to position 0, need to exchange 2 times, resb=2,lb++, Because if a guy wants to switch to the left, position 0 is already lined up.
Position 1 girls in exchange to the left, there is no need to go to the left, because position 0 is already a girl. So because of itself in position 1 out, exchange for 0,lg++ after 2. The same is true of the boys on the next position 3, as long as the exchange to position 1 can be completed after the Exchange lb++.
It can be seen that no matter the number of exchanges, will make the position of the right movement, using this indicator to measure the number of girls or boys exchange over.
We ended up looking at the girl at the end of the line, and she might have to trade if she wanted to find her partner.
Position 4 girl found that there are already two girls on the left to wait for her, she only needs to switch to position 2, with the current position of 4-2 is the number of exchanges, the final result resg=2.
Note here, because the lg,lb are all starting from 0. It records how many people have met the requirements, and the next person we want to switch to is just going to switch to the next location, so, since 0, the next location is LG, or LB.
This article only represents the author's point of view, does not represent Baidu position. The author authorizes the publication of the Hundred numbers