This problem’s main point is each second a boy will let every girl swap positions if a girl is behind the boy. This happens for all the girls and boys who meet the same condition.
Sample Input:
5 1
BGBGB
Here, if you look at sample input you will see a single string containing only ‘B’ or ‘G’ letters denoting boy and girl respectively, where the sequence of the whole string represents the line containing boys and girls int the line/queue at a certain time.
The first integer represents the number of children ( in this case string size ) and the 2nd integer represents seconds that will pass.
Steps to solve:
- First, we will take two integers as asked in the problem. (number of children and passable time).
- After inputting them we will declare a string whose length will be the 1st inputted integer to create the line of students as a string.
- Then, we will call a loop until we pass all iterations of the second Input integer so that we can do operations of swapping boys and girls for the given seconds. (line 8 of code )
- Now we will loop through all the index of the input string ( boys, girls queue representation ) to check if current_index = ‘B’ and next_index = ‘G’.
- If the previous comparison is correct we will swap current_index and next_index values. ( Boys exchanging position with girls if the girl is behind ). (line 10 – 12 of code)
- Then increment the loop iterator by 2 because we had done work with two indexes and we don,t need to do anything u til next second. (line 13 of code)
- Else if the comparison didn’t match we will increment the loop iterator only by one so we can check the next index.
- After the looping process is done just print the string to show the changed output.
Solutions of Codeforces 226b in C/C++
#include<bits/stdc++.h> int main() { int x,y; scanf("%d%d",&x,&y); char str[x],tmp; scanf(" %s",str); int len = strlen(str); while(y--) { for(int i = 0; i<len-1;) { if(str[i]=='B' && str[i+1]=='G') { tmp = str[i]; str[i] = str[i+1]; str[i+1] = tmp; i+=2; }else{ i++; } } } printf("%s\n",str); return 0; }
Click to rate this post!
[Total: 4 Average: 5]