Uva11127-triple-free binary strings (DFS + bit operation)

Source: Internet
Author: User

Question Link


Question:A string with the length of N is given. The string consists of '1', '0 ','*', Wherein '*'Can be replaced with '1', '0' at will to find the maximum number of strings without three consecutive substrings.

Ideas:We can use binary to represent strings for DFS. The Left shift of bitwise operations indicates that '1' is placed on the '*' position. Note that three consecutive identical substrings exist in the recursion process.

Code:

# Include <iostream> # include <cstdio> # include <cstring> # include <algorithm> using namespace STD; const int maxn = 32; char STR [maxn]; int N, ans; bool judge (int s, int d) {int K = (1 <D)-1; int A = S & K; S = s> D; int B = S & K; S = s> D; int c = S & K; if (a = B & B = c) Return true; else return false;} // use the bitwise operation to shift the D bit to the right to determine whether three substrings are the same void DFS (int s, int CNT) {int num = CNT/3; int t = n-CNT-1; for (INT I = 1; I <= num; I ++) {If (Judge (S> (t + 1 ), i) return;} If (CNT = N) {ans ++; return;} else if (STR [CNT] = '0') {DFS (S, CNT + 1);} else if (STR [CNT] = '1') {DFS (S + (1 <t), CNT + 1 );} else if (STR [CNT] = '*') {DFS (S, CNT + 1); DFS (S + (1 <t), CNT + 1 );} return;} int main () {int CAS = 1; while (scanf ("% d", & N) {scanf ("% s", STR ); ans = 0; DFS (0, 0); printf ("case % d: % d \ n", CAS ++, ANS);} return 0 ;}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.