2020 ICPC·Xiaomi Internet Trial Tournament First Walking Machine

Walking Machine
topic
in a n ∗ mn*mnSearch in the matrix of m , each character has a different meaning, such as:
WWW means from (xxx ,yyy ) can go to (x − 1 x-1x1 ,yyy )
AAA means from (xxx ,yyy ) can go to (xxx ,y - 1 y-1and1)
S S S means from (xxx ,yyy ) can go to (x + 1 x+1x+1 ,yyy)
D D D means from (xxx ,yyy ) can go to (xxx ,y + 1 y + 1and+1 )
Request which points will cross the boundary, that is, point coordinates (xxx ,yyy )xxx <1 orxxx > n n n , oryyy <1 , 或者yyy > m m m .
Input format
inputnnn andmmm represents the size of the matrix.
Nextnnn rows, each rowmmm characters.
Output format
Output an integer, indicating the number of points out of bounds. The comprehensive application of
problem solving ideas
and search set and dfs
splits the matrix into nnn* m m m points, record the position of each point, and then use the idea of ​​union search to merge all out-of-bounds points into a set, and finallyfindall pointsClick f i n d , and record the number of points out of bounds is the answer.

#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 1e6 + 7, inf = 1e8;
struct node{
    
    
    int x,y;
    char s;
};
node a[maxn];
int fa[maxn], cnt = 0;

char str[1007][1007];
bool inbound(int x, int l, int r)
{
    
    
    if(x < l || x > r) return false;
    return true;
}
void Init(int x)  //初始化
{
    
    
    for(int i = 1; i <= x; i++) fa[i] = i;
}
int Find(int x)  //查询,路径压缩
{
    
    
    if(fa[x] != x) fa[x] = Find(fa[x]);
    return fa[x];
}
void Merge(int x, int y)  //合并
{
    
    
    int fax = Find(x), fay = Find(y);
    fa[fax] = fay;
}

int main()
{
    
    
    int n,m;
    scanf(" %d%d",&n,&m);
    for(int i = 1; i <= n; i++)
        for(int j = 1; j <= m; j++){
    
    
            scanf(" %c",&str[i][j]);
            a[++cnt] = {
    
    i, j, str[i][j]};
        }

    Init(cnt+1);
    for(int i = 1; i <= cnt; i++)
    {
    
    
        int x = a[i].x, y = a[i].y; char s = a[i].s;
        int num = (x-1)*m + y;
        int tx = 0, ty = 0, tnum = 0;

        if(s == 'W') tx = x -  1, ty = y;
        if(s == 'A') tx = x, ty = y - 1;
        if(s == 'S') tx = x + 1, ty = y;
        if(s == 'D') tx = x, ty = y + 1;

        if(!inbound(tx, 1, n) || !inbound(ty, 1, m)) Merge(num, cnt+1);
        else
        {
    
    
             tnum = (tx - 1)*m + ty;
             if(Find(num) != Find(tnum)) Merge(num, tnum);
        }
    }

    int res = 0;
    for(int i = 1; i <= cnt; i++)
        if(Find(i) == cnt+1) res++;
    printf("%d\n",res);
    return 0;
}

Guess you like

Origin blog.csdn.net/Edviv/article/details/109391080