Problem solving with programming: Minimum number of symbols to change to make a chain
http://www.codechef.com/FEB15/problems/CHEFCH
http://www.codechef.com/FEB15/problems/CHEFCH
Given a string containing the only symbols '+' or '-', how do we find the minimum number of changes to transform it to a chain. A chain of length N is the sequence of alternative + and - symbols.
For example "+-+-+" is a chain of length 5.
Similarly "-+-+-+" is a chain of length 6.
Input: 2 ---+-+-+++ ------- Output: 2 3
Explanation
Example case 1.
We can change symbol 2 from '-' to '+' and symbol 9 from '+' to '-' and receive '-+-+-+-+-+'.
Example case 2.
We can change symbols 2, 4 and 6 from '-' to '+' and receive '-+-+-+-'.
Given the length of the sequence N, there are only two possible chains; One starting with - (-+-+....), and the other starting with + (+-+....).
So it is just enough to compare the input string to these two patterns and find the number of changes to make it a chain. Minimum of these two numbers gives us the answer.
For an example consider the input
+--++
Difference with +-+-+ is 2
Difference with -+-+- is 3
So the minimum number of changes to make it a chain is 2.
Read full article from Problem solving with programming: Minimum number of symbols to change to make a chainwhile(t--){string input;cin >> input;int i, result = 0, result1 = 0;char p1 = '+', p2 = '-';for( i = 0; i < input.size(); i++ ){if( input[i] != p1 )result++;if( input[i] != p2 )result1++;p1 = (p1 == '+')? '-':'+';p2 = (p2 == '+')? '-':'+';}cout << min(result,result1) << endl;}