kuangbin带你飞——专题一简单搜索

1-1 棋盘问题

问题

在一个给定形状的棋盘(形状可能是不规则的)上面摆放棋子,棋子没有区别。要求摆放时任意的两个棋子不能放在棋盘中的同一行或者同一列,请编程求解对于给定形状和大小的棋盘,摆放k个棋子的所有可行的摆放方案C。

输入

输入含有多组测试数据。
每组数据的第一行是两个正整数,n k,用一个空格隔开,表示了将在一个n*n的矩阵内描述棋盘,以及摆放棋子的数目。 n <= 8 , k <= n
当为-1 -1时表示输入结束。
随后的n行描述了棋盘的形状:每行有n个字符,其中 # 表示棋盘区域, . 表示空白区域(数据保证不出现多余的空白行或者空白列)。

输出

对于每一组数据,给出一行输出,输出摆放的方案数目C (数据保证C<2^31)。

样例输入

2 1
#.
.#
4 4
…#
…#.
.#…
#…
-1 -1

样例输出

2
1

思路

类似于八皇后,但不一定选择某一行满足条件的位置;
采用递归的方式思路很清晰,编写也简单。(尝试编写非递归代码失败)

源码

/*
* problem:棋盘问题
* method:dfs、八皇后
* date:
*/
#include<iostream>
#include<utility>
#define ll long long
using namespace std;
typedef pair<int,int> P;
const int maxn=9;
char maze[maxn][maxn];
P queen[maxn];
int col[maxn];
int n,k,sum;
void dfs(int i,int num) {
	if(num==k){
		sum++;
		return;
	}
	if(i<n){
		for(int j=0;j<n;j++){
			if(maze[i][j]=='#'&&col[j]==0){
				col[j]=1;
				dfs(i+1,num+1);
				col[j]=0;
			}
		}
		dfs(i+1,num);
	}
}
int main() {
	int i,j;
	while(cin>>n>>k) {
		if(n==-1&&k==-1) break;
		for(i=0; i<n; i++) {
			for(j=0; j<n; j++) {
				cin>>maze[i][j];
			}
			col[i]=0;
		}
		sum=0;
		dfs(0,0);
		cout<<sum<<endl;
	}
	return 0;
}

1-2 Dungeon Master

问题

You are trapped in a 3D dungeon and need to find the quickest way out! The dungeon is composed of unit cubes which may or may not be filled with rock. It takes one minute to move one unit north, south, east, west, up or down. You cannot move diagonally and the maze is surrounded by solid rock on all sides.
Is an escape possible? If yes, how long will it take?

输入

The input consists of a number of dungeons. Each dungeon description starts with a line containing three integers L, R and C (all limited to 30 in size).
L is the number of levels making up the dungeon.
R and C are the number of rows and columns making up the plan of each level.
Then there will follow L blocks of R lines each containing C characters. Each character describes one cell of the dungeon. A cell full of rock is indicated by a ‘#’ and empty cells are represented by a ‘.’. Your starting position is indicated by ‘S’ and the exit by the letter ‘E’. There’s a single blank line after each level. Input is terminated by three zeroes for L, R and C.

输出

Each maze generates one line of output. If it is possible to reach the exit, print a line of the form
Escaped in x minute(s).
where x is replaced by the shortest time it takes to escape.
If it is not possible to escape, print the line
Trapped!

样例输入

3 4 5
S…
.###.
.##…
###.#

##.##
##…

#.###
####E

1 3 3
S##
#E#

0 0 0

样例输出

Escaped in 11 minute(s).
Trapped!

思路

三维的迷宫寻路
源码

/*
* problem:Dungeon Master
* method:bfs、三维的迷宫寻路
* date:
*/
#include<iostream>
#include<queue>
#define ll long long
using namespace std;
const int INF=1e8;
const int maxn=35;
struct P {
	int x,y,z;
	P() {}
	P(int a,int b,int c):x(a),y(b),z(c) {}
};
int L,R,C,sx,sy,sz,ex,ey,ez;
char maze[maxn][maxn][maxn];
int d[maxn][maxn][maxn];
const int dx[]= {1,-1,0,0,0,0};
const int dy[]= {0,0,1,-1,0,0};
const int dz[]= {0,0,0,0,1,-1};
void bfs() {
	int i,j,k;
	int flag=0;
	queue<P> Q;
	Q.push(P(sx,sy,sz));
	d[sx][sy][sz]=0;
	while(!Q.empty()) {
		int nx,ny,nz;
		P p=Q.front();
		Q.pop();
		for(i=0; i<8; i++) {
			nx=p.x+dx[i];
			ny=p.y+dy[i];
			nz=p.z+dz[i];
			if(nx>=0&&nx<L&&ny>=0&&ny<R&&nz>=0&&nz<C&&maze[nx][ny][nz]=='.'&&d[nx][ny][nz]==INF) {
				d[nx][ny][nz]=d[p.x][p.y][p.z]+1;
				Q.push(P(nx,ny,nz));
				if(nx==ex&&ny==ey&&nz==ez) {
					flag=1;
					break;
				}
			}
		}
	}
	if(flag) {
		cout<<"Escaped in "<<d[ex][ey][ez]<<" minute(s)."<<endl;
	} else {
		cout<<"Trapped!"<<endl;
	}
}
int main() {
	int i,j,k;
	while(cin>>L>>R>>C) {
		if(L==0||R==0||C==0) break;
		for(i=0; i<L; i++) {
			for(j=0; j<R; j++) {
				for(k=0; k<C; k++) {
					cin>>maze[i][j][k];
					if(maze[i][j][k]=='S') {
						sx=i;
						sy=j;
						sz=k;
						maze[i][j][k]='.';
					} else if(maze[i][j][k]=='E') {
						ex=i;
						ey=j;
						ez=k;
						maze[i][j][k]='.';
					}
					d[i][j][k]=INF;
				}
			}
		}
		bfs();
	}
	return 0;
}

