B. Monopole Magnets(思维+连通块)

https://codeforces.com/contest/1344/problem/B


思路:开始看成了白块区域不能放S极了。

看懂题意的话还是能做对的。

1.如果有一行/一列存在不连续的黑块。 -1

2.如果有一行全空而不存在列全空。-1/反之亦然。

剩下的就全部扔S极,每个连通块里扔一个N极就好

#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=3e3+100;
typedef int LL;
inline LL read(){LL x=0,f=1;char ch=getchar();	while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}while (isdigit(ch)){x=x*10+ch-48;ch=getchar();}
return x*f;}
char ma[maxn][maxn];
LL fa[maxn*maxn];
int dx[4]={1,0,-1,0};
int dy[4]={0,1,0,-1};
LL n,m;
LL get(LL x,LL y){
   return (x-1)*m+y;
}
LL find(LL x){
   if(fa[x]!=x) return fa[x]=find(fa[x]);
   return fa[x];
}
int main(void){
   cin.tie(0);cout.tie(0);std::ios::sync_with_stdio(false);
   cin>>n>>m;
   for(LL i=0;i<maxn*maxn;i++) fa[i]=i;
   for(LL i=1;i<=n;i++){
       for(LL j=1;j<=m;j++){
           cin>>ma[i][j];
       }
   }
   bool flag=1;
   bool r1=false; bool l1=false;
   for(LL i=1;i<=n;i++){
      LL num=0;
      for(LL j=1;j<=m;j++){
          if(num==0&&ma[i][j]=='#') num=1;
          else if(num==1&&ma[i][j]=='.') num=2;
          else if(num==2&&ma[i][j]=='#'){
            flag=0;break;
          }
      }
      if(num==0) r1=true;
   }
   for(LL j=1;j<=m;j++){
      LL num=0;
      for(LL i=1;i<=n;i++){
         if(num==0&&ma[i][j]=='#') num=1;
         else if(num==1&&ma[i][j]=='.') num=2;
         else if(num==2&&ma[i][j]=='#'){
            flag=0;break;
         }
      }
      if(num==0) l1=true;
   }
   if(r1!=l1) flag=0;

   if(flag==0){
      cout<<"-1"<<"\n";
   }
   else{

      for(LL i=1;i<=n;i++){
          for(LL j=1;j<=m;j++){
              if(ma[i][j]!='#') continue;
              for(LL k=0;k<4;k++){
                  LL nx=i+dx[k];LL ny=j+dy[k];
                  if(nx<1||ny<1||nx>n||ny>m) continue;
                  if(ma[nx][ny]=='#'&&find(get(nx,ny))!=find(get(i,j))){
                     fa[find(get(nx,ny))]=find(get(i,j));
                  }
              }
          }
      }
      LL ans=0;
      for(LL i=1;i<=n;i++){
          for(LL j=1;j<=m;j++){
              if(ma[i][j]=='#'&&fa[get(i,j)]==get(i,j)){
                 ans++;
              }
          }
      }
      cout<<ans<<"\n";
   }
   return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值