题目链接:

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<''||CH>'';F= CH=='-',CH=getchar());
for(num=;CH>=''&&CH<='';num=num*+CH-'',CH=getchar());
F && (num=-num);
}
int stk[], tp;
template<class T> inline void print(T p) {
if(!p) { puts(""); return; }
while(p) stk[++ tp] = p%, p/=;
while(tp) putchar(stk[tp--] + '');
putchar('\n');
} const LL mod=1e9+;
const double PI=acos(-1.0);
const LL inf=1e14;
const int N=5e5+;
int n,m,cnt;
char s[][];
int vis[][],dis[][][],flag[][];
int dir[][]={,,,-,,,-,};
int dp[][]; 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[];
int bfs(int x,int y)
{
makepo(x,y);
vis[x][y]=;
flag[x][y]=;
qu.push(temp);
while(!qu.empty())
{
node fr=qu.front();
qu.pop();
if(s[fr.x][fr.y]!='.')cnt--;
for(int i=;i<;i++)
{
int fx=dir[i][]+fr.x,fy=dir[i][]+fr.y;
if(fx<||fx>n||fy<||fy>m)continue;
if(!vis[fx][fy]&&s[fx][fy]!='#')
{
vis[fx][fy]=;
flag[fx][fy]=;
makepo(fx,fy);
qu.push(temp);
}
}
}
if(cnt==)return ;
return ;
} void BFS(int start)
{
while(!qu.empty())qu.pop();
mst(vis,);
int len=ve[start].size();
for(int i=;i<len;i++)
{
node q=ve[start][i];
dis[start][q.x][q.y]=;
vis[q.x][q.y]=;
qu.push(q);
}
while(!qu.empty())
{
node fr=qu.front();
qu.pop(); for(int i=;i<;i++)
{
int fx=dir[i][]+fr.x,fy=dir[i][]+fr.y;
if(fx<||fx>n||fy<||fy>m)continue;
if(s[fx][fy]!='#'&&!vis[fx][fy])
{ if(s[fx][fy]>''&&s[fx][fy]<''&&s[fx][fy]!=''+start)
{
int c=s[fx][fy]-'';
int len=ve[c].size();
for(int j=;j<len;j++)
{
int ffx=ve[c][j].x,ffy=ve[c][j].y;
dis[start][ffx][ffy]=dis[start][fr.x][fr.y]+;
makepo(ffx,ffy);
vis[ffx][ffy]=;
qu.push(temp);
}
}
else {
vis[fx][fy]=;
dis[start][fx][fy]=dis[start][fr.x][fr.y]+;
makepo(fx,fy);
qu.push(temp);}
}
}
}
} int main()
{
int x,y;
read(n);read(m);
Riep(n)scanf("%s",s[i]+);
cnt=;
Riep(n)
{
Rjep(m)
{
if(s[i][j]==''||s[i][j]==''||s[i][j]=='')
{
makepo(i,j);
ve[s[i][j]-''].push_back(temp);
x=i,y=j;
cnt++;
}
}
}
if(bfs(x,y)){cout<<"-1"<<"\n";return ;}
BFS();
BFS();
BFS();
int ans=1e9;
for(int i=;i<=n;i++)
{
for(int j=;j<=m;j++)
{
if(s[i][j]!='#'&&flag[i][j])
ans=min(ans,dis[][i][j]+dis[][i][j]+dis[][i][j]-);
}
}
cout<<ans<<"\n";
return ;
}

