codeforces 590C C. Three States(bfs+连通块之间的最短距离)

题目链接:

C. Three States

time limit per test
5 seconds
memory limit per test
512 megabytes
input
standard input
output
standard output

The famous global economic crisis is approaching rapidly, so the states of Berman, Berance and Bertaly formed an alliance and allowed the residents of all member states to freely pass through the territory of any of them. In addition, it was decided that a road between the states should be built to guarantee so that one could any point of any country can be reached from any point of any other State.

Since roads are always expensive, the governments of the states of the newly formed alliance asked you to help them assess the costs. To do this, you have been issued a map that can be represented as a rectangle table consisting of n rows and m columns. Any cell of the map either belongs to one of three states, or is an area where it is allowed to build a road, or is an area where the construction of the road is not allowed. A cell is called passable, if it belongs to one of the states, or the road was built in this cell. From any passable cells you can move up, down, right and left, if the cell that corresponds to the movement exists and is passable.

Your task is to construct a road inside a minimum number of cells, so that it would be possible to get from any cell of any state to any cell of any other state using only passable cells.

It is guaranteed that initially it is possible to reach any cell of any state from any cell of this state, moving only along its cells. It is also guaranteed that for any state there is at least one cell that belongs to it.

 
Input
 

The first line of the input contains the dimensions of the map n and m (1 ≤ n, m ≤ 1000) — the number of rows and columns respectively.

Each of the next n lines contain m characters, describing the rows of the map. Digits from 1 to 3 represent the accessory to the corresponding state. The character '.' corresponds to the cell where it is allowed to build a road and the character '#' means no construction is allowed in this cell.

 
Output
 

Print a single integer — the minimum number of cells you need to build a road inside in order to connect all the cells of all states. If such a goal is unachievable, print -1.

 
Examples
 
input
4 5
11..2
#..22
#.323
.#333
output
2
input
1 5
1#2#3
output
-1

题意:


给这样的一个图,问所有的编号1,2,3,的点时候连通,如果没有连通那么最少要把多少个点.变成数字才会连通;保证编号相同的点是连通的,而且编号相同的点之间距离相当于0;

思路:

先bfs一遍看是否连通,并把可以连通的.标记出来,然后分别以编号1,2,3的点为起点bfs,找到每个点到编号为1,2,3的点的最短距离,最后找答案的时候再扫一遍,
这点到编号1,2,3的最短距离和的最小值;

AC代码:
//#include <bits/stdc++.h>
#include <vector>
#include <iostream>
#include <queue>
#include <cmath>
#include <map>
#include <cstring>
#include <algorithm>
#include <cstdio>

using namespace std;
#define Riep(n) for(int i=1;i<=n;i++)
#define Riop(n) for(int i=0;i<n;i++)
#define Rjep(n) for(int j=1;j<=n;j++)
#define Rjop(n) for(int j=0;j<n;j++)
#define mst(ss,b) memset(ss,b,sizeof(ss));
typedef long long LL;
template<class T> void read(T&num) {
    char CH; bool F=false;
    for(CH=getchar();CH<'0'||CH>'9';F= CH=='-',CH=getchar());
    for(num=0;CH>='0'&&CH<='9';num=num*10+CH-'0',CH=getchar());
    F && (num=-num);
}
int stk[70], tp;
template<class T> inline void print(T p) {
    if(!p) { puts("0"); return; }
    while(p) stk[++ tp] = p%10, p/=10;
    while(tp) putchar(stk[tp--] + '0');
    putchar('
');
}

const LL mod=1e9+7;
const double PI=acos(-1.0);
const LL inf=1e14;
const int N=5e5+15;
int n,m,cnt;
char s[1005][1005];
int vis[1005][1005],dis[4][1005][1005],flag[1005][1005];
int dir[4][2]={0,1,0,-1,1,0,-1,0};
int dp[4][4];

struct node
{
    int x,y;
};
node temp;
void makepo(int a,int b)
{
    temp.x=a,temp.y=b;
}

queue<node>qu;
vector<node>ve[4];
int bfs(int x,int y)
{
        makepo(x,y);
        vis[x][y]=1;
        flag[x][y]=1;
        qu.push(temp);
        while(!qu.empty())
        {
            node fr=qu.front();
            qu.pop();
            if(s[fr.x][fr.y]!='.')cnt--;
            for(int i=0;i<4;i++)
            {
                int fx=dir[i][0]+fr.x,fy=dir[i][1]+fr.y;
                if(fx<1||fx>n||fy<1||fy>m)continue;
                if(!vis[fx][fy]&&s[fx][fy]!='#')
                {
                    vis[fx][fy]=1;
                    flag[fx][fy]=1;
                    makepo(fx,fy);
                    qu.push(temp);
                }
            }
        }
        if(cnt==0)return 0;
        return 1;
}

void BFS(int start)
{
    while(!qu.empty())qu.pop();
    mst(vis,0);
    int len=ve[start].size();
    for(int i=0;i<len;i++)
    {
        node q=ve[start][i];
        dis[start][q.x][q.y]=0;
        vis[q.x][q.y]=1;
        qu.push(q);
    }
    while(!qu.empty())
    {
        node fr=qu.front();
        qu.pop();

        for(int i=0;i<4;i++)
        {
            int fx=dir[i][0]+fr.x,fy=dir[i][1]+fr.y;
            if(fx<1||fx>n||fy<1||fy>m)continue;
            if(s[fx][fy]!='#'&&!vis[fx][fy])
            {

                if(s[fx][fy]>'0'&&s[fx][fy]<'9'&&s[fx][fy]!='0'+start)
            {
                int c=s[fx][fy]-'0';
                int len=ve[c].size();
                for(int j=0;j<len;j++)
                {
                    int ffx=ve[c][j].x,ffy=ve[c][j].y;
                    dis[start][ffx][ffy]=dis[start][fr.x][fr.y]+1;
                    makepo(ffx,ffy);
                    vis[ffx][ffy]=1;
                    qu.push(temp);
                }
            }
            else {
                vis[fx][fy]=1;
                dis[start][fx][fy]=dis[start][fr.x][fr.y]+1;
                makepo(fx,fy);
                qu.push(temp);}
            }
        }
    }
}

int main()
{
    int x,y;
    read(n);read(m);
    Riep(n)scanf("%s",s[i]+1);
    cnt=0;
    Riep(n)
    {
        Rjep(m)
        {
            if(s[i][j]=='1'||s[i][j]=='2'||s[i][j]=='3')
            {
                makepo(i,j);
                ve[s[i][j]-'0'].push_back(temp);
                x=i,y=j;
                cnt++;
            }
        }
    }
    if(bfs(x,y)){cout<<"-1"<<"
";return 0;}
    BFS(1);
    BFS(2);
    BFS(3);
    int ans=1e9;
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=m;j++)
        {
            if(s[i][j]!='#'&&flag[i][j])
                ans=min(ans,dis[1][i][j]+dis[2][i][j]+dis[3][i][j]-2);
        }
    }
    cout<<ans<<"
";
        return 0;
}


原文地址:https://www.cnblogs.com/zhangchengc919/p/5568719.html