1359. 城堡【难度: 一般 / 知识点: 并查集】

在这里插入图片描述
https://www.acwing.com/problem/content/description/1361/
在这里插入图片描述

#include<bits/stdc++.h>
using namespace std;
const int N=55;
int p[N*N],s[N*N],n,m,a[N][N];
int get(int x,int y) {
    
    return x*m+y;}
int find(int x)
{
    
    
    if(x!=p[x]) p[x]=find(p[x]);
    return p[x];
}
void solve1()
{
    
    
    int cnt=n*m,maxv=1;
    int dx[2]={
    
    -1,0},dy[2]={
    
    0,1},dw[2]={
    
    2,4};
    for(int i=0;i<n;i++)
    {
    
    
        for(int j=0;j<m;j++)
        {
    
    
            for(int z=0;z<2;z++)
            {
    
    
                if( (a[i][j]&dw[z]) == 0)
                {
    
    
                    int x=i+dx[z],y=j+dy[z];
                    if(x<0||x>=n||y<0||y>=m) continue;
                    int a=get(i,j),b=get(x,y);
                    if(find(a)!=find(b))
                    {
    
    
                        cnt--;
                        s[find(b)]+=s[find(a)];
                        p[find(a)]=find(b);
                        maxv=max(maxv,s[find(b)]);
                    }
                }
            }
        }
    }
    cout<<cnt<<endl;
    cout<<maxv<<endl;
}
void solve2()
{
    
    
    int dx[2]={
    
    -1,0},dy[2]={
    
    0,1},dw[2]={
    
    2,4};
    int ans_x,ans_y,ans_u,area=0;
    for(int j=0;j<m;j++)//按照题目要求的优先级先列
    {
    
    
        for(int i=n-1;i>=0;i--)//再行
        {
    
    
            for(int z=0;z<2;z++)
            {
    
    
                if((a[i][j]&dw[z]))
                {
    
    
                    int x=i+dx[z],y=j+dy[z];
                    if(x<0||x>=n||y<0||y>=m) continue;
                    int a=get(i,j),b=get(x,y);
                    if(find(a)==find(b)) continue;
                    int maxv=s[find(a)]+s[find(b)];
                    if(maxv>area) ans_x=i,ans_y=j,ans_u=z,area=maxv;
                }
            }
        }
    }
    cout<<area<<endl;
    cout<<ans_x+1<<" "<<ans_y+1<<" "<<(ans_u?'E':'N')<<endl;
}
int main(void)
{
    
    
    cin>>m>>n;
    for(int i=0;i<n;i++)
        for(int j=0;j<m;j++)
            cin>>a[i][j];
    for(int i=0;i<n*m;i++) p[i]=i,s[i]=1;
    solve1();
    solve2();
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_46527915/article/details/121289248