Problem Description
有一种纸牌游戏,很有意思,给你N张纸牌,一字排开,纸牌有正反两面,开始的纸牌可能是一种乱的状态(有些朝正,有些朝反),现在你需要整理这些纸牌。但是麻烦的是,每当你翻一张纸牌(由正翻到反,或者有反翻到正)时,他左右两张纸牌(最左边和最右边的纸牌,只会影响附近一张)也必须跟着翻动,现在给你一个乱的状态,问你能否把他们整理好,使得每张纸牌都正面朝上,如果可以,最少需要多少次操作。
Input
有多个case,每个case输入一行01符号串(长度不超过20),1表示反面朝上,0表示正面朝上。
Output
对于每组case,如果可以翻,输出最少需要翻动的次数,否则输出NO。
Sample Input
01 011
Sample Output
NO 1
bfs遍历全部状态
#include<queue> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int N = 1 << 20; int f[N]; char s[N]; int main() { while (~scanf("%s", s)) { int x = 0, n = strlen(s); for (int i = 0; s[i]; i++) x = (x << 1) | (s[i] - '0'); for (int i = 0; i<(1 << n); i++) f[i] = N; f[x] = 0; queue<int> p; p.push(x); while (!p.empty()) { int q = p.front(); p.pop(); if (!q) break; for (int i = 0; i < n; i++) { int y = (q ^ (1 << i - 1) ^ (1 << i + 1) ^ (1 << i))&((1 << n) - 1); if (f[y] > f[q] + 1) { f[y] = f[q] + 1; p.push(y); } } } f[0] == N ? printf("NO\n") : printf("%d\n", f[0]); } return 0; }
枚举全部操作状态
#include<queue> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; #define rep(i,j,k) for (int i = j; i <= k; i++) const int N = 1e2 + 10; char s[N]; int x, n; int main() { while (scanf("%s", &s) != EOF) { for (n = x = 0; s[n]; n++) x = x << 1 | s[n] - '0'; int ans = N; rep(i, 0, (1 << n) - 1) { if (!(((1 << n) - 1)&(x ^ i ^ (i << 1) ^ (i >> 1)))) { int res = 0; rep(j, 0, n - 1) if (i & (1 << j)) res++; ans = min(ans, res); } } if (ans < N) printf("%d\n", ans); else printf("NO\n"); } return 0; }