HPU 暑期集训 Day 7
今天主要讲了BFS和DFS,还有存图和链式前向星,后面这两个在今天刷题的过程中还没有遇到,晚会把他们加到我的模板里面。
Rescue
Description:
Angel was caught by the MOLIGPY! He was put in prison by Moligpy. The prison is described as a N * M (N, M <= 200) matrix. There are WALLs, ROADs, and GUARDs in the prison.
Angel's friends want to save Angel. Their task is: approach Angel. We assume that "approach Angel" is to get to the position where Angel stays. When there's a guard in the grid, we must kill him (or her?) to move into the grid. We assume that we moving up, down, right, left takes us 1 unit time, and killing a guard takes 1 unit time, too. And we are strong enough to kill all the guards.
You have to calculate the minimal time to approach Angel. (We can move only UP, DOWN, LEFT and RIGHT, to the neighbor grid within bound, of course.)
Input
First line contains two integers stand for N and M.
Then N lines follows, every line has M characters. "." stands for road, "a" stands for Angel, and "r" stands for each of Angel's friend.
Process to the end of the file.
Output
For each test case, your program should output a single integer, standing for the minimal time needed. If such a number does no exist, you should output a line containing "Poor ANGEL has to stay in the prison all his life."
Sample Input
7 8
#.#####.
#.a#..r.
#..#x...
..#..#.#
#...##..
.#......
........
Sample Output
13
Problem solving:
注意是多组输入,这里用到了运算符重载和优先队列,这两个东西最近在刷题的过程中出现的频率很高。
因为这道题中r可能有多个所以我们用a去寻找r,用结构体存点的坐标,用优先队列存结构体实现BFS,先定义一个ans变量用来存放答案,初始化为-1,如果可以找到符合条件的点就更新ans的值并结束查找。查找结束之后,如果ans仍是-1,那么输出Poor ANGEL has to stay in the prison all his life.
,否则就输出ans的值,查找过程就是bfs的模板,但是用的是优先队列。我们遇到X的时候只需要+2即可。其他的判断条件都挺好理解,可以直接看代码。
结构体如果想套到优先队列中就需要运算符重载。运算符重载的方法有好几种,这里我就会这一种。
Code
#include<bits/stdc++.h> using namespace std; char s[205][205]; int d[4][2]={-1,0,0,1,1,0,0,-1}; struct node{ int x,y,step; friend bool operator < (node a,node b) { return a.step>b.step; } }; int n,m; int vis[205][205]; void bfs(int x,int y,int xx,int yy) { int ans=-1; memset(vis,0,sizeof(vis)); priority_queue<node> q; node mid,mmp; mid.x=x,mid.y=y,mid.step=0; vis[x][y]=1; q.push(mid); while(!q.empty()) { mid=q.top(); q.pop(); if(mid.x==xx&&mid.y==yy) { ans=mid.step; break; } for(int i=0;i<4;i++) { mmp.x=mid.x+d[i][0]; mmp.y=mid.y+d[i][1]; if(mmp.x<0||mmp.x>=n||mmp.y<0||mmp.y>=m||vis[mmp.x][mmp.y]==1||s[mmp.x][mmp.y]=='#') continue; if(s[mmp.x][mmp.y]=='x') mmp.step=mid.step+2; else mmp.step=mid.step+1; q.push(mmp); vis[mmp.x][mmp.y]=1; } } if(ans==-1) puts("Poor ANGEL has to stay in the prison all his life."); else cout<<ans<<endl; } int main() { int sx,sy,ex,ey; while(~scanf("%d %d",&n,&m)) { for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { cin>>s[i][j]; if(s[i][j]=='a') { sx=i; sy=j; } if(s[i][j]=='r') { ex=i; ey=j; } } } bfs(sx,sy,ex,ey); } }
Red and Black
Description:
There is a rectangular room, covered with square tiles. Each tile is colored either red or black. A man is standing on a black tile. From a tile, he can move to one of four adjacent tiles. But he can't move on red tiles, he can move only on black tiles.
Write a program to count the number of black tiles which he can reach by repeating the moves described above.
Input
The input consists of multiple data sets. A data set starts with a line containing two positive integers W and H; W and H are the numbers of tiles in the x- and y- directions, respectively. W and H are not more than 20.
There are H more lines in the data set, each of which includes W characters. Each character represents the color of a tile as follows.
'.' - a black tile
'#' - a red tile
'@' - a man on a black tile(appears exactly once in a data set)
Output
For each data set, your program should output a line which contains the number of tiles he can reach from the initial tile (including itself).
Sample Input
6 9
....#.
.....#
......
......
......
......
......
#@...#
.#..#.
11 9
.#.........
.#.#######.
.#.#.....#.
.#.#.###.#.
.#.#..@#.#.
.#.#####.#.
.#.......#.
.#########.
...........
11 6
..#..#..#..
..#..#..#..
..#..#..###
..#..#..#@.
..#..#..#..
..#..#..#..
7 7
..#.#..
..#.#..
###.###
...@...
###.###
..#.#..
..#.#..
0 0
Sample Output
45
59
6
13
Problem solving:
简单的BFS模板题,注意答案要加上一开始所处位置的点。
Code
#include<bits/stdc++.h> using namespace std; char s[25][25]; int vis[25][25]; int d[4][2]={1,0,0,1,0,-1,-1,0}; struct node{ int x,y; }; int w,h; queue<node> que; void bfs(int x,int y) { memset(vis,0,sizeof(vis)); node mid,now,mmp; int ans=0; mid.x=x; mid.y=y; vis[x][y]=1; que.push(mid); while(!que.empty()) { now=que.front(); que.pop(); for(int i=0;i<4;i++) { mmp.x=now.x+d[i][0]; mmp.y=now.y+d[i][1]; if(mmp.x<0||mmp.x>=h||mmp.y<0||mmp.y>=w||vis[mmp.x][mmp.y]==1||s[mmp.x][mmp.y]=='#') continue; ans++; vis[mmp.x][mmp.y]=1; que.push(mmp); s[mmp.x][mmp.y]='?'; } } cout<<ans+1<<endl; } int main() { int sx,sy; while(scanf("%d %d",&w,&h)&&w&&h) { for(int i=0;i<h;i++) { for(int j=0;j<w;j++) { cin>>s[i][j]; if(s[i][j]=='@') { sx=i; sy=j; } } } // cout<<sx<<" "<<sy<<endl; bfs(sx,sy); // for(int i=0;i<h;i++) // { // for(int j=0;j<w;j++) // { // cout<<s[i][j]; // } // puts(""); // } } }
Battle City
Description:
Many of us had played the game "Battle city" in our childhood, and some people (like me) even often play it on computer now.
What we are discussing is a simple edition of this game. Given a map that consists of empty spaces, rivers, steel walls and brick walls only. Your task is to get a bonus as soon as possible suppose that no enemies will disturb you (See the following picture).
Your tank can't move through rivers or walls, but it can destroy brick walls by shooting. A brick wall will be turned into empty spaces when you hit it, however, if your shot hit a steel wall, there will be no damage to the wall. In each of your turns, you can choose to move to a neighboring (4 directions, not 8) empty space, or shoot in one of the four directions without a move. The shot will go ahead in that direction, until it go out of the map or hit a wall. If the shot hits a brick wall, the wall will disappear (i.e., in this turn). Well, given the description of a map, the positions of your tank and the target, how many turns will you take at least to arrive there?
Input
The input consists of several test cases. The first line of each test case contains two integers M and N (2 <= M, N <= 300). Each of the following M lines contains N uppercase letters, each of which is one of 'Y' (you), 'T' (target), 'S' (steel wall), 'B' (brick wall), 'R' (river) and 'E' (empty space). Both 'Y' and 'T' appear only once. A test case of M = N = 0 indicates the end of input, and should not be processed.
Output
For each test case, please output the turns you take at least in a separate line. If you can't arrive at the target, output "-1" instead.
Sample Input
3 4
YBEB
EERE
SSTE
0 0
Sample Output
8
Problem solving:
这道题跟A很像。用优先队列进行BFS查找。判断条件也很简单。不懂的话,可以直接看代码
Code
#include<iostream> #include<queue> #include<cstring> #include<cstdio> using namespace std; int m,n; char s[305][305]; int vis[305][305]; struct node{ int x,y,step; friend bool operator < (node a,node b) { return a.step>b.step; } }; int d[4][2]={1,0,0,1,-1,0,0,-1}; void bfs(int x,int y,int xx,int yy) { int ans=-1; memset(vis,0,sizeof(vis)); node mid,now; priority_queue<node> q; mid.x=x;mid.y=y;mid.step=0; q.push(mid); vis[x][y]=1; while(!q.empty()) { mid=q.top(); if(mid.x==xx&&mid.y==yy) { // cout<<mid.x<<" "<<mid.y<<endl; ans=mid.step; break; } q.pop(); for(int i=0;i<8;i++) { now.x=mid.x+d[i][0]; now.y=mid.y+d[i][1]; if(now.x<0||now.x>=m||now.y<0||now.y>=n||s[now.x][now.y]=='S'||s[now.x][now.y]=='R'||vis[now.x][now.y]==1) continue; if(s[now.x][now.y]=='B') now.step=mid.step+2; else now.step=mid.step+1; vis[now.x][now.y]=1; s[now.x][now.y]=now.step+'0'; q.push(now); } } cout<<ans<<endl; } int main() { int sx,sy,ex,ey; while(scanf("%d %d",&m,&n)&&m&&n) { for(int i=0;i<m;i++) { for(int j=0;j<n;j++) { cin>>s[i][j]; if(s[i][j]=='Y') { sx=i; sy=j; } if(s[i][j]=='T') { ex=i; ey=j; } } } bfs(sx,sy,ex,ey); // for(int i=0;i<m;i++) // { // for(int j=0;j<n;j++) // { // cout<<s[i][j]; // } // puts(""); // } } }
Catch That Cow
Description:
农夫知道一头牛的位置,想要抓住它。农夫和牛都于数轴上 ,农夫起始位于点 N(0<=N<=100000) ,牛位于点 K(0<=K<=100000) 。农夫有两种移动方式: 1、从 X移动到 X-1或X+1 ,每次移动花费一分钟 2、从 X移动到 2\X ,每次移动花费一分钟 假设牛没有意识到农夫的行动,站在原地不。最少要花多少时间才能抓住牛?
Input
一行: 以空格分隔的两个字母: N 和 K
Output
一行: 农夫抓住牛需要的最少时间,单位分钟
Sample Input
5 17
Sample Output
4
Hint
农夫使用最短时间抓住牛的方案如下: 5-10-9-18-17, 需要4分钟.
Problem solving:
经典的BFS例题。每次往下扩展队列的时候只有3种情况。就像是经常在图里面用到的四个方向一样。判断条件中要有一个最大值,不然就有可能会一直查找下去。
Code
#include<iostream> #include<queue> #include<cstring> #include<cstdio> using namespace std; int vis[1000000]; int step[1000000]; void bfs(int x,int y) { memset(vis,0,sizeof(vis)); queue<int> q; q.push(x); step[x]=0; vis[x]=1; while(!q.empty()) { int mid=q.front(),mmp; q.pop(); if(mid==y) { cout<<step[y]<<endl; break; } for(int i=0;i<3;i++) { if(i==0) mmp=mid-1; if(i==1) mmp=mid+1; if(i==2) mmp=mid*2; if(mmp>=0&&mmp<1000000&&vis[mmp]==0) { q.push(mmp); step[mmp]=step[mid]+1; vis[mmp]=1; } } } } int main() { int n,k; while(~scanf("%d %d",&n,&k)) { if(n>=k) cout<<n-k<<endl; else bfs(n,k); } }
Dungeon Master
Description:
[NWUACM]
你被困在一个三维的空间中,现在要寻找最短路径逃生!
空间由立方体单位构成
你每次向上下前后左右移动一个单位需要一分钟
你不能对角线移动并且四周封闭
是否存在逃出生天的可能性?如果存在,则需要多少时间?
Input
输入第一行是一个数表示空间的数量。
每个空间的描述的第一行为L,R和C(皆不超过30)。
L表示空间的高度。
R和C分别表示每层空间的行与列的大小。
随后L层地牢,每层R行,每行C个字符。
每个字符表示空间的一个单元。'#'表示不可通过单元,'.'表示空白单元。你的起始位置在'S',出口为'E'。
每层空间后都有一个空行。L,R和C均为0时输入结束。
Output - 输出
每个空间对应一行输出。
如果可以逃生,则输出如下
Escaped in x minute(s).
x为最短脱离时间。
如果无法逃生,则输出如下
Trapped!
Sample Input
3 4 5 S.... .###. .##.. ###.# ##### ##### ##.## ##... ##### ##### #.### ####E 1 3 3 S## #E# ### 0 0 0
Sample Output
Escaped in 11 minute(s).
Trapped!
Problem solving:
三维中的BFS,跟平常用到的差不多。不过是6个方向,上下左右前后,然后开三位数组进行BFS就好了。
Code
#include<stdio.h> #include<iostream> #include<queue> #include<cstring> using namespace std; char map[30][30][30]; int sta[30][30][30]; int base[6][3] = { {-1,0,0},{1,0,0},{0,-1,0},{0,1,0},{0,0,-1},{0,0,1} }; int L, R, C; struct Piont { int x, y, z; int step; }; struct Piont s; struct Piont e; struct Piont curp; bool success(struct Piont cur) { if (cur.x == e.x && cur.y == e.y && cur.z == e.z) return true; else return false; } bool check(int x, int y, int z) { if ((x >= 0) && (x < L) && (y >= 0) && (y < R) && (z >= 0) && (z < C) && (!sta[x][y][z]) && (map[x][y][z] == '.' || map[x][y][z] == 'E')) return true; else return false; } void bfs() { struct Piont next; queue<Piont>q; q.push(s); while (!q.empty()) { curp = q.front(); q.pop(); if (success(curp)) return; else { sta[curp.x][curp.y][curp.z] = 1; for (int i = 0; i < 6; i++) { next.x = curp.x + base[i][0]; next.y = curp.y + base[i][1]; next.z = curp.z + base[i][2]; if (check(next.x, next.y, next.z)) { next.step = curp.step + 1; sta[next.x][next.y][next.z] = 1; q.push(next); } } } } } int main() { while (scanf("%d%d%d", &L, &R, &C)) { if((L == 0) && (R == 0) && (C == 0)) break; memset(sta, 0, sizeof(sta)); for (int i = 0; i < L; i++) { getchar(); for (int j = 0; j < R; j++) { for (int k = 0; k < C; k++) { scanf("%c", &map[i][j][k]); if (map[i][j][k] == 'S') { s.x = i; s.y = j; s.z = k; s.step = 0; } else if (map[i][j][k] == 'E') { e.x = i; e.y = j; e.z = k; } } getchar(); } } bfs(); if (curp.x == e.x && curp.y == e.y && curp.z == e.z) printf("Escaped in %d minute(s).\n", curp.step); else printf("Trapped!\n"); } return 0; }
Robot Motion
Description:
A robot has been programmed to follow the instructions in its path. Instructions for the next direction the robot is to move are laid down in a grid. The possible instructions are
N north (up the page)
S south (down the page)
E east (to the right on the page)
W west (to the left on the page)
For example, suppose the robot starts on the north (top) side of Grid 1 and starts south (down). The path the robot follows is shown. The robot goes through 10 instructions in the grid before leaving the grid.
Compare what happens in Grid 2: the robot goes through 3 instructions only once, and then starts a loop through 8 instructions, and never exits.
You are to write a program that determines how long it takes a robot to get out of the grid or how the robot loops around.
Input
There will be one or more grids for robots to navigate. The data for each is in the following form. On the first line are three integers separated by blanks: the number of rows in the grid, the number of columns in the grid, and the number of the column in which the robot enters from the north. The possible entry columns are numbered starting with one at the left. Then come the rows of the direction instructions. Each grid will have at least one and at most 10 rows and columns of instructions. The lines of instructions contain only the characters N, S, E, or W with no blanks. The end of input is indicated by a row containing 0 0 0.
Output
For each grid in the input there is one line of output. Either the robot follows a certain number of instructions and exits the grid on any one the four sides or else the robot follows the instructions on a certain number of locations once, and then the instructions on some number of locations repeatedly. The sample input below corresponds to the two grids above and illustrates the two forms of output. The word "step" is always immediately followed by "(s)" whether or not the number before it is 1.
Sample Input
3 6 5
NEESWE
WWWESS
SNWWWW
4 5 1
SESWE
EESNW
NWEEN
EWSEN
0 0 0
Sample Output
10 step(s) to exit
3 step(s) before a loop of 8 step(s)
Problem solving:
这道题我是CSDN上搜的,一开始有思路不知道怎么实现。
但是我们可以发现这个里面每个点就会决定自己下一步是往哪里走,所以情况是唯一的。可以直接模拟。
这个模拟方式很巧妙地就是标记了走到任意一个位置需要的步数,如果是走出去了,直接调用中间用来存放步数的变量的值进行输出就行。如果在循环的过程中发现下一个要去到的点对应的步数的数组已经有值了就说明此时是在里面刚好转了一圈了。而转圈之前走的步数正好是从开始走走到这个点用到的步数减一,
每次转圈的长度就可以用存放步数的变量的值减去到达转圈的第一个点所需要的步数来得到(可以看着代码理解,模拟一下。
Code
#include<iostream> #include<cstdio> #include<cstring> using namespace std; char s[12][12]; int vis[12][12]; int main() { int a,b,c; while(scanf("%d %d %d",&a,&b,&c)) { if(a==0&&b==0&&c==0) break; for(int i=0;i<a;i++) for(int j=0;j<b;j++) cin>>s[i][j]; int x=0,y=c-1,step=0; memset(vis,0,sizeof(vis)); while(true) { step++; if(s[x][y]=='N'&&!vis[x][y]) { vis[x][y]=step; x--; } else if(s[x][y]=='S'&&!vis[x][y]) { vis[x][y]=step; x++; } else if(s[x][y]=='W'&&!vis[x][y]) { vis[x][y]=step; y--; } else if(s[x][y]=='E'&&!vis[x][y]) { vis[x][y]=step; y++; } if(x<0||x==a||y<0||y==b) { printf("%d step(s) to exit\n",step); break; } else if(vis[x][y]) { printf("%d step(s) before a loop of %d step(s)\n",vis[x][y]-1,step+1-vis[x][y]); break; } } } }
Number Transformation
Description:
In this problem, you are given an integer number s. You can transform any integer number A to another integer number B by adding x to A. This x is an integer number which is a prime factor of A (please note that 1 and A are not being considered as a factor of A). Now, your task is to find the minimum number of transformations required to transform s to another integer number t.
Input
Input starts with an integer T (≤ 500), denoting the number of test cases.
Each case contains two integers: s (1 ≤ s ≤ 100) and t (1 ≤ t ≤ 1000).
Output
For each case, print the case number and the minimum number of transformations needed. If it's impossible, then print -1.
Sample Input
2
6 12
6 13
Sample Output
Case 1: 2
Case 2: -1
Problem solving:
暴力解决就行,数据范围很小。
先对素数打表,然后再进行BFS查找即可。
BFS中扩展队列的方式
对输入的s,求出s的每个质因子加上它本身之后放进队列,如果出现了与t相同的情况,退出查找即可。关于特殊情况的判定我们还用A题的方式,定义一个ans变量初始值设为-1,如果出现了相等的就对ans进行更新即可。注意,如果在扩展队列的过程中遇到了之前已经出现过的数或者这个数已经大于了t,就不需要再把这个数放进队列了。
Code
#include<iostream> #include<cstdio> #include<queue> #include<cstring> #include<cmath> using namespace std; const int maxn = 2005; int p[2005]; int vis[2005]; void init() { p[1]=p[0]=1; for(int i=2;i<sqrt(maxn);i++) { for(int j=i*2;j<maxn;j+=i) p[j]=1; } } struct node{ int x,step; }; int flag; void bfs(int x,int y) { memset(vis,0,sizeof(vis)); flag=-1; queue<node> q; node now,mid; now.x=x;now.step=0; vis[x]=1; q.push(now); int ans=-1; while(!q.empty()) { now=q.front(); q.pop(); for(int i=2;i<now.x;i++) { if(now.x%i==0&&!p[i]) { mid.x=now.x+i; if(vis[mid.x]||mid.x>y) continue; vis[mid.x]=1; mid.step=now.step+1; if(mid.x==y) { flag=mid.step; return ; } q.push(mid); } } } } int main() { int n,a,b; cin>>n; init(); int cnt=1; while(n--) { int a,b; cin>>a>>b; cout<<"Case "<<cnt++<<": "; if(a==b) { puts("0"); continue; } bfs(a,b); cout<<flag<<endl; } }
Knight Moves
Description:
A friend of you is doing research on the Traveling Knight Problem (TKP) where you are to find the shortest closed tour of knight moves that visits each square of a given set of n squares on a chessboard exactly once. He thinks that the most difficult part of the problem is determining the smallest number of knight moves between two given squares and that, once you have accomplished this, finding the tour would be easy.
Of course you know that it is vice versa. So you offer him to write a program that solves the "difficult" part.
Your job is to write a program that takes two squares a and b as input and then determines the number of knight moves on a shortest route from a to b.
Input
The input file will contain one or more test cases. Each test case consists of one line containing two squares separated by one space. A square is a string consisting of a letter (a-h) representing the column and a digit (1-8) representing the row on the chessboard.
Output
For each test case, print one line saying "To get from xx to yy takes n knight moves.".
Sample Input
e2 e4
a1 b2
b2 c3
a1 h8
a1 h7
h8 a1
b1 c3
f6 f6
Sample Output
To get from e2 to e4 takes 2 knight moves.
To get from a1 to b2 takes 4 knight moves.
To get from b2 to c3 takes 2 knight moves.
To get from a1 to h8 takes 6 knight moves.
To get from a1 to h7 takes 5 knight moves.
To get from h8 to a1 takes 6 knight moves.
To get from b1 to c3 takes 1 knight moves.
To get from f6 to f6 takes 0 knight moves.
Problem solving:
这道题就是一道简单的BFS模板题,只不过题不太好懂,这里我找到一张图可以参考一下。
就是马走日的问题,分8个方向进行查找即可。
Code
#include<iostream> #include<cstdio> #include<cstring> #include<queue> using namespace std; int vis[10][10],sx,sy,ex,ey; struct node{ int x,y,step; }; int d[8][2]={-2,-1, -1,-2, 1,-2, 2,-1, 2,1, 1,2, -1,2, -2,1}; int bfs(int x,int y) { memset(vis,0,sizeof(vis)); queue<node> que; vis[x][y]=1; node now,mid; now.x=x;now.y=y;now.step=0; que.push(now); while(!que.empty()) { now=que.front();que.pop(); if(now.x==ex&&now.y==ey) { return now.step; } for(int i=0;i<8;i++) { mid.x=now.x+d[i][0]; mid.y=now.y+d[i][1]; if(mid.x<=0||mid.x>8||mid.y<=0||mid.y>8||vis[mid.x][mid.y]) continue; vis[mid.x][mid.y]=1; mid.step=now.step+1; que.push(mid); } } } int main() { char a[3],b[3]; while(~scanf("%s %s",a,b)) { int m; sx=a[0]-'a'+1;sy=a[1]-'0';ex=b[0]-'a'+1;ey=b[1]-'0'; // cout<<sx<<sy<<ex<<ey<<endl; m=bfs(sx,sy); cout<<"To get from "<<a<<" to "<<b<<" takes "<<m<<" knight moves."<<endl; } } //To get from e2 to e4 takes 2 knight moves.