B - Three States CodeForces - 590C -0-1 BFS

  •  
  • B - Three States

  •  CodeForces - 590C 
  • 题意:给出一个图,有三类区域1,2,3,#是墙不能走,’.‘是可以修路的,问如何修一条路能够是三块联通
  • 思路:bfs预处理出,三类区域到达图上个点需要修路的数量,队列堆优化修路数量少的优先级高。
  • 然后枚举一下他们三个的交点在哪使得修路最短。
  • #include<bits/stdc++.h>
    using namespace std;
    #define ll long long
    #define inf 0x3f3f3f3f
    #define maxn 1050
    int n,m,c[5],d[5];
    char mmp[maxn][maxn];
    bool vis[maxn][maxn];
    int dis[5][maxn][maxn];
    int to[5][2]= {{0,1},{0,-1},{1,0},{-1,0}};
    struct node
    {
        int x,y,step;
        bool operator<(const node &b)const
        {
            return step>b.step;
        }
    } top,temp;
    bool judge(int x,int y)
    {
        if(x<0||y<0||x>=n||y>=m||vis[x][y]||mmp[x][y]=='#')return false;
        return true;
    }
    void bfs(int ord,int x,int y)
    {
        memset(vis,0,sizeof(vis));
        priority_queue<node>q;
        q.push(node{x,y,0});
        vis[x][y]=1;
        while(!q.empty())
        {
            top=q.top();
            q.pop();
            dis[ord][top.x][top.y]=top.step;
            for(int i=0; i<4; i++)
            {
                temp=top;
                temp.x+=to[i][0];
                temp.y+=to[i][1];
                if(judge(temp.x,temp.y))
                {
                    vis[temp.x][temp.y]=1;
                    if(mmp[temp.x][temp.y]=='.')
                        temp.step++;
                    q.push(temp);
                }
            }
        }
        return ;
    }
    ll mi(ll a,ll b)
    {
        if(a<b)return a;
        else return b;
    }
    int main()
    {
        ll ans=inf,te;
        memset(dis,inf,sizeof(dis));
        scanf("%d%d",&n,&m);
        for(int i=0; i<n; i++)
        {
            cin>>mmp[i];
            for(int j=0; j<m; j++)
            {
                if(mmp[i][j]=='1')
                    c[1]=i,d[1]=j;
                else if(mmp[i][j]=='2')
                    c[2]=i,d[2]=j;
                else if(mmp[i][j]=='3')
                    c[3]=i,d[3]=j;
            }
        }
        for(int i=1; i<=3; i++)
            bfs(i,c[i],d[i]);
        for(int i=0; i<n; i++)
            for(int j=0; j<m; j++)
            {
                if(mmp[i][j]=='#')continue;
                if(dis[1][i][j]==inf||dis[2][i][j]==inf||dis[3][i][j]==inf)continue;
                te=dis[1][i][j]+dis[2][i][j]+dis[3][i][j];
                if(mmp[i][j]=='.')
                    ans=mi(ans,te-2);
                else
                    ans=mi(ans,te);
            }
        if(ans>=inf)printf("-1\n");
        else printf("%lld\n",ans);
        return 0;
    }
    
  •  
  •  
  •  

猜你喜欢

转载自blog.csdn.net/BePosit/article/details/84190815
今日推荐