1-3 Catch That Cow

问题

Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a point N (0 ≤ N ≤ 100,000) on a number line and the cow is at a point K (0 ≤ K ≤ 100,000) on the same number line. Farmer John has two modes of transportation: walking and teleporting.

  • Walking: FJ can move from any point X to the points X - 1 or X + 1 in a single minute
  • Teleporting: FJ can move from any point X to the point 2 × X in a single minute.

If the cow, unaware of its pursuit, does not move at all, how long does it take for Farmer John to retrieve it?

输入

Line 1: Two space-separated integers: N and K

输出

Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.

样例输入

5 17

样例输出

4

思路

一维bfs+dp

源码

/*
* problem:Catch That Cow
* method:bfs
* date:
*/
#include<iostream>
#include<string>
#include<queue>
#define ll long long
using namespace std;
const int inf=99999999;
int N,K;
int d[100005];
void bfs() {
	int i,j;
	for(i=0; i<100005; i++) {
		d[i]=inf;
	}
	queue<int> Q;
	Q.push(N);
	d[N]=0;
	if(N==K) return;
	while(!Q.empty()) {
		int now=Q.front();
		Q.pop();
		int next[3];
		next[0]=now+1;
		next[1]=now-1;
		next[2]=now*2;
		for(int i=0; i<3; i++) {
			if(next[i]>=0&&next[i]<=100000) {
				if(d[next[i]]>d[now]+1) {
					d[next[i]]=d[now]+1;
					Q.push(next[i]);
					if(next[i]==K) return;
				}
			}
		}
	}
}
int main() {
	cin>>N>>K;
	bfs();
	cout<<d[K]<<endl;
	return 0;
}

1-4 Fliptile

问题

Farmer John knows that an intellectually satisfied cow is a happy cow who will give more milk. He has arranged a brainy activity for cows in which they manipulate an M × N grid (1 ≤ M ≤ 15; 1 ≤ N ≤ 15) of square tiles, each of which is colored black on one side and white on the other side.

As one would guess, when a single white tile is flipped, it changes to black; when a single black tile is flipped, it changes to white. The cows are rewarded when they flip the tiles so that each tile has the white side face up. However, the cows have rather large hooves and when they try to flip a certain tile, they also flip all the adjacent tiles (tiles that share a full edge with the flipped tile). Since the flips are tiring, the cows want to minimize the number of flips they have to make.

Help the cows determine the minimum number of flips required, and the locations to flip to achieve that minimum. If there are multiple ways to achieve the task with the minimum amount of flips, return the one with the least lexicographical ordering in the output when considered as a string. If the task is impossible, print one line with the word “IMPOSSIBLE”.

输入

Line 1: Two space-separated integers: M and N
Lines 2…M+1: Line i+1 describes the colors (left to right) of row i of the grid with N space-separated integers which are 1 for black and 0 for white

输出

Lines 1…M: Each line contains N space-separated integers, each specifying how many times to flip that particular location.

样例输入

4 4
1 0 0 1
0 1 1 0
0 1 1 0
1 0 0 1

样例输出

0 0 0 0
1 0 0 1
1 0 0 1
0 0 0 0

思路

第一行的n个格子的决策决定后,后面每行的最佳决策是固定的,因此只需遍历第一行的2n种情况

源码

/*
* problem:Fliptile
* method:dfs+状态压缩
* date:2020/08/07
*/
#include<iostream>
#include<vector>
#include<queue>
#include<stack>
#include<utility>
#include<cmath>
#define ll long long
using namespace std;
const int inf=1e8;
const int maxn=20;
const int dx[4]= {-1,1,0,0};
const int dy[4]= {0,0,-1,1};
int ori[maxn][maxn],test[maxn][maxn];
int ans[maxn][maxn],res[maxn][maxn];
int m,n,minRes,flag;
void turnOver(int x,int y) {
	ans[x][y]++;
	test[x][y]=test[x][y]==1?0:1;
	int nx,ny;
	for(int i=0; i<4; i++) {
		nx=x+dx[i];
		ny=y+dy[i];
		if(nx>=0&&nx<m&&ny>=0&&ny<n) {
			test[nx][ny]=test[nx][ny]==1?0:1;
		}
	}
}
void dfs(int k) {
	int i,j;
	if(k==m) {
		for(i=0; i<n; i++) {
			if(test[k-1][i]==1) return;
		}
		flag=1;
		int temp=0;
		for(i=0; i<m; i++) {
			for(j=0; j<n; j++) {
				if(ans[i][j]==1) temp++;
			}
		}
		if(temp<minRes) {
			minRes=temp;
			for(i=0; i<m; i++) {
				for(j=0; j<n; j++) {
					res[i][j]=ans[i][j];
				}
			}
		}
		return;
	}
	for(i=0; i<n; i++) {
		if(test[k-1][i]==1) turnOver(k,i);
	}
	dfs(k+1);
}
int main() {
	int i,j;
	cin>>m>>n;
	for(i=0; i<m; i++) {
		for(j=0; j<n; j++) {
			cin>>ori[i][j];
		}
	}
	flag=0;
	minRes=inf;
	for(i=0; i<1<<n; i++) {
		for(j=0; j<m; j++) {
			for(int k=0; k<n; k++) {
				test[j][k]=ori[j][k];
				ans[j][k]=0;
			}
		}
		for(j=0; j<n; j++) {
			if(i&1<<j) turnOver(0,j);
		}
		dfs(1);
	}
	if(flag) {
		for(i=0; i<m; i++) {
			for(j=0; j<n; j++) {
				cout<<res[i][j]<<' ';
			}
			cout<<endl;
		}
	} else {
		cout<<"IMPOSSIBLE"<<endl;
	}
	return 0;
}

