题解:CF1985H1 Maximize the Largest Component (Easy Version)

· · 题解

题目大意

给出一个 n 行 m 列的二维字符数组,且只由 '.' 和 '#' 组成,我们需要找出其中由 '#' 组成的最大的那个联通块并输出它里面 '#' 的数量。
但是我们可以选择将数组中的一行或者一列全部变成 '#' ,以让我们能构造出一个最大的联通块并输出其个数。(只能操作一次)

思路分析

首先需要注意 n \times m \leq 10^6 , 所以不能使用 char 数组,我们可以使用 vector 存储该题的数据。 并且可以使用 assign 重置 vector 的大小并初始化。

接下来我们可以使用搜索将所有联通块进行染色(可以理解为编号),并用 ltk[] 数组存储每个联通块中 '#' 的数量。

然后先遍历每一行,依次将离改行 1 格内的所有点进行判断,并将所有能够访问到的联通块编号放入集合 set 中,同时记得用 cnt 统计改行 '.' 的数量。

使用 set 去重之后,将所有能访问到的联通块的大小也统计到 cnt 中。

最后再对所有列进行同样的操作,使用 ans 记录对每行每列操作完之后 cnt 的最大值即可。

代码

#include<bits/stdc++.h>
using namespace std;
#define endl '\n'
typedef long long ll;
const int N = 2e5 + 10;
vector<vector<int> > dp;
vector<vector<char> > a;
int n, m, color=1;
int dx[]={0,0,1,-1};
int dy[]={1,-1,0,0};
int ltk[1000010];
void dfs(int x, int y){
    for(int i=0;i<4;i++){
        int xx = x + dx[i], yy = y + dy[i];
        if(xx>=0&&xx<n&&yy>=0&&yy<m&&dp[xx][yy]==0&&a[xx][yy]=='#'){
            dp[xx][yy] = color;
            ltk[color]++;
            dfs(xx, yy);
        }
    }
}
void solve(){
    cin >> n >> m;
    color=1;
    dp.assign(n + 5, vector<int>(m + 5, 0));
    a.assign(n + 5, vector<char>(m + 5, 0));
    for(int i=0;i<n;i++){
        for(int j=0; j<m; j++){
            char c; cin>>c;
            a[i][j] = c;
        }
    }
    for(int i=0; i<n;i++){
        for(int j=0; j<m; j++){
            if(a[i][j]=='#'&&dp[i][j]==0){
                dp[i][j] = color;
                ltk[color] = 1;
                dfs(i, j);
                color++;
            }
        }
    }


    set<int> st;
    int ans = 0;
    // 枚举每一行
    for(int i=0; i<n;i++){
        int cnt = 0;
        st.clear();
        for(int j=0; j<m; j++){
            if(a[i][j]=='.') cnt++;
            for(int k=0; k<4; k++){
                int xx=i+dx[k], yy=j+dy[k];
                if(xx>=0&&xx<n&&yy>=0&&yy<m&&dp[xx][yy]){
                    st.insert(dp[xx][yy]);
                }
            }
        }
        for(auto x : st){
            cnt += ltk[x];
        }
        if(cnt==0) cnt=1;
        ans = max(ans, cnt);
    }
    // 枚举每一列
    for(int j=0; j<m;j++){
        int cnt = 0;
        st.clear();
        for(int i=0; i<n; i++){
            if(a[i][j]=='.') cnt++;
            for(int k=0; k<4; k++){
                int xx=i+dx[k], yy=j+dy[k];
                if(xx>=0&&xx<n&&yy>=0&&yy<m&&dp[xx][yy]){
                    st.insert(dp[xx][yy]);
                }
            }
        }
        for(auto x : st){
            cnt += ltk[x];
        }
        if(cnt==0) cnt=1;
        ans = max(ans, cnt);
    }
    cout << ans << endl;
}

int main(){
    int t; cin>>t;
    while(t--){
        solve();
    }
    return 0;
}