费解的开关
先枚举第一行所有情况,接下来四行根据前一行来应用。其实就是枚举状态空间。
#include <iostream>
#include <cstdio>
#include <cstring>using namespace std;
const int N = 7;
const int INF = 0x3f3f3f3f;int g[N][N], backup[N][N];void click(int x, int y)
{g[ x ][ y ] ^= 1;g[x - 1][ y ] ^= 1;g[x + 1][ y ] ^= 1;g[ x ][y - 1] ^= 1;g[ x ][y + 1] ^= 1;
}int main()
{int T; cin >> T;while (T--){char c;for (int i = 1; i <= 5; i++)for (int j = 1; j <= 5; j++){cin >> c;g[i][j] = c - '0';}int ans = INF;/* click */for (int k = 0; k < (1 << 5); k++){int res = 0;memcpy(backup, g, sizeof g);/* first line */for (int j = 0; j < 5; j++){if (k >> j & 1){res++;click(1, j + 1);}}/* other line */for (int i = 2; i <= 5; i++){for (int j = 1; j <= 5; j++){if (!g[i - 1][j]){click(i, j);res++;}}}/* check last line */bool is_success = true;for (int j = 1; j <= 5; j++){if (!g[5][j]){is_success = false;break;}}/* get min ans */if (is_success && res <= 6) ans = min(ans, res);memcpy(g, backup, sizeof g);}if (ans != INF) cout << ans << endl;else puts("-1");}return 0;
}
[类似]飞行员兄弟
只是将灯泡影响范围变大。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>using namespace std;
typedef pair<int, int> PII;
const int N = 6;
const int INF = 0x3f3f3f3f;int g[N][N], backup[N][N];
vector<PII> ans;void click(int x, int y)
{for (int i = 1; i <= 4; i++) g[x][i] ^= 1;for (int i = 1; i <= 4; i++) g[i][y] ^= 1;g[x][y] ^= 1; // NOTICE HERE!!!!
}bool check()
{for (int i = 1; i <= 4; i++)for (int j = 1; j <= 4; j++)if (!g[i][j])return false;return true;
}int main()
{char c;for (int i = 1; i <= 4; i++)for (int j = 1; j <= 4; j++){cin >> c;g[i][j] = (c == '-') ? 1 : 0;}memcpy(backup, g, sizeof g);/* permutation */for (int k = 0; k < (1 << 16); k++){/* start */vector<PII> res;/* click */for (int i = 0; i < 16; i++){if (k >> i & 1){int x = i / 4 + 1;int y = i % 4 + 1;click(x, y);res.push_back({ x, y });}}/* better answer */if (check() && (res.size() < ans.size() || ans.empty()))ans = res;/* end */memcpy(g, backup, sizeof g);}cout << ans.size() << endl;for (auto item : ans) printf("%d %d\n", item.first, item.second);return 0;
}