题目链接:POJ 1176
题意:
对于一串彩灯,提供四种改变彩灯状态(ON<=>OFF)的操作:a.改变所有彩灯状态;b.改变奇数彩灯状态;c.改变偶数彩灯状态;d.改变3k+1号彩灯状态(1,4,7,10...)。
给定彩灯数目,操作次数,和对于某几个彩灯必须为ON、某几个彩灯必须为OFF的要求,问经过给定次数的操作,最终能达到的满足要求的状态有多少种,输出所有满足要求的彩灯状态(按二进制字符升序输出)。
CODE:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <stack>
#include <queue>
#include <algorithm>
#include <cmath>using namespace std;const int maxn = 110;char s[maxn*10][maxn];
int N, C, ontot, offtot, on[maxn], off[maxn], t, tot;
bool a[maxn];//a[i]=true:on a[i]=false:off
int vis[maxn*10];int valid()
{for (int i = 0; i < ontot; i++)if (a[on[i]] == false) return 0;for (int i = 0; i < offtot; i++)if (a[off[i]] == true) return 0;return 1;
}void dfs(int k)
{if (k > C) return;if (k == C) {if (valid()) {s[tot][0] = '0';for (int i = 1; i <= N; i++) {if (a[i]) s[tot][i] = '1';else s[tot][i] = '0';}s[tot][N + 1] = '\0';tot++;}}else {for (int i = 1; i <= 4; i++) {if (i == 1) {for (int j = 1; j <= N; j++)a[j] = !a[j];dfs(k + 1);for (int j = 1; j <= N; j++)a[j] = !a[j];}else if(i == 2) {for (int j = 1; j <= N; j += 2)a[j] = !a[j];dfs(k + 1);for (int j = 1; j <= N; j += 2)a[j] = !a[j];}else if (i == 3) {for (int j = 2; j <= N; j += 2)a[j] = !a[j];dfs(k + 1);for (int j = 2; j <= N; j += 2)a[j] = !a[j];}else {for (int j = 1; j <= N; j += 3)a[j] = !a[j];dfs(k + 1);for (int j = 1; j <= N; j += 3)a[j] = !a[j];}}}
}int main()
{
#ifdef LOCALfreopen("in.txt", "r", stdin);//freopen("out.txt", "w", stdout);
#endif while (~scanf("%d%d", &N, &C)) {if (C > 4) {//700K 16MSC = C % 4 ;}/*if (C>4)//700K 0MS{C %= 2;if (C == 1) C = 3;else C = 4;}*/for (int i = 1; i <= N; i++)a[i] = true;ontot = offtot = tot= 0;while (1) {scanf("%d", &t);if (t == -1) break;on[ontot++] = t;}while (1) {scanf("%d", &t);if (t == -1) break;off[offtot++] = t;}dfs(0);//排序for (int i = 0; i < tot; i++) {int k = i;for (int j = i + 1; j < tot; j++) {if (strcmp(s[j]+1, s[k]+1) < 0) k = j;}if (k != i) {char tmp[maxn];strcpy(tmp, s[i]);strcpy(s[i], s[k]);strcpy(s[k], tmp);}}//标记重复memset(vis, 0, sizeof(vis));for (int i = 0; i < tot; i++) {if (vis[i]) continue;for (int j = i + 1; j < tot; j++) {if (strcmp(s[i], s[j]) == 0) vis[j] = 1;//else break;}}for (int i = 0; i < tot; i++) {if (!vis[i]) {//for (int j = 1; j <= N; j++)// putchar(s[i][j]);//printf("\n");puts(s[i] + 1);}}}return 0;
}