abc351_d tj

· · 题解

思路

我们充分发扬人类智慧,使用 dfs,对每一个不是磁铁的地点进行记忆化爆搜,然后对于每个爆搜得到的答案进行取最大值操作即可。

细节看代码注释。

喜提最劣解 1928ms。

Code

#include <bits/stdc++.h>
#define endl '\n'
#define ll long long

using namespace std;
const int E = 1e6 + 5;
ll n, m, ans;
ll x_1, y_1;
char a[1001][1001];
bool vis[1001][1001];
map<pair<ll, ll>, ll> mp1;//记忆化
int main()
{
    cin >> n >> m;
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= m; j++)
            cin >> a[i][j];
    ll ans1 = 0;
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= m; j++)
        {
            x_1 = i, y_1 = j;
            map<pair<ll, ll>, bool> mp;//检查是否重复统计
            auto dfs = [&](auto &&dfs, ll x, ll y) -> ll
            {
                // if (x_1 == 2 && y_1 == 3)
                //     cout << x << " " << y << endl;
                if (mp[{x, y}])
                    return 1;//可以忽略不计
                if (mp1[{x, y}])
                {
                    ans += mp1[{x, y}];
                    return 1;//可以忽略不计
                }
                ans++;//统计
                mp[{x, y}] = 1;//将这个位置视为已经统计过的点
                if ((a[x + 1][y] == '#' || a[x - 1][y] == '#' || a[x][y + 1] == '#' || a[x][y - 1] == '#'))
                    return 0;//可以忽略不计
                vis[x][y] = 1;
                if (x + 1 <= n && !vis[x + 1][y])
                    dfs(dfs, x + 1, y);
                if (x - 1 >= 1 && !vis[x - 1][y])
                    dfs(dfs, x - 1, y);
                if (y + 1 <= m && !vis[x][y + 1])
                    dfs(dfs, x, y + 1);
                if (y - 1 >= 1 && !vis[x][y - 1])
                    dfs(dfs, x, y - 1);
                vis[x][y] = 0;
                mp1[{x, y}] = ans;
                return 1;//可以忽略不计
            };
            if (a[i][j] != '#')
                dfs(dfs, i, j);
            // cout << i << " " << j << " " << ans << endl;
            ans1 = max(ans1, ans);//统计答案
            ans = 0;
        }
    cout << ans1;
    return 0;
}