1-5 Find The Multiple

问题

Given a positive integer n, write a program to find out a nonzero multiple m of n whose decimal representation contains only the digits 0 and 1. You may assume that n is not greater than 200 and there is a corresponding m containing no more than 100 decimal digits.

输入

The input file may contain multiple test cases. Each line contains a value of n (1 <= n <= 200). A line containing a zero terminates the input.

输出

For each value of n in the input print a line containing the corresponding value of m. The decimal representation of m must not contain more than 100 digits. If there are multiple solutions for a given value of n, any one of them is acceptable.

样例输入

2
6
19
0

样例输出

10
100100100100100100
111111111111111111

思路

bfs逐位增加搜索

源码

/*
* problem:Find The Mutiple
* method:bfs
* date:
*/
#include<iostream>
#include<vector>
#include<queue>
#include<stack>
#include<utility>
#include<cmath>
#define ll long long
using namespace std;
int n;
void bfs(){
	queue<unsigned long long> Q;
	Q.push(1);
	while(!Q.empty()){
		unsigned long long m=Q.front();
		Q.pop();
		if(m%n==0){
			cout<<m<<endl;
			break;
		}
		Q.push(m*10);
		Q.push(m*10+1);
	}
}
int main(){
	int i,j,k;
	while(cin>>n){
		if(n==0) break;
		bfs();
	}
	return 0;
}

1-6 Prime Path

问题

The ministers of the cabinet were quite upset by the message from the Chief of Security stating that they would all have to change the four-digit room numbers on their offices.
— It is a matter of security to change such things every now and then, to keep the enemy in the dark.
— But look, I have chosen my number 1033 for good reasons. I am the Prime minister, you know!
— I know, so therefore your new number 8179 is also a prime. You will just have to paste four new digits over the four old ones on your office door.
— No, it’s not that simple. Suppose that I change the first digit to an 8, then the number will read 8033 which is not a prime!
— I see, being the prime minister you cannot stand having a non-prime number on your door even for a few seconds.
— Correct! So I must invent a scheme for going from 1033 to 8179 by a path of prime numbers where only one digit is changed from one prime to the next prime.

Now, the minister of finance, who had been eavesdropping, intervened.
— No unnecessary expenditure, please! I happen to know that the price of a digit is one pound.
— Hmm, in that case I need a computer program to minimize the cost. You don’t know some very cheap software gurus, do you?
— In fact, I do. You see, there is this programming contest going on… Help the prime minister to find the cheapest prime path between any two given four-digit primes! The first digit must be nonzero, of course. Here is a solution in the case above.
1033
1733
3733
3739
3779
8779
8179
The cost of this solution is 6 pounds. Note that the digit 1 which got pasted over in step 2 can not be reused in the last step – a new 1 must be purchased.

输入

One line with a positive number: the number of test cases (at most 100). Then for each test case, one line with two numbers separated by a blank. Both numbers are four-digit primes (without leading zeros).

输出

One line for each case, either with a number stating the minimal cost or containing the word Impossible.

样例输入

3
1033 8179
1373 8017
1033 1033

样例输出

6
7
0

思路

逐位bfs搜索满足条件的数

源码

/*
* problem:Prime Path
* method:bfs
* date:2020/08/03
*/
#include<iostream>
#include<cmath>
#include<queue>
#define ll long long
using namespace std;
const int maxn=10005;
const int inf=1e6;
bool isprime[maxn],vis[maxn];
int dp[maxn];
int T,x,y,flag;
int getnext(int now,int index,int x) {
	int a,res;
	a=(now%(int)pow(10.0,index+1))/pow(10.0,index);
	res=now+(x-a)*pow(10.0,index);
	return res;
}
void sieve() {
	int i;
	for(i=0; i<maxn; i++) isprime[i]=true;
	isprime[0]=false;
	isprime[1]=false;
	for(i=2; i<maxn; i++) {
		if(isprime[i]) {
			for(int j=2; j*i<maxn; j++) {
				isprime[i*j]=false;
			}
		}
	}
}
void init() {
	int i,j;
	for(i=0; i<maxn; i++) {
		dp[i]=inf;
		vis[i]=false;
	}
}
void bfs() {
	int i,j;
	queue<int> Q;
	Q.push(x);
	vis[x]=true;
	dp[x]=0;
	while(!Q.empty()) {
		int now=Q.front();
		Q.pop();
		if(now==y) {
			flag=1;
			cout<<dp[y]<<endl;
			break;
		}
		for(i=0; i<4; i++) {
			for(j=0; j<=9; j++) {
				if(i==3&&j==0) continue;
				int next=getnext(now,i,j);
				if(!vis[next]&&isprime[next]) {
					vis[next]=1;
					dp[next]=dp[now]+1;
					Q.push(next);
				}
			}
		}
	}
}
int main() {
	cin>>T;
	sieve();
	while(T--) {
		init();
		cin>>x>>y;
		flag=0;
		bfs();
		if(!flag) cout<<"Impossible"<<endl;
	}
	return 0;
}

