百练+上下是否联通+并查集应用

点击打开链接
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string>
#include<cstring>
#include<string.h>
#include<math.h>
#include<algorithm>
#define inf 0x3f3f3f3f
#define LL long long
using namespace std;
const int maxn=1e3+5;
int T=0,N=0,M=0,xx=0,yy=0,p[maxn*maxn],sum=0,result=inf;
void init()
{
    for(int i=0;i<=N*N+1;i++){
        p[i]=-1;
    }
}
int find(int x){
    if(p[x]!=x){
        return p[x]=find(p[x]);
    }
    else return x;
}
int main()
{
    int xx=0,yy=0,temp1,temp2;
    scanf("%d",&T);
    while (T--) {
        bool flag=false;
        scanf("%d %d",&N,&M);
        init();
        for(int i=1;i<=M;i++){
            scanf("%d %d",&xx, &yy);
            if(!flag){
                int loc=(xx-1)*N+yy;
                p[loc]=loc;//必须要有的
                //第一行 翻了就是标记0
                if(loc<=N&&loc>0){
                    p[0]=0;
                    temp1=find(loc);
                    if(temp1!=0) p[temp1]=0;
                }
                else if(loc>N*(N-1)&&loc<=N*N){//最后一行 翻了就是标记N*N+1
                    p[N*N+1]=N*N+1;
                    temp1 = find(loc);
                    if(temp1!=N*N+1) p[temp1]=N*N+1;
                }
                //左
                if(loc%N>1&&p[loc-1]!=-1){
                    temp1= find(loc);
                    temp2= find(loc-1);
                    if(temp1!=temp2) p[temp1] =temp2;
                }
                //上
                if(loc/N>0&&p[loc-N]!=-1){
                    temp1= find(loc);
                    temp2= find(loc-N);
                    if(temp1!=temp2) p[temp1]=temp2;
                }
                //右
                if(loc%N!=0&&p[loc+1]!=-1){
                    temp1=find(loc);
                    temp2=find(loc+1);
                    if(temp1!=temp2) p[temp1]=temp2;
                }
                //下
                if(loc+N<=N*N&&p[loc+N]!=-1){
                    temp1=find(loc);
                    temp2=find(loc+N);
                    if(temp1!=temp2) p[temp1]=temp2;
                }
                
                // cout<< temp1<<" "<<p[temp1] << endl;
                
                if(p[0]!=-1&&p[N*N+1]!=-1&&find(0)==find(N*N+1)){//一定要用find(0)==find(N*N+1)
                    flag=true;
                    printf("%d\n",i);
                }
            }
        }
        if(!flag){
            printf("-1\n");
        }
    }
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值