1. 程式人生 > 其它 >「「POJ2965」飛行員兄弟/The Pilots Brothers' Refrigerator」題解

「「POJ2965」飛行員兄弟/The Pilots Brothers' Refrigerator」題解

「「POJ2965」飛行員兄弟/The Pilots Brothers' Refrigerator」題解。

「「POJ2965」飛行員兄弟/The Pilots Brothers' Refrigerator」題解

原題目連結:Link

其實就是普通的 dfs……程式碼如下:

#include <bits/stdc++.h>
using namespace std;
const int MAXN = 10, MAXM = 20;

char a[MAXN][MAXN];
int t[MAXM][2], ans[MAXM][2], tot = 1e9;

bool check() {
    for (int i = 1; i <= 4; i++)
        for (int j = 1; j <= 4; j++)
            if (a[i][j] == '+') return false;
    return true; // 判斷是否全部開啟
}

void mov(int x, int y) {
    for (int i = 1; i <= 4; i++) {
        if (a[x][i] == '+') a[x][i] = '-';
        else a[x][i] = '+';
        if (a[i][y] == '+') a[i][y] = '-';
        else a[i][y] = '+';
    }
    if (a[x][y] == '+') a[x][y] = '-';
    else a[x][y] = '+'; // 模擬改變
}
void dfs(int k, int step) {
    if (k > 16) {
        if (check() && step < tot) { // 如果都開著,並且步數小於目前答案
		// 這裡如果取等號就會盡量大,而不是題意的儘量小
            tot = step;
            for (int i = 1; i <= tot; i++) {
                ans[i][0] = t[i][0];
                ans[i][1] = t[i][1];
            }
        } // copy 到 ans 數組裡
        return;
    }
    int x = (k - 1) / 4 + 1, y = k % 4 ? k % 4 : 4; // 獲取行列
    t[++step][0] = x; t[step][1] = y; // 佔位
    mov(x, y);
    dfs(k + 1, step);
    t[step][0] = 0; t[step--][1] = 0; // 取消佔位
    mov(x, y);
    dfs(k + 1, step);
}
int main() {
    #ifndef ONLINE_JUDGE
        freopen("1.in", "r", stdin);
        freopen("1.out", "w", stdout);
    #endif
    for (int i = 1; i <= 4; i++)
        for (int j = 1; j <= 4; j++)
            cin >> a[i][j];
    dfs(1, 0);
    cout << tot << endl;
    for (int i = 1; i <= tot; i++)
        cout << ans[i][0] << " " << ans[i][1] << endl;
    return 0;
}

當然,你用二進位制表示也行。