1-7 Shuffle’m Up

问题
在这里插入图片描述

输入

The first line of input contains a single integer N, (1 ≤ N ≤ 1000) which is the number of datasets that follow.

Each dataset consists of four lines of input. The first line of a dataset specifies an integer C, (1 ≤ C ≤ 100) which is the number of chips in each initial stack (S1 and S2). The second line of each dataset specifies the colors of each of the C chips in stack S1, starting with the bottommost chip. The third line of each dataset specifies the colors of each of the C chips in stack S2 starting with the bottommost chip. Colors are expressed as a single uppercase letter (A through H). There are no blanks or separators between the chip colors. The fourth line of each dataset contains 2 * C uppercase letters (A through H), representing the colors of the desired result of the shuffling of S1 and S2 zero or more times. The bottommost chip’s color is specified first.

输出

Output for each dataset consists of a single line that displays the dataset number (1 though N), a space, and an integer value which is the minimum number of shuffle operations required to get the desired resultant stack. If the desired result can not be reached using the input for the dataset, display the value negative 1 (−1) for the number of shuffle operations.

样例输入

2
4
AHAH
HAHA
HHAAAAHH
3
CDE
CDE
EEDDCC

样例输出

1 2
2 -1

思路

简单模拟

源码

/*
* problem:Shuffle'm Up
* method:模拟、string
* date:2020/08/07
*/
#include<iostream>
#include<string>
#include<vector>
#include<queue>
#include<stack>
#include<utility>
#include<cmath>
#define ll long long
using namespace std;
int t,c,cnt,flag;
string os1,os2,res;
int main() {
	int i,j;
	cin>>t;
	for(i=0; i<t; i++) {
		cin>>c;
		cin>>os1>>os2>>res;
		string s1=os1,s2=os2,ns;
		flag=1;
		cnt=0;
		do {
			cnt++;
			ns="";
			for(j=0; j<c; j++) {
				ns+=s2[j];
				ns+=s1[j];
			}
			s1=ns.substr(0,c);
			s2=ns.substr(c);
			if(s1==os1&&s2==os2) {
				flag=0;
				break;
			}
		} while(ns!=res);
		if(flag==1) cout<<i+1<<" "<<cnt<<endl;
		else cout<<i+1<<" -1"<<endl;;
	}
	return 0;
}

1-8 Pots

问题

You are given two pots, having the volume of A and B liters respectively. The following operations can be performed:

  • FILL(i) fill the pot i (1 ≤ i ≤ 2) from the tap;
  • DROP(i) empty the pot i to the drain;
  • POUR(i,j) pour from pot i to pot j;
    after this operation either the pot j is full (and there may be some water left in the pot i), or the pot i is empty (and all its contents have been moved to the pot j).
    Write a program to find the shortest possible sequence of these operations that will yield exactly C liters of water in one of the pots.

输入

On the first and only line are the numbers A, B, and C. These are all integers in the range from 1 to 100 and C≤max(A,B).

输出

The first line of the output must contain the length of the sequence of operations K. The following K lines must each describe one operation. If there are several sequences of minimal length, output any one of them. If the desired result can’t be achieved, the first and only line of the file must contain the word ‘impossible’.

样例输入

3 5 4

样例输出

6
FILL(2)
POUR(2,1)
DROP(1)
POUR(2,1)
FILL(2)
POUR(2,1)

思路

bfs搜索更新状态

源码

/*
* problem:Pots
* method:bfs+回溯
* date:2020/08/02
*/
#include<iostream>
#include<queue>
#include<vector>
#include<stack>
#include<string>
#define ll long long
using namespace std;
const int maxn=105;
struct state {
	int id,pre;
	int a,b;
	int step,cnt;
	state() {}
	state(int a,int b,int step,int cnt,int id,int pre):a(a),b(b),step(step),cnt(cnt),id(id),pre(pre) {}
};
int vis[maxn][maxn]= {0};
string ope[]= {"FILL(1)","FILL(2)","DROP(1)",
               "DROP(2)","POUR(1,2)","POUR(2,1)"
              };
