P4129

贪心 #状压

一定优先选择当前的距离最远的两个点中的一个

proof
如果后取这两个,取到这两个点的时候的代价仍然为这个值,不会更优,、
但是对于中间的部分,代价只会不变或者更劣,所以优先选择这两个点中的一个是正确的
证毕

然后直接对当前选择节点状压,最多 \(O(2^{64})\) 种状态,但是其中的合法状态很少,可以通过

// Author: xiaruize
#ifndef ONLINE_JUDGE
bool start_of_memory_use;
#endif
#include <bits/stdc++.h>
using namespace std;
#ifndef ONLINE_JUDGE
clock_t start_clock = clock();
#endif
#define int long long
#define ull unsigned long long
#define ALL(a) (a).begin(), (a).end()
#define pb push_back
#define mk make_pair
#define pii pair<int, int>
#define pis pair<int, string>
#define sec second
#define fir first
#define sz(a) int((a).size())
#define Yes cout << "Yes" << endl
#define YES cout << "YES" << endl
#define No cout << "No" << endl
#define NO cout << "NO" << endl
#define mms(arr, n) memset(arr, n, sizeof(arr))
#define rep(i, a, n) for (int i = (a); i <= (n); ++i)
#define per(i, n, a) for (int i = (n); i >= (a); --i)
int max(int a, int b)
{
    if (a > b)
        return a;
    return b;
}
int min(int a, int b)
{
    if (a < b)
        return a;
    return b;
}
const int INF = 0x3f3f3f3f3f3f3f3f;
const int MOD = 1000000007;
const int N = 30 + 10;

int n;
char s[N][N];
vector<pii> vec;
int m;
map<ull, int> mp;

int dfs(ull msk)
{
    if (mp.count(msk))
        return mp[msk];
    int &res = mp[msk];
    ull mx = 0, a, b;
    rep(i, 0, m - 1)
    {
        if (msk & (1ull << i))
            rep(j, i + 1, m - 1)
            {
                if (msk & (1ull << j))
                    if (abs(vec[i].first - vec[j].first) + abs(vec[i].second - vec[j].second) > mx)
                    {
                        mx = abs(vec[i].first - vec[j].first) + abs(vec[i].second - vec[j].second);
                        a = i;
                        b = j;
                    }
            }
    }
    return (res = min(dfs(msk ^ (1ull << a)), dfs(msk ^ (1ull << b))) + mx);
}

void solve()
{
    cin >> n;
    rep(i, 1, n) cin >> (s[i] + 1);
    rep(i, 1, n)
    {
        rep(j, 1, n)
        {
            if (s[i][j] == '#')
                vec.push_back({i, j});
        }
    }
    m = vec.size();
    ull msk = 0;
    rep(i, 0, m - 1) msk |= (1ull << i);
    cout << dfs(msk) << endl;
}

#ifndef ONLINE_JUDGE
bool end_of_memory_use;
#endif

signed main()
{
    // freopen(".in","r",stdin);
    // freopen(".out","w",stdout);
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int testcase = 1;
    // cin >> testcase;
    while (testcase--)
        solve();
#ifndef ONLINE_JUDGE
    cerr << "Memory use:" << (&end_of_memory_use - &start_of_memory_use) / 1024.0 / 1024.0 << "MiB" << endl;
    cerr << "Time use:" << (double)clock() / CLOCKS_PER_SEC * 1000.0 << "ms" << endl;
#endif
    return 0;
}
posted @ 2024-04-02 17:00  xiaruize  阅读(7)  评论(0)    收藏  举报