グリッドゲーム(そして裸の質問を集める)

ここに画像の説明を挿入
ここに画像の説明を挿入

アイデア:エッジを接続する前に、現在の2つのポイントがすでに同じセットにあるかどうかを判断します。そうであれば、接続がリングを形成することを意味します。ユニオン検索セットを使用して書き込みます。次の図に従って、次のことができます。座標がポイント番号になる方法を知っている

ここに画像の説明を挿入

//#pragma GCC optimize(2)
#include<bits/stdc++.h>
 
using namespace std;
typedef long long ll;
#define SIS std::ios::sync_with_stdio(false)
#define space putchar(' ')
#define enter putchar('\n')
#define lson root<<1
#define rson root<<1|1
typedef pair<int,int> PII;
const int mod=1e9+7;
const int N=1e7+5;

int gcd(int a,int b)
{
    
    
    return b==0?a:gcd(b,a%b);
}
 
ll lcm(ll a,ll b)
{
    
    
    return a*(b/gcd(a,b));
}
 
template <class T>
void read(T &x)
{
    
    
    char c;
    bool op = 0;
    while(c = getchar(), c < '0' || c > '9')
        if(c == '-')
            op = 1;
    x = c - '0';
    while(c = getchar(), c >= '0' && c <= '9')
        x = x * 10 + c - '0';
    if(op)
        x = -x;
}
template <class T>
void write(T x)
{
    
    
    if(x < 0)
        x = -x, putchar('-');
    if(x >= 10)
         write(x / 10);
    putchar('0' + x % 10);
}
ll qsm(int a,int b,int p)
{
    
    
    ll res=1%p;
    while(b)
    {
    
    
        if(b&1)
            res=res*a%p;
        a=1ll*a*a%p;
        b>>=1;
    }
    return res;
}
int fa[N];
 int n;
int fnd(int x)
{
    
    
   return fa[x]==x?x:fa[x]=fnd(fa[x]);
}
int getid(int x,int y){
    
    
    return x*n+y;
}
int main()
{
    
    


     int m;
      scanf("%d%d",&n,&m);
      for(int i=0;i<=n*n;i++) fa[i]=i;
      int ans=0;
      for(int i=1;i<=m;i++){
    
    
          int x,y;
          char op;
          cin>>x>>y>>op;
          x--;y--;
          int a=getid(x,y),b;
          if(op=='D'){
    
    
             b=getid(x+1,y);
          }else{
    
    
             b=getid(x,y+1);
          }
          a=fnd(a);b=fnd(b);
          if(a!=b){
    
    
           fa[a]=b;
          }else {
    
    
              ans=i;break;
              
          };
          
          
      }
  
      if(!ans)puts("draw");
      else cout<<ans;
     
      
       
      

    return 0;

}


おすすめ

転載: blog.csdn.net/qq_43619680/article/details/109540125