int a,b,c,flag;
void bfs() {
	vector<state> arr;
	queue<state> Q;
	state s=state(0,0,-1,0,0,-1);
	arr.push_back(s);
	Q.push(s);
	vis[0][0]=1;
	int cnt=1;
	while(!Q.empty()) {
		state now=Q.front();
	//	cout<<now.a<<" "<<now.b<<endl;
		Q.pop();
		if(now.a==c||now.b==c) {
			flag=1;
			cout<<now.cnt<<endl;
			stack<int> res;
			int id=now.id;
			while(id!=0) {
				res.push(arr[id].step);
				id=arr[id].pre;
			}
			while(!res.empty()) {
				int step=res.top();
				res.pop();
				cout<<ope[step]<<endl;
			}
			break;
		}
		if(vis[a][now.b]==0) { //FILL(1)
			state n(a,now.b,0,now.cnt+1,cnt,now.id);
			cnt++;
			arr.push_back(n);
			Q.push(n);
			vis[a][now.b]=1;
		}
		if(vis[now.a][b]==0) { //FILL(2)
			state n(now.a,b,1,now.cnt+1,cnt,now.id);
			cnt++;
			arr.push_back(n);
			Q.push(n);
			vis[now.a][b]=1;
		}
		if(vis[0][now.b]==0) { //DROP(1)
			state n(0,now.b,2,now.cnt+1,cnt,now.id);
			cnt++;
			arr.push_back(n);
			Q.push(n);
			vis[0][now.b]=1;
		}
		if(vis[now.a][0]==0) { //DROP(2)
			state n(now.a,0,3,now.cnt+1,cnt,now.id);
			cnt++;
			arr.push_back(n);
			Q.push(n);
			vis[now.a][0]=1;
		}
		int s=now.a+now.b;
		int anext,bnext;
		if(now.a!=0&&now.b!=b) { //POUR(1,2)
			if(s>b) anext=s-b,bnext=b;
			else anext=0,bnext=s;
			if(vis[anext][bnext]==0) {
				state n(anext,bnext,4,now.cnt+1,cnt,now.id);
				cnt++;
				arr.push_back(n);
				Q.push(n);
				vis[anext][bnext]=1;
			}
		}
		if(now.a!=a&&now.b!=0) { //POUR(2,1)
			if(s>a) anext=a,bnext=s-a;
			else anext=s,bnext=0;
			if(vis[anext][bnext]==0) {
				state n(anext,bnext,5,now.cnt+1,cnt,now.id);
				cnt++;
				arr.push_back(n);
				Q.push(n);
				vis[anext][bnext]=1;
			}
		}

	}
}
int main() {
	cin>>a>>b>>c;
	flag=0;
	bfs();
	if(flag==0) cout<<"impossible"<<endl;
	return 0;
}

1-9 Fire Game

问题

Fat brother and Maze are playing a kind of special (hentai) game on an N*M board (N rows, M columns). At the beginning, each grid of this board is consisting of grass or just empty and then they start to fire all the grass. Firstly they choose two grids which are consisting of grass and set fire. As we all know, the fire can spread among the grass. If the grid (x, y) is firing at time t, the grid which is adjacent to this grid will fire at time t+1 which refers to the grid (x+1, y), (x-1, y), (x, y+1), (x, y-1). This process ends when no new grid get fire. If then all the grid which are consisting of grass is get fired, Fat brother and Maze will stand in the middle of the grid and playing a MORE special (hentai) game. (Maybe it’s the OOXX game which decrypted in the last problem, who knows.)

You can assume that the grass in the board would never burn out and the empty grid would never get fire.

Note that the two grids they choose can be the same.

输入

The first line of the date is an integer T, which is the number of the text cases.

Then T cases follow, each case contains two integers N and M indicate the size of the board. Then goes N line, each line with M character shows the board. “#” Indicates the grass. You can assume that there is at least one grid which is consisting of grass in the board.

1 <= T <=100, 1 <= n <=10, 1 <= m <=10

输出

For each case, output the case number first, if they can play the MORE special (hentai) game (fire all the grass), output the minimal time they need to wait after they set fire, otherwise just output -1. See the sample input and output for more details.

样例输入

4
3 3
.#.

.#.
3 3
.#.
#.#
.#.
3 3

#.#

3 3

…#
#.#

样例输出

Case 1: 1
Case 2: -1
Case 3: 0
Case 4: 2

思路

遍历所有组合每次进行bfs

源码

/*
* problem: Fire Game
* method:bfs
* date:
*/
#include<iostream>
#include<queue>
#include<utility>
#define ll long long
using namespace std;
typedef pair<int,int> P;
const int inf=1e8;
const int maxn=205;
char maze[maxn][maxn];
int dp[2][maxn][maxn];
bool vis[2][maxn][maxn];
int dx[]={-1,1,0,0};
int dy[]={0,0,-1,1};
int m,n,x,y,min=0;
P Y,M;
void init(){
	int i,j,k;
	for(i=0;i<2;i++){
		for(j=0;j<n;j++){
			for(k=0;k<m;k++){
				dp[i][j][k]=inf;
				vis[i][j][k]=false;
			}
		}
	}
}
void bfs(P start,int i){
	queue<P> Q;
	Q.push(start);
	dp[i][start.first][start.second]=0;
	vis[i][start.first][start.second]=true;
	while(!Q.empty()){
		P now=Q.front();
		Q.pop();
		for(int j=0;j<4;j++){
			int nx,ny;
			nx=now.first+dx[j];
			ny=now.second+dy[j];
			//cout<<nx<<' '<<ny<<endl;
			if(nx>=0&&nx<n&&ny>=0&&ny<m&&maze[nx][ny]!='#'&&!vis[i][nx][ny]){
				dp[i][nx][ny]=dp[i][now.first][now.second]+1;
				vis[i][nx][ny]=true;
				Q.push(P(nx,ny));
			}
		}
	}
}
int main(){
	int i,j;
	while(cin>>n>>m){
		for(i=0;i<n;i++){
			for(j=0;j<m;j++){
				cin>>maze[i][j];
				if(maze[i][j]=='Y'){
					Y.first=i;
					Y.second=j;
				}else if(maze[i][j]=='M'){
					M.first=i;
					M.second=j;
				}
			}
		}
		init();
		bfs(Y,0);
		bfs(M,1);
		int min=inf;
		for(i=0;i<n;i++){
			for(j=0;j<m;j++){
				//cout<<dp[0][i][j]<<" ";
				if(maze[i][j]=='@'){
					int t=dp[0][i][j]+dp[1][i][j];
					min=min<t?min:t;
				}
			}
			//cout<<endl;
		}
		cout<<min*11<<endl;
	}
	return 0;
}

