uva 11127 - Triple-Free Binary Strings(回溯)

来源:互联网 发布:百度地图城市数据库 编辑:程序博客网 时间:2024/05/17 04:06

题目链接:uva 11127 - Triple-Free Binary Strings


题目大意:给出一个串,有0,1,*,然后*的位置可以填0或1,问组成的串中不存在连续三个子串相同的串的个数。


解题思路:递归求解,可以剪枝对与当前位置,如果前面的构成已经有存在连续的三个子串相同,可以直接return。


#include <stdio.h>#include <string.h>const int N = 50;int n;char tmp[N];bool judge(int s, int d) {int t = (1<<d) - 1;int a = s & t;s = s>>d;int b = s & t;s = s>>d;int c = s & t;return a == b && b == c;}int dfs(int s, int d) {int k = d / 3, t = n-d-1;for (int i = 1; i <= k; i++) {if (judge(s>>(t+1), i)) return 0;}if (d == n) {return 1;} else if (tmp[d] == '0') {return dfs(s, d + 1);} else if (tmp[d] == '1') {return dfs(s+(1<<t), d + 1);} else {return dfs(s+(1<<t), d + 1) + dfs(s, d + 1);}}int main() {int cas = 1;while (scanf("%d", &n) == 1 && n) {scanf("%s", tmp);printf("Case %d: %d\n", cas++, dfs(0, 0));}return 0;}


2 0