数组写法
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#define x first
#define y second
using namespace std;
typedef pair<int, int> PII;
const int N = 5;
char g[N][N], backup[N][N];
int get(int x, int y)
{
return x * 4 + y;
}
void turn_one(int x, int y)
{
if (g[x][y] == '+') g[x][y] = '-';
else g[x][y] = '+';
}
void turn_all(int x, int y)
{
for (int i = 0; i < 4; i ++ )
{
turn_one(x, i);
turn_one(i, y);
}
turn_one(x, y);
}
int main()
{
for (int i = 0; i < 4; i ++ ) cin >> g[i];
vector<PII> res;
for (int op = 0; op < 1 << 16; op ++ )
{
vector<PII> temp;
memcpy(backup, g, sizeof g);
for (int i = 0; i < 4; i ++ )
for (int j = 0; j < 4; j ++ )
if (op >> get(i, j) & 1)
{
temp.push_back({i, j});
turn_all(i, j);
}
bool has_closed = false;
for (int i = 0; i < 4; i ++ )
for (int j = 0; j < 4; j ++ )
if (g[i][j] == '+')
has_closed = true;
if (has_closed == false)
{
if (res.empty() || res.size() > temp.size()) res = temp;
}
memcpy(g, backup, sizeof g);
}
cout << res.size() << endl;
for (auto op : res) cout << op.x + 1 << ' ' << op.y + 1 << endl;
return 0;
}
位运算写法
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
typedef pair<int,int> PII;
const int N = 4, INF = 100;
int change[N][N];
int get(int x, int y)
{
return x * N + y;
}
int main()
{
for (int i = 0; i < N; i ++ )
for (int j = 0; j < N; j ++ )
{
for (int k = 0; k < N; k ++ ) change[i][j] += (1 << get(i, k)) + (1 << get(k, j));
change[i][j] -= 1 << get(i, j);
}
int state = 0;
for (int i = 0; i < N; i ++ )
{
string line;
cin >> line;
for (int j = 0; j < N; j ++ )
if (line[j] == '+')
state += 1 << get(i, j);
}
vector<PII> path;
for (int i = 0; i < 1 << 16; i ++ )
{
int now = state;
vector<PII> temp;
for (int j = 0; j < 16; j ++ )
if (i >> j & 1)
{
int x = j / 4, y = j % 4;
now ^= change[x][y];
temp.push_back({x, y});
}
if (!now && (path.empty() || path.size() > temp.size())) path = temp;
}
cout << path.size() << endl;
for (auto &p : path)
cout << p.first + 1 << ' ' << p.second + 1 << endl;
return 0;
}