1-10 Fire!

在这里插入图片描述

思路

两次bfs

源码

/*
* problem: Fire
* method:两次bfs
* date:
*/
#include<iostream>
#include<vector>
#include<queue>
#include<stack>
#include<utility>
#include<cmath>
#define ll long long
using namespace std;
typedef pair<int,int> P;
const int maxn=1005;
const int inf=1e8;
const int dx[]= {-1,1,0,0};
const int dy[]= {0,0,-1,1};
char maze[maxn][maxn];
int dp[2][maxn][maxn];
bool vis[2][maxn][maxn];
P J;
queue<P> F;
int T,R,C;
int i,j,k;
void init() {
	for(i=0; i<2; i++) {
		for(j=0; j<R; j++) {
			for(k=0; k<C; k++) {
				dp[i][j][k]=inf;
				vis[i][j][k]=false;
			}
		}
	}
}
void bfs(int index) {
	queue<P> Q;
	if(index==1) {
		Q.push(J);
		dp[index][J.first][J.second]=0;
		vis[index][J.first][J.second]=true;
	} else if(index==0) {
		while(!F.empty()) {
			P p=F.front();
			F.pop();
			Q.push(p);
			dp[index][p.first][p.second]=0;
			vis[index][p.first][p.second]=true;
		}
	}
	while(!Q.empty()) {
		P now=Q.front();
		//cout<<now.first<<" "<<now.second<<endl;
		Q.pop();
		int nx,ny;
		for(i=0; i<4; i++) {
			nx=now.first+dx[i];
			ny=now.second+dy[i];
			if(nx>=0&&nx<R&&ny>=0&&ny<C&&maze[nx][ny]!='#'&&!vis[index][nx][ny]) {
				dp[index][nx][ny]=dp[index][now.first][now.second]+1;
				vis[index][nx][ny]=true;
				Q.push(P(nx,ny));
			}
		}
	}
}
int main() {
	cin>>T;
	while(T--) {
		init();
		cin>>R>>C;
		for(i=0; i<R; i++) {
			for(j=0; j<C; j++) {
				cin>>maze[i][j];
				if(maze[i][j]=='J') {
					J.first=i;
					J.second=j;
				} else if(maze[i][j]=='F') {
					F.push(P(i,j));
				}
			}
		}
		bfs(0);
		bfs(1);
		int flag=0,min=inf;
		for(i=0; i<R; i++) {
			for(j=0; j<C; j++) {
				if(i==0||i==R-1||j==0||j==C-1) {
					if(dp[1][i][j]<dp[0][i][j]) {
						flag=1;
						min=min<dp[1][i][j]?min:dp[1][i][j];
					}
				}
				//cout<<dp[1][i][j]<<" ";
			}
			//cout<<endl;
		}
		if(flag&&min!=inf) cout<<min+1<<endl;
		else cout<<"IMPOSSIBLE"<<endl;
	}
	return 0;
}

1-11 迷宫问题

问题

定义一个二维数组:

int maze[5][5] = {

0, 1, 0, 0, 0,

0, 1, 0, 1, 0,

0, 0, 0, 0, 0,

0, 1, 1, 1, 0,

0, 0, 0, 1, 0,

};

它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。

输入

一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。

输出

左上角到右下角的最短路径,格式如样例所示。

样例输入

0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0

样例输出

(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)

思路

bfs+回溯
源码

/*
* problem: 迷宫问题
* method: bfs+回溯
* date:
*/
#include<iostream>
#include<queue>
#include<stack>
#include<utility>
#define ll long long
using namespace std;
const int maxn=5;
const int INF=1e8;
typedef pair<int,int> P;
int maze[maxn][maxn],d[maxn][maxn];
const int dx[]= {1,-1,0,0};
const int dy[]= {0,0,-1,1};
void bfs(int x,int y) {
	int i,j;
	for(i=0; i<maxn; i++) {
		for(j=0; j<maxn; j++) {
			d[i][j]=INF;
		}
	}
	queue<P> Q;
	Q.push(P(x,y));
	d[x][y]=0;
	while(!Q.empty()) {
		P p=Q.front();
		Q.pop();
		for(i=0; i<4; i++) {
			int nx,ny;
			nx=p.first+dx[i];
			ny=p.second+dy[i];
			if(nx>=0&&ny>=0&&nx<maxn&&ny<maxn&&maze[nx][ny]==0&&d[nx][ny]==INF) {
				d[nx][ny]=d[p.first][p.second]+1;
				Q.push(P(nx,ny));
			}
		}
	}
}
void back() {
	stack<P> road;
	int len=d[maxn-1][maxn-1];
	road.push(P(maxn-1,maxn-1));
	while(len!=-1) {
		len--;
		P p=road.top();
		for(int i=0; i<4; i++) {
			int x=p.first+dx[i],y=p.second+dy[i];
			if(x>=0&&y>=0&&x<maxn&&y<maxn&&d[x][y]==len) {
				road.push(P(x,y));
				break;
			}
		}
	}
	while(!road.empty()) {
		P p=road.top();
		road.pop();
		cout<<"("<<p.first<<", "<<p.second<<")"<<endl;
	}
}
int main() {
	int i,j;
	for(i=0; i<maxn; i++) {
		for(j=0; j<maxn; j++) {
			cin>>maze[i][j];
		}
	}
	int x=0,y=0;
	bfs(x,y);
	back();
	return 0;
}

