Magical Planks
Ryan is a boy from, who has been given a task by his father. He has
wooden planks, numbered from to , which are colored either black or white.
His task is to color all planks the same color! But there is some magic in the winds of his small town. Whenever he colors the ( plank which has the color ) to a color then following events happen:
- if and , then color of plank changes to .
- if and , then color of plank changes to .
Now this process continues for the newly colored planks also. If none of the neighbors have same color, then nothing happens to the neighbors.
Suppose Ryan has planks which have their coloring : If Ryan colors the fourth plank( whose color is ) to color , then the finally the planks would be colored as following:
Ryan can choose any one of the planks and change its color as many times as he wants. Determine the minimum number of times Ryan has to paint a plank such that all planks get the same color at the end.
Input Format
- First line will contain , number of testcases. Then the testcases follow.
- The first line of each test case consists of an integer the number of planks
- Second line of each test case consists of a string of size ,where the th character denotes the color of plank
Output Format
For each testcase, output a single integer denoting the minimum number of times Ryan has to paint a single plank such that all planks get the same color at the end.
Constraints
- consists only of characters and
- The sum of over all cases doesn't exceed .
Sample Input 1
4
6
BBWWWB
5
WWBWB
2
BB
9
WWBBBBBWW
Sample Output 1
1
2
0
1
Explanation
Test case 1: The first test case is already described in the question.
Test case 2: Ryan can paint the third plank to . After doing so the color string of planks become . Then he can again paint the third plank to the color . After doing so the string goes through following transitions:
- The color of third plank changes to . ( The string becomes )
- The color of second and fourth plank changes to . ( The string becomes )
- The color of first plank changes to . ( The string becomes )
Finally, all planks have same color.
Test case 3: All planks have the same color.
Test case 4: Ryan can paint any of the planks numbered from to to , and all these planks will be colored to !
Code:
#include <bits/stdc++.h>
using namespace std;
int main() {
// your code goes here
int t,n;
cin>>t;
while(t--){
cin>>n;
string s; cin>>s;int temp = 0;
int answer =0;
for(int i=0;i<n;i++){
if(s[i] == 'W'){
int j=i+1;
while(j<n && s[j] == s[i]) j++;
temp +=j;
}
else if(i>0 && s[i] != s[i-1]){
answer++;
int k = i + 1;
while(k<n && s[k] == s[i]) k++;
temp+=k;
}
else{
int k = i + 1;
while(k<n && s[k] == s[i]) k++;
temp+=k;
}
}
if(temp) cout<<answer<<endl;
else cout<<0<<endl;
}
}
bhai code galat aa rha hai multiple cases me
ReplyDeletesame bro
Delete