Pelom777's Blog

洛谷 github
Pelom的头像
Pelom777
Stop crying and smile.——Angels of Death
/*tool*/

电路维修

#include<iostream>
#include<cstdio>
#include<deque>
#include<memory.h>
using namespace std;
#define min(a,b) ((a)<(b)?(a):(b))
#define N 510
bool m[N][N];
int T,R,C;
char s[N];
int dis[N][N];
bool vis[N][N];
int p[4][2]={{1,1},{1,-1},{-1,1},{-1,-1}};
inline bool calc(int vx,int vy,int ux,int uy){
    if((ux<vx && uy<vy) || (ux>vx && uy>vy))
        return !m[min(ux,vx)][min(uy,vy)];
    else return m[min(ux,vx)][min(uy,vy)];
}
void bfs(){
    m[0][0]=1;
    deque<pair<pair<int,int>,pair<int,int> > > Q;
    Q.push_back(make_pair(make_pair(0,0),make_pair(1,1)));
    for(;!Q.empty();){
        pair<pair<int,int>,pair<int,int> > e=Q.front();
        Q.pop_front();
        pair<int,int> u=e.first,v=e.second;
        int ux=u.first,uy=u.second,vx=v.first,vy=v.second;
        if(vis[vx][vy])
            continue;
        dis[vx][vy]=dis[ux][uy]+calc(vx,vy,ux,uy);
        vis[vx][vy]=1;
        for(int i=0;i<4;i++){
            int nx=vx+p[i][0],ny=vy+p[i][1];
            if(vis[nx][ny] || nx<1 || nx>R+1 || ny<1 || ny>C+1)
                continue;
            if(calc(nx,ny,vx,vy))
                Q.push_back(make_pair(v,make_pair(nx,ny)));
            else Q.push_front(make_pair(v,make_pair(nx,ny)));
        }
    }
}
int main(){
    scanf("%d",&T);
    for(;T--;){
        memset(vis,0,sizeof(vis));
        memset(dis,0,sizeof(dis));
        scanf("%d%d",&R,&C);
        for(int i=1;i<=R;i++){
            scanf("%s",s+1);
            for(int j=1;j<=C;j++)
                if(s[j]=='\\')
                    m[i][j]=1;
                else m[i][j]=0;
        }
        bfs();
        if(vis[R+1][C+1])
            printf("%d\n",dis[R+1][C+1]);
        else puts("NO SOLUTION");
    }
    return 0;
}
posted @ 2019-03-29 19:10  Pelom  阅读(171)  评论(0编辑  收藏  举报