1-12 Oil Deposits

问题

The GeoSurvComp geologic survey company is responsible for detecting underground oil deposits. GeoSurvComp works with one large rectangular region of land at a time, and creates a grid that divides the land into numerous square plots. It then analyzes each plot separately, using sensing equipment to determine whether or not the plot contains oil. A plot containing oil is called a pocket. If two pockets are adjacent, then they are part of the same oil deposit. Oil deposits can be quite large and may contain numerous pockets. Your job is to determine how many different oil deposits are contained in a grid.

输入

The input file contains one or more grids. Each grid begins with a line containing m and n, the number of rows and columns in the grid, separated by a single space. If m = 0 it signals the end of the input; otherwise 1 <= m <= 100 and 1 <= n <= 100. Following this are m lines of n characters each (not counting the end-of-line characters). Each character corresponds to one plot, and is either ‘*’, representing the absence of oil, or `@’, representing an oil pocket.

输出

For each grid, output the number of distinct oil deposits. Two different pockets are part of the same oil deposit if they are adjacent horizontally, vertically, or diagonally. An oil deposit will not contain more than 100 pockets.

样例输入

1 1
*
3 5
@@*
@
@@*
1 8
@@***@
5 5
****@
@@@
@**@
@@@
@
@@**@
0 0

样例输出

0
1
2
2

思路

dfs找分割集
源码

/*
* problem: Oil Deposits
* method: dfs找分割集
* date:
*/
#include<iostream>
#include<utility>
#include<stack>
#define ll long long
using namespace std;
typedef pair<int,int> P;
const int maxn=105;
const int dx[]= {-1,0,1,1,1,0,-1,-1};
const int dy[]= {-1,-1,-1,0,1,1,1,0};
int m,n;
char maze[maxn][maxn];
void dfs(int x,int y) {
	stack<P> S;
	maze[x][y]='*';
	S.push(P(x,y));
	while(!S.empty()) {
		P p=S.top();
		S.pop();
		int x=p.first,y=p.second;
		for(int i=0; i<8; i++) {
			int nx,ny;
			nx=x+dx[i];
			ny=y+dy[i];
			if(nx>=0&&nx<m&&ny>=0&&ny<n&&maze[nx][ny]=='@') {
				maze[nx][ny]='*';
				S.push(P(nx,ny));
			}
		}
	}
}
int main() {
	int i,j;
	while(cin>>m>>n) {
		if(m==0||n==0) break;
		int i,j;
		for(i=0; i<m; i++) {
			for(j=0; j<n; j++) {
				cin>>maze[i][j];
			}
		}
		int cnt=0;
		for(i=0; i<m; i++) {
			for(j=0; j<n; j++) {
				if(maze[i][j]=='@') {
					dfs(i,j);
					cnt++;
				}
			}
		}
		cout<<cnt<<endl;
	}
	return 0;
}

1-13 非常可乐

问题

大家一定觉的运动以后喝可乐是一件很惬意的事情,但是seeyou却不这么认为。因为每次当seeyou买了可乐以后,阿牛就要求和seeyou一起分享这一瓶可乐,而且一定要喝的和seeyou一样多。但seeyou的手中只有两个杯子,它们的容量分别是N 毫升和M 毫升 可乐的体积为S (S<101)毫升 (正好装满一瓶) ,它们三个之间可以相互倒可乐 (都是没有刻度的,且 S==N+M,101>S>0,N>0,M>0) 。聪明的ACMER你们说他们能平分吗?如果能请输出倒可乐的最少的次数,如果不能输出"NO"。

输入

三个整数 : S 可乐的体积 , N 和 M是两个杯子的容量,以"0 0 0"结束。

输出

如果能平分的话请输出最少要倒的次数,否则输出"NO"。

样例输入

7 4 3
4 1 3
0 0 0

样例输出

NO
3

思路

bfs逐步寻找目标状态

源码

/*
* problem:非常可乐
* method:bfs
* date:2020/08/02
*/
#include<iostream>
#include<queue>
#include<queue>
#define ll long long
using namespace std;
struct state {
	int s,n,m;
	int step;
	state() {}
	state(int s,int a,int b,int step):s(s),n(a),m(b),step(step) {}
};
const int maxn=105;
int vis[maxn][maxn][maxn];
int S,N,M,flag;
int out(int a,int b,int c){
	if(a>b){
		a^=b;
		b^=a;
		a^=b;
	}
	if(a>c){
		a^=c;
		c^=a;
		a^=c;
	}
	if(a==0){
		if(b==c){
			return 1;
		}
	}
	return 0;
}
void init() {
	int i,j;
	for(i=0; i<=S; i++) {
		for(j=0; j<=N; j++) {
			for(int k=0; k<=M; k++) {
				vis[i][j][k]=0;
			}
		}
	}
}
void bfs() {
	queue<state> Q;
	Q.push(state(S,0,0,0));
	vis[S][0][0]=1;
	while(!Q.empty()) {
		state now=Q.front();
		Q.pop();
		//cout<<now.s<<" "<<now.n<<" "<<now.m<<endl;
		if(out(now.s,now.n,now.m)) {
			flag=1;
			cout<<now.step<<endl;
			break;
		}
		int ns,nn,nm;
		if(now.s!=0) {
			//s->n
			int san=now.s+now.n;
			if(san>N) ns=san-N,nn=N;
			else ns=0,nn=san;
			nm=now.m;
			if(vis[ns][nn][nm]==0) {
				vis[ns][nn][nm]=1;
				Q.push(state(ns,nn,nm,now.step+1));
			}
			//s->m
			int sam=now.s+now.m;
			if(sam>M) ns=sam-M,nm=M;
			else ns=0,nm=sam;
			nn=now.n;
			if(vis[ns][nn][nm]==0) {
				vis[ns][nn][nm]=1;
				Q.push(state(ns,nn,nm,now.step+1));
			}
		}
		if(now.n!=0) {
			//n->s
			int nas=now.n+now.s;
			ns=nas,nn=0,nm=now.m;
			if(vis[ns][nn][nm]==0) {
				vis[ns][nn][nm]=1;
				Q.push(state(ns,nn,nm,now.step+1));
			}
			//n->m
			int nam=now.n+now.m;
			ns=now.s;
			if(nam>M) nn=nam-M,nm=M;
			else nn=0,nm=nam;
			if(vis[ns][nn][nm]==0) {
				vis[ns][nn][nm]=1;
				Q.push(state(ns,nn,nm,now.step+1));
			}
		}
		if(now.m!=0) {
			//m->s
			int mas=now.m+now.s;
			ns=mas,nn=now.n,nm=0;
			if(vis[ns][nn][nm]==0) {
				vis[ns][nn][nm]=1;
				Q.push(state(ns,nn,nm,now.step+1));
			}
			//m->n
			int man=now.m+now.n;
			if(man>N) nm=man-N,nn=N;
			else nm=0,nn=man;
			ns=now.s;
			if(vis[ns][nn][nm]==0) {
				vis[ns][nn][nm]=1;
				Q.push(state(ns,nn,nm,now.step+1));
			}
		}
	}
}
int main() {
	while(cin>>S>>N>>M) {
		if(S==0&&N==0&&M==0) break;
		init();
		flag=0;
		bfs();
		if(!flag) cout<<"NO"<<endl;
	}
	return 0;
}

1-14 Find a way

问题

Pass a year learning in Hangzhou, yifenfei arrival hometown Ningbo at finally. Leave Ningbo one year, yifenfei have many people to meet. Especially a good friend Merceki.
Yifenfei’s home is at the countryside, but Merceki’s home is in the center of city. So yifenfei made arrangements with Merceki to meet at a KFC. There are many KFC in Ningbo, they want to choose one that let the total time to it be most smallest.
Now give you a Ningbo map, Both yifenfei and Merceki can move up, down ,left, right to the adjacent road by cost 11 minutes.

输入

The input contains multiple test cases.
Each test case include, first two integers n, m. (2<=n,m<=200).
Next n lines, each line included m character.
‘Y’ express yifenfei initial position.
‘M’ express Merceki initial position.
‘#’ forbid road;
‘.’ Road.
‘@’ KCF

输出

For each test case output the minimum total time that both yifenfei and Merceki to arrival one of KFC.You may sure there is always have a KFC that can let them meet.

样例输入

4 4
Y.#@

.#…
@…M
4 4
Y.#@

.#…
@#.M
5 5
Y…@.
.#…
.#…
@…M.
#…#

样例输出

66
88
66

思路

两次bfs
源码

/*
* problem: Fire Game
* method:两次bfs
* date:
*/
#include<iostream>
#include<queue>
#include<utility>
#define ll long long
using namespace std;
typedef pair<int,int> P;
const int inf=1e8;
const int maxn=205;
char maze[maxn][maxn];
int dp[2][maxn][maxn];
bool vis[2][maxn][maxn];
int dx[]={-1,1,0,0};
int dy[]={0,0,-1,1};
int m,n,x,y,min=0;
P Y,M;
void init(){
	int i,j,k;
	for(i=0;i<2;i++){
		for(j=0;j<n;j++){
			for(k=0;k<m;k++){
				dp[i][j][k]=inf;
				vis[i][j][k]=false;
			}
		}
	}
}
void bfs(P start,int i){
	queue<P> Q;
	Q.push(start);
	dp[i][start.first][start.second]=0;
	vis[i][start.first][start.second]=true;
	while(!Q.empty()){
		P now=Q.front();
		Q.pop();
		for(int j=0;j<4;j++){
			int nx,ny;
			nx=now.first+dx[j];
			ny=now.second+dy[j];
			//cout<<nx<<' '<<ny<<endl;
			if(nx>=0&&nx<n&&ny>=0&&ny<m&&maze[nx][ny]!='#'&&!vis[i][nx][ny]){
				dp[i][nx][ny]=dp[i][now.first][now.second]+1;
				vis[i][nx][ny]=true;
				Q.push(P(nx,ny));
			}
		}
	}
}
int main(){
	int i,j;
	while(cin>>n>>m){
		for(i=0;i<n;i++){
			for(j=0;j<m;j++){
				cin>>maze[i][j];
				if(maze[i][j]=='Y'){
					Y.first=i;
					Y.second=j;
				}else if(maze[i][j]=='M'){
					M.first=i;
					M.second=j;
				}
			}
		}
		init();
		bfs(Y,0);
		bfs(M,1);
		int min=inf;
		for(i=0;i<n;i++){
			for(j=0;j<m;j++){
				//cout<<dp[0][i][j]<<" ";
				if(maze[i][j]=='@'){
					int t=dp[0][i][j]+dp[1][i][j];
					min=min<t?min:t;
				}
			}
			//cout<<endl;
		}
		cout<<min*11<<endl;
	}
	return 0;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值