zoukankan      html  css  js  c++  java
  • 【TOJ1162】格子游戏-二维并查集判环

    题目大意:在一个n*n的点阵上按顺序添边,到围成环的时候就停止,求添多少条边之后停止,如果添完所有边也不能停止,输出draw。

    做法:用二维并查集判环,如果当前边涉及到的两点不在同一集合内,则合并两个集合,否则说明形成环,直接输出结果即可。

    以下是本人代码:

    #include <cstdio>
    #include <cstdlib>
    #include <iostream>
    #include <algorithm>
    using namespace std;
    long n,m;
    
    struct
    {
      long x,y;
    }f[210][210],a,b;
    
    long findx(long x,long y)
    {
      long rx=x,ry=y,ix=x,iy=y,jx,jy;
      while(f[rx][ry].x!=rx||f[rx][ry].y!=ry) {jx=rx;rx=f[rx][ry].x;ry=f[jx][ry].y;}
      while(ix!=rx||iy!=ry)
      {
        jx=f[ix][iy].x;
    	jy=f[ix][iy].y;
    	f[ix][iy].x=rx;
    	f[ix][iy].y=ry;
    	ix=jx;
    	iy=jy;
      }
      return rx;
    }
    
    long findy(long x,long y)
    {
      long rx=x,ry=y,ix=x,iy=y,jx,jy;
      while(f[rx][ry].x!=rx||f[rx][ry].y!=ry) {jx=rx;rx=f[rx][ry].x;ry=f[jx][ry].y;}
      while(ix!=rx||iy!=ry)
      {
        jx=f[ix][iy].x;
    	jy=f[ix][iy].y;
    	f[ix][iy].x=rx;
    	f[ix][iy].y=ry;
    	ix=jx;
    	iy=jy;
      }
      return ry;
    }
    
    void merge(long x,long y,long xx,long yy)
    {
      long fx=findx(x,y),fy=findy(x,y),fxx=findx(xx,yy),fyy=findy(xx,yy);
      f[fx][fy].x=fxx;
      f[fx][fy].y=fyy;
    }
    
    void input()
    {
      scanf("%ld %ld
    ",&n,&m);
    }
    
    void work()
    {
      int i;
      for(i=1;i<=n;i++)
        for(int j=1;j<=n;j++)
    	  {f[i][j].x=i;f[i][j].y=j;}
      for(i=1;i<=m;i++)
      {
        char c;
        scanf("%ld %ld %c
    ",&a.x,&a.y,&c);
    	if (c=='D') {b.x=a.x+1;b.y=a.y;}
    	if (c=='R') {b.x=a.x;b.y=a.y+1;}
    	long ax=findx(a.x,a.y),ay=findy(a.x,a.y),bx=findx(b.x,b.y),by=findy(b.x,b.y);
        if (ax==bx&&ay==by) break;
    	else merge(a.x,a.y,b.x,b.y);
      }
      if (i>m) printf("draw");
      else printf("%ld",i);
    }
    
    int main()
    {
      input();
      work();
      
      return 0;
    }


  • 相关阅读:
    HDU 5912 Fraction (模拟)
    CodeForces 722C Destroying Array (并查集)
    CodeForces 722B Verse Pattern (水题)
    CodeForces 722A Broken Clock (水题)
    CodeForces 723D Lakes in Berland (dfs搜索)
    CodeForces 723C Polycarp at the Radio (题意题+暴力)
    CodeForces 723B Text Document Analysis (水题模拟)
    CodeForces 723A The New Year: Meeting Friends (水题)
    hdu 1258
    hdu 2266 dfs+1258
  • 原文地址:https://www.cnblogs.com/Maxwei-wzj/p/9793930.html
Copyright © 2011-2022 走看看