codeforces 590C C. Three States(bfs+连通块之间的最短距离)的更多相关文章

  1. C. Edgy Trees Codeforces Round #548 (Div. 2) 【连通块】

    一.题面 here 二.分析 这题刚开始没读懂题意,后来明白了,原来就是一个数连通块里点数的问题.首先在建图的时候,只考虑红色路径上的点.为什么呢,因为为了不走红色的快,那么我们可以反着想只走红色的路 ...

  2. CodeForces 690D1 The Wall (easy) (判断连通块的数量)

    题意:给定一个图,问你有几个连通块. 析:不用说了,最简单的DFS. 代码如下: #include <bits/stdc++.h> using namespace std; const i ...

  3. D. Lakes in Berland (DFS或者BFS +连通块

    https://blog.csdn.net/guhaiteng/article/details/52730373 参考题解 http://codeforces.com/contest/723/prob ...

  4. DFS or BFS --- 连通块

    Oil Deposits Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64 Descrip ...

  5. Codeforces 987 K预处理BFS 3n,7n+1随机结论题/不动点逆序对 X&Y=0连边DFS求连通块数目

    A /*Huyyt*/ #include<bits/stdc++.h> #define mem(a,b) memset(a,b,sizeof(a)) #define pb push_bac ...

  6. 图-用DFS求连通块- UVa 1103和用BFS求最短路-UVa816。

    这道题目甚长, 代码也是甚长, 但是思路却不是太难.然而有好多代码实现的细节, 确是十分的巧妙. 对代码阅读能力, 代码理解能力, 代码实现能力, 代码实现技巧, DFS方法都大有裨益, 敬请有兴趣者 ...

  7. ZOJ 3781 - Paint the Grid Reloaded - [DFS连通块缩点建图+BFS求深度][第11届浙江省赛F题]

    题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3781 Time Limit: 2 Seconds      Me ...

  8. 【BZOJ 1098】办公楼(补图连通块个数,Bfs)

    补图连通块个数这大概是一个套路吧,我之前没有见到过,想了好久都没有想出来QaQ 事实上这个做法本身就是一个朴素算法,但进行巧妙的实现,就可以分析出它的上界不会超过 $O(n + m)$. 接下来介绍一 ...

  9. ZOJ 3781 Paint the Grid Reloaded(DFS连通块缩点+BFS求最短路)

    题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=5268 题目大意:字符一样并且相邻的即为连通.每次可翻转一个连通块X( ...

随机推荐

  1. ADT下开发环境的配置--个人配置啦 Eclipse Color Themes

    一. Eclipse Color Themes的安装 首先 这个ADT没有Marketplace Client 需要装一个, 节选自: http://blog.csdn.net/liu37226700 ...

  2. JdkDynamicAopProxy源码

     JdkDynamicAopProxy是通过接口实现动态代理类,主要方法是getProxy(ClassLoader classLoader), 代理类生成之后再调用目标方法时就会调用invoke方法. ...

  3. js 基于函数伪造的方式实现继承

    <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8&quo ...

  4. windows7下实现局域网内文件共享

    1.右击桌面网络----属性----更改高级共享设置 (注释:查看当前网络 比如:家庭网络.公共网络 等!) "我这里为公共网络" 2.选择 公共网络---选择以下选项:启动网络发 ...

  5. 拖动窗体FormBorderStyle属性为None的窗体移动

    winform窗体的样式很单一,不够漂亮,往往我们需要对窗体进行重写,但是我们又要保留在重写前窗体本身带的功能,例如拖动窗体的头进行移动之类的. 一下方式可以实现该方法: [DllImport(&qu ...

  6. [MySQL复制异常]'Cannot execute statement: impossible to write to binary log since statement is in row format and BINLOG_FORMAT = STATEMENT.'

    MySQL复制错误]Last_Errno: 1666 Last_Error: Error executing row event: 'Cannot execute statement: imposs ...

  7. SGU 531. Bonnie and Clyde 线段树

    531. Bonnie and Clyde 题目连接: http://acm.sgu.ru/problem.php?contest=0&problem=531 Description Bonn ...

  8. ASP.NET Jquery+ajax上传文件(带进度条)

    效果图 支持ie6+,chrome,ie6中文文件名会显示乱码. 上传时候会显示进度条. 需要jquery.uploadify.js插件,稍后会给出下载 前台代码 <%@ Page Langua ...

  9. C++红旗之更短形式:500多字符且无法遵守原题规则

    Purpose and Scope 研究五星红旗C++代码生成问题的代码压缩方法. 没有最短,仅仅有更短. 已经尽力了.爱因斯坦的三个小板凳里,我这是第四个. 继续深入压缩代码的方法肯定非常诡异了. ...

  10. 微信公共服务平台开发(.Net 的实现)13-------网页授权(下 :C#代码的实现 )

    接着上次的理论,我们这次来研究用代码实现“网页授权获取用户基本信息”,首先我们需要一个链接指向微信的授权页面,在微信开发平台中已经说了,这个链接必须在微信客户端中打开,那么我们就干脆使用文本消息来完成 ...