Train of Thought: DFS + backtracking
[Cpp]
# Include <stdio. h>
# Include <string. h>
# Define INF 1 <30
Int a [25], cnt [25];
Int ans, temp, len;
Bool myok ()
{
Int I;
For (I = 0; I <len; I ++)
If (a [I]) return false;
Return true;
}
Void dfs (int idx)
{
Int I;
If (myok () // determines whether there are cards on the opposite side. if there are cards on the opposite side, continue to flip the cards. if not, count them.
{
Temp = 0;
For (I = 0; I <len; I ++)
If (cnt [I] = 1) temp ++;
If (temp <ans)
Ans = temp;
Return;
}
If (idx> = len) return; // the return value is required when the last one is searched.
For (cnt [idx] = 0; cnt [idx] <2 ;)
{
A [idx] ^ = 1; // flop
If (idx> 0) a [idx-1] ^ = 1; // Flip left
If (idx <len) a [idx + 1] ^ = 1; // flip the right
Cnt [idx] ++;
Dfs (idx + 1 );
}
}
Int main ()
{
Int I;
Char ch [25];
While (~ Scanf ("% s", ch ))
{
Len = strlen (ch );
For (I = 0; I <len; I ++)
A [I] = ch [I]-'0 ';
Ans = INF;
Memset (cnt, 0, sizeof (cnt ));
Dfs (0 );
If (ans! = INF) printf ("% d \ n", ans );
Else printf ("NO \ n ");
}
Return 0;
}