专题一 简单搜索

 

 

棋盘问题

Time Limit: 1000MSMemory Limit: 10000K
Total Submissions: 115518Accepted: 51924

Description

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

Input

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

Output

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

Sample Input

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

Sample Output

2
1

思路

这道题目和之前的棋盘问题有点儿不一样,因为它的棋子个数可能比 能放置 的位置还要少。这就意味着有的位置可以放也可以不放,可以把机会让给其他位置。

这种问题就要考虑不放这个选择

第一处出错

这是我一开始TLE的写法,TLE就在标注的那个语句上

第二处出错 

递归边界条件没写全

#include <iostream>
#include <cstring>
#include <cmath>
using namespace std;
const int N=20;
char map[N][N];
int n,k;
int ans;
bool col[N],row[N];
 

void dfs(int u,int cnt)
{
	if(cnt==k+1)
	{
		ans++;
		return;
	}
//	cout<<" u is "<<u<<endl;
	for(int i=0;i<n;i++)
	{
		if(col[i]||row[u])
		continue;
		
		if(map[u][i]!='#')
		continue;
		
		row[u]=true;
		col[i]=true;
		dfs(u+1,cnt+1);
		
		//cout<<" u is "<<u<< " i is "<<i<<endl;
		row[u]=col[i]=false;
		dfs(u+1,cnt);  //错误之处 不放的这种情况 要放在for循环外面,这样明显不对
	}
}

int main()
{
   while(cin>>n>>k)
   {
   	  memset(col,false,sizeof col);
   	  memset(row,false,sizeof row);
   	  ans=0;
   	  if(n==-1&&k==-1)
   	  break;
   	  
   	  for(int i=0;i<n;i++)
   	  cin>>map[i];
   	  
   	  dfs(0,1);  //传的是行标
	
	  cout<<ans<<endl;
   }
   
   return 0;
}

正确代码

#include <iostream>
#include <cstring>
#include <cmath>
using namespace std;
const int N=20;
char map[N][N];
int n,k;
int ans;
bool col[N],row[N];
int cnt;

void dfs(int u)
{
	if(cnt==k)
	{
		ans++;
		return;
	}
	if(u>=n)   //之前的代码没有这个判断条件 
	return;
//	cout<<" u is "<<u<<endl;
	for(int i=0;i<n;i++)
	{
		if(col[i]||row[u])
		continue;
		
		if(map[u][i]!='#')
		continue;
		
		row[u]=true;
		col[i]=true;
		++cnt;
		dfs(u+1);
		--cnt;
		//cout<<" u is "<<u<< " i is "<<i<<endl;
		row[u]=col[i]=false;
		
	}
	dfs(u+1);
}

int main()
{
   while(cin>>n>>k)
   {
   	  memset(col,false,sizeof col);
   	  memset(row,false,sizeof row);
   	  ans=0;
   	  cnt=0;
   	  if(n==-1&&k==-1)
   	  break;
   	  
   	  for(int i=0;i<n;i++)
   	  cin>>map[i];
   	  
   	  dfs(0);  //传的是行标

	  cout<<ans<<endl;
   }
   
   return 0;
}

另一个代码是我第一回写的正确代码

#include <iostream>
#include <cstring>
#include <cmath>
using namespace std;
const int N=20;
char map[N][N];
int n,k;
int ans;
bool col[N],row[N];
 

void dfs(int u,int cnt)
{
	if(cnt==k)
	{
		ans++;
		return;
	}
//	cout<<" u is "<<u<<endl;
	for(int i=0;i<n;i++)
	{
		if(col[i]||row[u])
		continue;
		
		if(map[u][i]!='#')
	    continue;
		
		row[u]=true;
		col[i]=true;
		
		for(int j=0;j<n&&j!=u;j++)
		dfs(j,cnt+1);
		
		//cout<<" u is "<<u<< " i is "<<i<<endl;
		row[u]=col[i]=false;
	}
}

int main()
{
   while(cin>>n>>k)
   {
   	  memset(col,false,sizeof col);
   	  memset(row,false,sizeof row);
   	  ans=0;
   	  if(n==-1&&k==-1)
   	  break;
   	  
   	  for(int i=0;i<n;i++)
   	  cin>>map[i];
   	  
   	  for(int j=0;j<n;j++)
   	  dfs(j,1);  //传的是行标
	
	  cout<<ans<<endl;
   }
   
   return 0;
}

 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.

Input

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.

Output

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.

Sample Input

2 
6 
19 
0
6 
19 
0

Sample Output

10 
100100100100100100 
111111111111111111
100100100100100100 
111111111111111111

Sponsor

深搜和宽搜都可做

BFS

#include <iostream>
#include <cmath>
#include <algorithm>
#include <queue>
using namespace std;
typedef long long LL;
LL n;


void bfs(LL u)
{
	queue<LL> q;
	q.push(u);
	
	while(!q.empty())
	{
		LL t=q.front();
		q.pop();
		
		if(t%n==0)
		{
			cout<<t<<endl;
			return;
		}
		
		q.push(t*10);
		q.push(t*10+1);
	}
}


int main()
{
	//int n;
	while(cin>>n&&n)
	{
		bfs(1);
	}
} 

DFS

#include <algorithm>
#include <cmath>
#include <iostream>
using namespace std;
typedef long long LL;
int n;
bool flag;  //由于深搜会去找所有路径,所以找到一条就退出 

//long long最长19位数字
//int 最长10位数字
//所以深搜添加可行性剪枝当次数超过19时 
void dfs(LL u,int cnt)
{
	if(flag||cnt>19)
	return;
	if(u%n==0)
	{
		cout<<u<<endl;
		flag=true;
		return;
	}
	
	dfs(u*10,cnt+1); 
	dfs(u*10+1,cnt+1);
}
int main()
{
   while(cin>>n&&n)
   {
   	flag=false;
   	dfs(1,1);
   }
   
   return 0;	
}

Pots   

Debug好艰难,但进步很大

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

  1. FILL(i)        fill the pot i (1 ≤ ≤ 2) from the tap;
  2. DROP(i)      empty the pot i to the drain;
  3. 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.

Input

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

Output

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’.

Sample Input

3 5 4

Sample Output

6
FILL(2)
POUR(2,1)
DROP(1)
POUR(2,1)
FILL(2)
POUR(2,1)
#include <iostream> 
#include <cstdio>
#include <cstring>
#include <cmath> 
#include <vector>
using namespace std;
const int N=110;
int a,b,c;
//int res=-1;
//int cnt=0;
bool st[N][N];
vector<string> op,op2;  //debug出现的问题,原本没有加op2 


/*
由于要求 minimal length,
本来想着求这种最小值一般用BFS,利用BFS的两段性 
现在用最优性剪枝DFS来求 
*/
int res=1<<30; 
void dfs(int u1,int u2,int cnt)
{ 
	if(cnt>=res)  //最优性剪枝,这样可以让DFS发挥BFS的用途,求最小 
	return;
	 
/*
st[u1][u2]=true;  debug出现的问题
不可以写在这里而应该去递归前后,
因为要回溯操作 ,这样不好回溯 

一开始debug的时候甚至连st[][]都没有
所以以后注意了,这题可能出现impossible的情况,
这种情况下,一般都是要写st[][] ,不然错误的情况一直搜搜搜
之前Find the multiple 之所以不写 是因为给的数据不管哪一个
都肯定能搜出一个结果 
*/
	if(u1==c||u2==c)
	{
	    res=cnt;
	    op2=op; 
		/* 
		如果不把当前能出结果的op存起来,深搜继续找
		其他最小值的时候,就算可能找不到比当前小的最小值了,
		但op会随着深搜而变动 
		*/ 
	    //return;
    }
    //cout<<u1<<" "<<u2<<endl;
    
	if(!st[a][u2])
	{
		//u1=a;  debug出现的问题,此处不可以直接改,因为回溯后会进行更往后的也要用到u1 
		
		//cnt++;  也可以把cnt 写在全局变量的位置,这样用也是对的 
		op.push_back("FILL(1)");
		st[a][u2]=true;
		dfs(a,u2,cnt+1);
		st[a][u2]=false;
		op.pop_back();
	//	cnt--;
	} 
	
	if(!st[u1][b])
	{
		//u2=b;
		//cnt++;
		op.push_back("FILL(2)");
		st[u1][b]=true;
		dfs(u1,b,cnt+1);
		st[u1][b]=false;
		op.pop_back();
		//cnt--;
	} 
	
		if((a-u1)<u2&&!st[a][u2-(a-u1)])
		{
		//cnt++;
		op.push_back("POUR(2,1)");
		st[a][u2-(a-u1)]=true;
		dfs(a,u2-(a-u1),cnt+1);
		st[a][u2-(a-u1)]=false;
		op.pop_back();	
		}
		else if(!st[u1+u2][0]&&(a-u1)>=u2)
		{
		op.push_back("POUR(2,1)");
		st[u1+u2][0]=true;
		dfs(u1+u2,0,cnt+1);
		st[u1+u2][0]=false;
		op.pop_back();
	    }

	
		if((b-u2)<u1&&!st[u1-(b-u2)][b])
		{
			//cnt++;
			op.push_back("POUR(1,2)");
			st[u1-(b-u2)][b]=true;
			dfs(u1-(b-u2),b,cnt+1);
			st[u1-(b-u2)][b]=false;
			op.pop_back();
			//cnt--;
		}
		else if(!st[0][u2+u1]&&(b-u2)>=u1)
			{
			op.push_back("POUR(1,2)");
			st[0][u2+u1]=true;
			dfs(0,u2+u1,cnt+1);
			st[0][u2+u1]=false;
			op.pop_back();
	    	}
	
	if(!st[0][u2])
	{
		//u1=0;
		//cnt++;
		op.push_back("DROP(1)");
		st[0][u2]=true;
		dfs(0,u2,cnt+1);
		st[0][u2]=false;
		op.pop_back();
		//cnt--;
	}
	
	if(!st[u1][0])
	{
		//u2=0;
		//cnt++;
		op.push_back("DROP(2)");
		st[u1][0]=true;
		dfs(u1,0,cnt+1);
		st[u1][0]=false;
		op.pop_back();
		//cnt--;
	}
}
 
int main()
{
	cin>>a>>b>>c;
	dfs(0,0,0);
	st[0][0]=true;
	if(res==1<<30)
	cout<<"impossible"<<endl;
	else 
	{
		cout<<res<<endl;
		for(int i=0;i<op2.size();i++)
		cout<<op2[i]<<endl;
	}
	return 0;
}


Shuffle'm Up

A common pastime for poker players at a poker table is to shuffle stacks of chips. Shuffling chips is performed by starting with two stacks of poker chips, S1 and S2, each stack containing C chips. Each stack may contain chips of several different colors.

The actual shuffle operation is performed by interleaving a chip from S1 with a chip from S2 as shown below for C = 5:

The single resultant stack, S12, contains 2 * C chips. The bottommost chip of S12 is the bottommost chip from S2. On top of that chip, is the bottommost chip from S1. The interleaving process continues taking the 2nd chip from the bottom of S2 and placing that on S12, followed by the 2nd chip from the bottom of S1 and so on until the topmost chip from S1 is placed on top of S12.

After the shuffle operation, S12 is split into 2 new stacks by taking the bottommost C chips from S12 to form a new S1 and the topmost C chips from S12 to form a new S2. The shuffle operation may then be repeated to form a new S12.

For this problem, you will write a program to determine if a particular resultant stack S12 can be formed by shuffling two stacks some number of times.

Input

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

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.

Sample Input

2
4
AHAH
HAHA
HHAAAAHH
3
CDE
CDE
EEDDCC

Sample Output

1 2
2 -1

 DFS

#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <stack>
using namespace std;
int c;
string s1,s2,s3;
int res;
bool flag;

void dfs(string s,int cnt) 
{
	if(cnt>2*c) 
	return;  
	/*
	我举了一个四个数字(c=2)的例子,
	发现2*c之后又会变成原来四个数字的样子,变成最初的样子了
	所以我用这个来筛掉那些不可能搜出结果的案例 
	*/
	 
	if(s==s3)
	{
	res=cnt;
	return;
    }
	
	string a=s.substr(0,c);
	//cout<<a<<endl;
	string b=s.substr(c);
	//cout<<b<<endl;
	
	string u;
	for(int i=0;i<c;i++)
	{
		u+=b[i];
		u+=a[i];
	} 
	dfs(u,cnt+1);
}
int main()
{
	int T;
	cin>>T;
	for(int i=1;i<=T;i++)
	{
		cin>>c;
		res=-1;
		flag=false;
		s1.clear();
		s2.clear();
		s3.clear();
		cin>>s1>>s2>>s3;
		dfs(s1+s2,0);
		
		cout<<i<<" "<<res<<endl;
	}
}

BFS

#include <iostream>
#include <cstring>
#include <iostream>
#include <map>
#include <queue>
#define x first
#define y second  
using namespace std;
typedef long long LL;
typedef pair<string,int> PII;
int c;
int res;
string s1,s2,s3;
queue<PII> q;
map<string,int> st;  
//如果没有这个就会像深搜没有if(cnt>2*c)一样出不来 
/*而find the multiple
这道题不用st标记的原因是
一定能搜到结果。
而这道题目有可能搜不到结果,输出-1,为了防止盲搜出不来
需要st数组标记一下 
*/
void bfs(string s)
{
	q.push({s,0});
    st[s]=true;
	
	while(!q.empty())
	{
		PII t=q.front();
		q.pop();
		
		if(t.x==s3)
	    {
	    	res=t.y;
	    	return;
		}
		
		
		string a=t.x.substr(0,c);
	    string b=t.x.substr(c);
	    
	    string u;
	    
	    for(int i=0;i<c;i++)
	    {
	    	u+=b[i];
	    	u+=a[i];
		}
		
		if(!st[u])
		{
	    q.push({u,t.y+1});
	    st[u]=true;
	    }
	}
}

int main()
{
	int T;
	cin>>T;
	for(int i=1;i<=T;i++)
	{
		cin>>c;
		res=-1;
		cin>>s1>>s2>>s3;
		bfs(s1+s2);
		cout<<i<<" "<<res<<endl;
	} 
}

 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.

Input

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).

Output

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

Sample Input

3 
1033 8179 
1373 8017 
1033 1033
1033 8179 
1373 8017 
1033 1033

Sample Output

6 
7 
0
7 
0

BFS

#include <iostream>
#include <cmath>
#include <cstring>
#include <queue> 
using namespace std;
const int N=1e5+10;
bool p[N];
bool st[N];
int A,B;
int res;
struct node
{
	int a;
	int b;
	int c;
	int d;
	int step;
};
void get_primes()
{
	for(int i=2;i<=9999;i++)
	{
	//	if(!p[i]) 
	 //   pirmes[cnt++]=i;
	    
	    for(int j=i+i;j<=9999;j+=i)
	    {
	    	p[j]=true;
		}
	}
}


void bfs(int x)
{
	st[x]=true;
	queue<struct node> q;
	struct node J;
	int co=0;
	while(x)
	{
	  co++;
	  if(co==1)
	  J.d=x%10;
	  else if(co==2)
	  J.c=x%10;
	  else if(co==3)
	  J.b=x%10;
	  else J.a=x%10;
	  x/=10;
    }  
    J.step=0;
    q.push(J);
    
    while(!q.empty())
    {
    	struct node t=q.front();
    	q.pop();
    	int aa=t.a;
    	int bb=t.b;
    	int cc=t.c;
    	int dd=t.d;
    	int ss=t.step;
    	
    	
    	if((aa*1000+bb*100+cc*10+dd)==B)
    	{
    		res=t.step;
    		return;
		}
    	//
    	
    	for(int i=1;i<=9;i++)
    	{
    		int cur=i*1000+bb*100+cc*10+dd;
    		if(!p[cur]&&!st[cur])
    		{
    			q.push({i,bb,cc,dd,ss+1});
    			st[cur]=true;
			}
		}
		for(int i=0;i<=9;i++)
    	{
    		int cur=aa*1000+i*100+cc*10+dd;
    		if(!p[cur]&&!st[cur])
    		{
    			q.push({aa,i,cc,dd,ss+1});
    			st[cur]=true;
			}
		}
		
		for(int i=0;i<=9;i++)
    	{
    		int cur=aa*1000+bb*100+i*10+dd;
    		if(!p[cur]&&!st[cur])
    		{
    			q.push({aa,bb,i,dd,ss+1});
    			st[cur]=true;
			}
		}
		
		for(int i=0;i<=9;i++)
    	{
    		int cur=aa*1000+bb*100+cc*10+i;
    		if(!p[cur]&&!st[cur])
    		{
    			q.push({aa,bb,cc,i,ss+1});
    			st[cur]=true;
			}
		}	
	}
	
	return;
}
int main()
{
	int t;
	cin>>t;
	get_primes();
	while(t--)
	{
		//int a,b;
		memset(st,false,sizeof st);
		res=-1;
		cin>>A>>B;
		bfs(A);
		
		if(res==-1)
		cout<<"Impossible"<<endl;
		
		else cout<<res<<endl;
	}
} 

L:鸣人和佐助   BFS变式
Description
佐助被大蛇丸诱骗走了,鸣人在多少时间内能追上他呢?
已知一张地图(以二维矩阵的形式表示)以及佐助和鸣人的位置。地图上的每个位置都可以走到,只不过有些位置上有大蛇丸的手下,需要先打败大蛇丸的手下才能到这些位置。鸣人有一定数量的查克拉,每一个单位的查克拉可以打败一个大蛇丸的手下。假设鸣人可以往上下左右四个方向移动,每移动一个距离需要花费1个单位时间,打败大蛇丸的手下不需要时间。如果鸣人查克拉消耗完了,则只可以走到没有大蛇丸手下的位置,不可以再移动到有大蛇丸手下的位置。佐助在此期间不移动,大蛇丸的手下也不移动。请问,鸣人要追上佐助最少需要花费多少时间?

Input
输入的第一行包含三个整数:M,N,T。代表M行N列的地图和鸣人初始的查克拉数量T。0 < M,N < 200,0 ≤ T < 10。后面是M行N列的地图,其中@代表鸣人,+代表佐助。*代表通路,#代表大蛇丸的手下。
Output
输出包含一个整数R,代表鸣人追上佐助最少需要花费的时间。如果鸣人无法追上佐助,则输出-1。

Sample Input
样例输入1

4 4 1
#@##
**##
###+
****
1
2
3
4
5
样例输入2

4 4 2
#@##
**##
###+
****
1
2
3
4
5
Sample Output
样例输出1

6
1
样例输出2

4
1
题目分析
这道题目因为是求最短路径(时间),我们还是选用广度优先搜索。但是不一样的在于队列的结构体中除了坐标(x,y)和时间(tot),还增加了当前的查克拉数量(T)。现在我们开始分析过程——
1. 定义变量,避免重复走过路径(awl)
2. 输入,与其他迷宫题目输入相同,需要保存起点
3. 进入广度优先搜索
4. 遍历4个方向
5. 判断边界和重复。这是一个难点——通常的迷宫问题,我们会使用二维的bool数组来判断重复,甚至直接改变原来的地图——但是这道题就会有BUG,给出一个数据(默认优先向下行走,坐标从(0,0)开始):

5 5 2
@#***
####*
#**#*
#****
+####
 

这道题目,首先看到最短时间,肯定想到BFS,但是这题与普通的BFS不一样,普通的BFS标记了访问过的点,能搜出一条最短路径。但此处不能再用二维标记访问过的点了,因为被标记过的点不能再访问了,而此处很有可能再访问

3  6    1
@#**** 
*#*###
***##+

以这个例子为例,先去掉查克拉这个因素,看成普通宽搜,我们知道,宽搜为了找到一条最短路, 会去标记访问的哪些点

(1,1)——>(1,2)——>(1,3)。。。会把(1, 3)给标记了,但是这条路走下去发现走不通,由于查克拉不足等因素。

于是另一条正确的路(1,1)——>(2,1)——>(3,1)——>(3,2)——>(3,3)——>(2,3)——>(1,3)中也来到了(1, 3)这时(1, 3)也被标记过了,无法再访问,输出了-1

如何解决上述问题:

1.把st标记数组直接去掉不用可以吗?

答:不可以,会超内存

这是超内存的错误代码,用的仍然是二维标记数组

#include <iostream>
#include <cstring>
#include <cmath>
#define x first
#define y second
using namespace std;
typedef pair<int,int> PII;
const int N=205;
int px,py;
int dx[4]={-1,0,1,0};
int dy[4]={0,1,0,-1}; 
char map[N][N];
int dis[N][N];  //去掉了dis的标记功能
struct node
{
   int x,y;
   int co;	
}q[N*N*N];
int n,m,t;
int bfs(int x,int y)
{
	int hh=0,tt=-1;
	//memset(dis,-1,sizeof dis);
	dis[x][y]=0;
    q[++tt]={x,y,t};
	
	while(hh<=tt)
	{
		
	struct node t=q[hh++];
	if(map[t.x][t.y]=='+')
	{
		return dis[t.x][t.y];
	}
	
	
	for(int i=0;i<4;i++)
	{
		int xx=t.x+dx[i];
		int yy=t.y+dy[i];
		if(xx>=0&&xx<m&&yy>=0&&yy<n)//无标记数组查重
		{
			
			if(map[xx][yy]=='#')
			{
				if(t.co-1>=0)
				{
				dis[xx][yy]=dis[t.x][t.y]+1;
				q[++tt]={xx,yy,t.co-1};
			//	cout<<"xx is "<<xx<<" yy is "<<yy<<endl;
			    }
			    else continue;
			}
			else
			{
				dis[xx][yy]=dis[t.x][t.y]+1;
				q[++tt]={xx,yy,t.co};
			//	cout<<"xx is "<<xx<<" yy is "<<yy<<endl;
			}
		}
	}
   }
   
   return -1;
}
int main()
{
	while(cin>>m>>n>>t)
	{
		for(int i=0;i<m;i++)
		for(int j=0;j<n;j++)
		{
		cin>>map[i][j];
		if(map[i][j]=='@')
		{
			px=i;
			py=j;
		}
	    }
	    
	   cout<<bfs(px,py)<<endl;
	}
	
	return 0;
}

2.正确做法是什么?

用一个三维数组,前两维与正常的坐标对应,最后一维用来记录这个点剩余的查克拉数量,这样重复经过某个点,只要他们剩余的查克拉数量不一样,他们就是彼此独立的,就像之前举的那两个路径的例子

#include <iostream>
#include <cstring>
#include <cmath>
#define x first
#define y second
using namespace std;
typedef pair<int,int> PII;
const int N=205;
int px,py;
int dx[4]={-1,0,1,0};
int dy[4]={0,1,0,-1}; 
char map[N][N];
bool st[N][N][N];   //定义三重标记
struct node
{
   int x,y;
   int co;
   int step;	
}q[N*N];
int n,m,t;
int bfs(int x,int y)
{
	memset(st,false,sizeof st);
	int hh=0,tt=-1;
	st[x][y][0]=true;
    q[++tt]={x,y,t,0};
	
	while(hh<=tt)
	{
		
	struct node t=q[hh++];
	if(map[t.x][t.y]=='+')
	{
		return t.step;
	}
	
	
	for(int i=0;i<4;i++)
	{
		int xx=t.x+dx[i];
		int yy=t.y+dy[i];
		if(xx>=0&&xx<m&&yy>=0&&yy<n)
		{
			
			if(map[xx][yy]=='#')
			{
				if(t.co-1>=0)
				{
				 if(!st[xx][yy][t.co-1]) 
				 {
				    q[++tt]={xx,yy,t.co-1,t.step+1};
			        //	cout<<"xx is "<<xx<<" yy is "<<yy<<endl;
			        st[xx][yy][t.co-1]=true;
		         }
			    }
			    else continue;
			}
			else
			{
				if(!st[xx][yy][t.co])
				{
				st[xx][yy][t.co]=true;
				q[++tt]={xx,yy,t.co,t.step+1};
			//	cout<<"xx is "<<xx<<" yy is "<<yy<<endl;
	        	}
			}
		}
	}
   }
   
   return -1;
}
int main()
{
	while(cin>>m>>n>>t)
	{
		for(int i=0;i<m;i++)
		for(int j=0;j<n;j++)
		{
		cin>>map[i][j];
		if(map[i][j]=='@')
		{
			px=i;
			py=j;
		}
	    }
	    
	   cout<<bfs(px,py)<<endl;
	}
	
	return 0;
}

 拯救行动      BFS变式

公主被恶人抓走,被关押在牢房的某个地方。牢房用N*M (N, M <= 200)的矩阵来表示。矩阵中的每项可以代表道路(@)、墙壁(#)、和守卫(x)。
英勇的骑士(r)决定孤身一人去拯救公主(a)。我们假设拯救成功的表示是“骑士到达了公主所在的位置”。由于在通往公主所在位置的道路中可能遇到守卫,骑士一旦遇到守卫,必须杀死守卫才能继续前进。
现假设骑士可以向上、下、左、右四个方向移动,每移动一个位置需要1个单位时间,杀死一个守卫需要花费额外的1个单位时间。同时假设骑士足够强壮,有能力杀死所有的守卫。

给定牢房矩阵,公主、骑士和守卫在矩阵中的位置,请你计算拯救行动成功需要花费最短时间。

Input

第一行为一个整数S,表示输入的数据的组数(多组输入)
随后有S组数据,每组数据按如下格式输入
1、两个整数代表N和M, (N, M <= 200).
2、随后N行,每行有M个字符。"@"代表道路,"a"代表公主,"r"代表骑士,"x"代表守卫, "#"代表墙壁。

Output

如果拯救行动成功,输出一个整数,表示行动的最短时间。
如果不可能成功,输出"Impossible"

Sample Input

2
7 8
#@#####@
#@a#@@r@
#@@#x@@@
@@#@@#@#
#@@@##@@
@#@@@@@@
@@@@@@@@ 
13 40
@x@@##x@#x@x#xxxx##@#x@x@@#x#@#x#@@x@#@x
xx###x@x#@@##xx@@@#@x@@#x@xxx@@#x@#x@@x@
#@x#@x#x#@@##@@x#@xx#xxx@@x##@@@#@x@@x@x
@##x@@@x#xx#@@#xxxx#@@x@x@#@x@@@x@#@#x@#
@#xxxxx##@@x##x@xxx@@#x@x####@@@x#x##@#@
#xxx#@#x##xxxx@@#xx@@@x@xxx#@#xxx@x#####
#x@xxxx#@x@@@@##@x#xx#xxx@#xx#@#####x#@x
xx##@#@x##x##x#@x#@a#xx@##@#@##xx@#@@x@x
x#x#@x@#x#@##@xrx@x#xxxx@##x##xx#@#x@xx@
#x@@#@###x##x@x#@@#@@x@x@@xx@@@@##@@x@@x
x#xx@x###@xxx#@#x#@@###@#@##@x#@x@#@@#@@
#@#x@x#x#x###@x@@xxx####x@x##@x####xx#@x
#x#@x#x######@@#x@#xxxx#xx@@@#xx#x#####@

Sample Output

13
7

这题和上道题鸣人和佐助一样,都是BFS的变式。

一开始我想的很简单,就是简单宽搜,虽然内心也有点没底,果真不是简单宽搜

其实这反映了我对宽搜并没有真正掌握

朴素的BFS求出来是最短路径所花费的时间,而我们要求的是花费的最短时间

理解起来就像上一道题,以我举的那个例子,宽搜一开始为了找到最短路径,会先访问

(1,1)——>(1,2)——>(1,3)这一条路,并且标记所有点

而发现这条路走不下去,因为查克拉不足,迂回走另一条路时还会经过(1,3),这时按朴素BFS

来说(1, 3)已经被标记了,无法再走,所以朴素BFS是不成立的

回到这道题,既然是BFS的变式,有两种思路:

1.用普通队列,把守卫看成两个格子

2.用优先队列,时间少的优先级高

#include <iostream>
#include <cstring>
#include <cmath>
#include <queue>
using namespace std;
const int N=210;
char map[N][N];
bool st[N][N];
int dx[4]={-1,0,1,0};
int dy[4]={0,1,0,-1};
struct node
{
	int x;
	int y;
	int step;
	
	friend bool operator<(node a,node b)
	{
		return a.step>b.step;  //b的优先级比a高
	}
};
int px,py;
int n,m;
void bfs()
{
	priority_queue<struct node> q;
	q.push({px,py,0});
	memset(st,false,sizeof st);
    while(!q.empty())
    {
    	struct node t=q.top();
    	q.pop();
    	
    	if(map[t.x][t.y]=='a')
    	{
    		cout<<t.step<<endl;
    		return;
		}
		
    	for(int i=0;i<4;i++)
    	{
    		int xx=t.x+dx[i];
    		int yy=t.y+dy[i];
    		
    		if(xx>=0&&xx<n&&yy>=0&&yy<m&&!st[xx][yy]&&map[xx][yy]!='#')
    		{
    			if(map[xx][yy]=='x')
    			{
    				st[xx][yy]=true;
    				q.push({xx,yy,t.step+2});
				}
				else
				{
					st[xx][yy]=true;
					q.push({xx,yy,t.step+1});
				}
			}
		}
    	
	}
	cout<<"Impossible"<<endl;
} 
int main()
{
	int s;
	cin>>s;
	while(s--)
	{
	//	int n,m;
		cin>>n>>m;
		for(int i=0;i<n;i++)
		for(int j=0;j<m;j++)
		{
			cin>>map[i][j];
			if(map[i][j]=='r')
			{
				px=i;
				py=j;
			}
		}
		
		bfs();
	}
	
	return 0;
}

Dungeon Master[地牢大师]  三维BFS

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?

Input

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.

Output

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!

Sample Input

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

#####
#####
##.##
##...

#####
#####
#.###
####E

1 3 3
S##
#E#
###

0 0 0

Sample Output

Escaped in 11 minute(s).
Trapped!
#include <iostream> 
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int N=35;
char map[N][N][N];
int dis[N][N][N];
int dz[6]={-1,1,0,0,0,0};
int dx[6]={0,0,-1,0,1,0};
int dy[6]={0,0,0,1,0,-1}; 
struct node
{
	int z;
	int x;
	int y;
};
int l,r,c;
//int pl,px,py;

int bfs(int pl,int px,int py)
{
	memset(dis,-1,sizeof dis);
	dis[pl][px][py]=0;
	queue<struct node> q;
	q.push({pl,px,py});
	
	
	while(!q.empty())
	{
		struct node t=q.front();
		q.pop();
		if(map[t.z][t.x][t.y]=='E')
		return dis[t.z][t.x][t.y];
	    for(int i=0;i<6;i++)
	    {
	    	int zz=t.z+dz[i];
	    	int xx=t.x+dx[i];
	    	int yy=t.y+dy[i];
	    	
	    	if(zz<0||zz>=l||xx<0||xx>=r||yy<0||yy>=c)
	    	continue;
	    	
	    	if(map[zz][xx][yy]=='#')
	    	continue;
	    	
	    	if(dis[zz][xx][yy]!=-1)
	    	continue;
	    	
	    	dis[zz][xx][yy]=dis[t.z][t.x][t.y]+1;
	    	q.push({zz,xx,yy});
		}
	}
	
	return -1;
	
}
int main()
{
	while(cin>>l>>r>>c&&l&&r&&c)
	{
		int pl,px,py;
		for(int k=0;k<l;k++)
		for(int i=0;i<r;i++)
		for(int j=0;j<c;j++)
		{
		cin>>map[k][i][j];
		if(map[k][i][j]=='S')
		{
			pl=k;
			px=i;
			py=j;
		}
	    }
		
		int res=bfs(pl,px,py);
		if(res!=-1)
		{
			printf("Escaped in %d minute(s).\n",res);
		}
		else 
		{
			cout<<"Trapped!"<<endl;
		}
		
		getchar();
	}
	
	return 0;
}

在这里插入图片描述

这道题目非常难debug

双BFS

 这道题目是类似于多源最短路的,题目中有个坑点是没有交代初始情况下火可以有很多个,不止一个,首先要以每一个火为起点,向四个方向扩散,标记到达每其他格子的时间。很显然类似于多源最短路。

第二个BFS就是对人的宽搜了,找到人能跑出去的最早时间

坑点

1.定义队列一定不能局部定义,要全局定义

2.要把time[][]数组初始化为无穷大

#include <iostream>
#include <cstring>
#include <cmath>
#include <queue>
#define x first
#define y second
using namespace std;
const int N=1e3+10;
typedef pair<int,int> PII;
int r,c;
char map[N][N];
int tim[N][N];
//int dis[N][N];
bool st[N][N]; //这题的坑点:fire的st可以隐藏到time中,但person的st不可以隐藏 
int px,py;
//queue<PII> q;
//queue<PII> qf;
int dx[4]={-1,0,1,0};
int dy[4]={0,1,0,-1};
struct node
{
	int x;
	int y;
	int step;
}J;
queue<struct node> q;
int Step;
int Time;

void clear_queue()
{
	while(!q.empty())
	{
		q.pop();
	}
}

void bfs_f()
{
	//cout<<"1111"<<endl;
	//memset(tim,-1,sizeof tim);
//	memset(st,false,sizeof st);
	//相当于多源BFS 
	for(int i=0;i<r;i++)
	for(int j=0;j<c;j++)
	{
		if(map[i][j]=='F')
		{
			q.push({i,j,0});
			tim[i][j]=0;
			st[i][j]=true;
		}
	}
	
	while(!q.empty())
	{
		struct node t=q.front();
		q.pop();
		
		for(int i=0;i<4;i++)
		{
			int xx=t.x+dx[i];
			int yy=t.y+dy[i];
			Time=t.step+1;
			if(xx>=0&&xx<r&&yy>=0&&yy<c&&!st[xx][yy]&&(map[xx][yy]=='.'||map[xx][yy]=='J'))
			{
				
				tim[xx][yy]=Time;
				st[xx][yy]=true;
				q.push({xx,yy,Time});
			}
		}
	}
}

 
int bfs_j()
{
	clear_queue();
	//memset(dis,-1,sizeof dis);
	int Time;
	q.push({J.x,J.y,J.step});
	st[J.x][J.y]=true;
	
	while(!q.empty())
	{
		struct node t=q.front();
		q.pop();
		if(t.x==0||t.x==r-1||t.y==0||t.y==c-1) 
		{
		    Step=t.step+1;
			return 1;
		}
		for(int i=0;i<4;i++)
		{
			int xx=t.x+dx[i];
			int yy=t.y+dy[i];
			int Time=t.step+1;
			if(xx>=0&&xx<r&&yy>=0&&yy<c&&!st[xx][yy]&&map[xx][yy]=='.'&&Time<tim[xx][yy])
			{
				st[xx][yy]=true;
				q.push({xx,yy,Time});
			} 
		}
	}
	return 0;
}


int main()
{
	int t;
	cin>>t;
	while(t--)
	{
		cin>>r>>c;
		clear_queue();
		for(int i=0;i<r;i++)
		for(int j=0;j<c;j++)
		{
		cin>>map[i][j];
		if(map[i][j]=='J')
		{
			J.x=i;
			J.y=j;
			J.step=0;
		}
    	}
    	
    	for(int i=0;i<r;i++)
    	for(int j=0;j<c;j++)
    	{
    		tim[i][j]=1000000007;
		}
		memset(st,false,sizeof st);
		bfs_f();
		memset(st,false,sizeof st);
		if(bfs_j())
		cout<<Step<<endl;
		else cout<<"IMPOSSIBLE"<<endl;
		
	}
} 

Saving Tang Monk   状态压缩BFS

Journey to the West》(also 《Monkey》) is one of the Four Great Classical Novels of Chinese literature. It was written by Wu Cheng'en during the Ming Dynasty. In this novel, Monkey King Sun Wukong, pig Zhu Bajie and Sha Wujing, escorted Tang Monk to India to get sacred Buddhism texts.

During the journey, Tang Monk was often captured by demons. Most of demons wanted to eat Tang Monk to achieve immortality, but some female demons just wanted to marry him because he was handsome. So, fighting demons and saving Monk Tang is the major job for Sun Wukong to do.

Once, Tang Monk was captured by the demon White Bones. White Bones lived in a palace and she cuffed Tang Monk in a room. Sun Wukong managed to get into the palace. But to rescue Tang Monk, Sun Wukong might need to get some keys and kill some snakes in his way.

The palace can be described as a matrix of characters. Each character stands for a room. In the matrix, 'K' represents the original position of Sun Wukong, 'T' represents the location of Tang Monk and 'S' stands for a room with a snake in it. Please note that there are only one 'K' and one 'T', and at most five snakes in the palace. And, '.' means a clear room as well '#' means a deadly room which Sun Wukong couldn't get in.

There may be some keys of different kinds scattered in the rooms, but there is at most one key in one room. There are at most 9 kinds of keys. A room with a key in it is represented by a digit(from '1' to '9'). For example, '1' means a room with a first kind key, '2' means a room with a second kind key, '3' means a room with a third kind key... etc. To save Tang Monk, Sun Wukong must get ALL kinds of keys(in other words, at least one key for each kind).

For each step, Sun Wukong could move to the adjacent rooms(except deadly rooms) in 4 directions(north,west,south and east), and each step took him one minute. If he entered a room in which a living snake stayed, he must kill the snake. Killing a snake also took one minute. If Sun Wukong entered a room where there is a key of kind N, Sun would get that key if and only if he had already got keys of kind 1,kind 2 ... and kind N-1. In other words, Sun Wukong must get a key of kind N before he could get a key of kind N+1 (N>=1). If Sun Wukong got all keys he needed and entered the room in which Tang Monk was cuffed, the rescue mission is completed. If Sun Wukong didn't get enough keys, he still could pass through Tang Monk's room. Since Sun Wukong was a impatient monkey, he wanted to save Tang Monk as quickly as possible. Please figure out the minimum time Sun Wukong needed to rescue Tang Monk.

Input

There are several test cases.

For each case, the first line includes two integers N and M(0 < N <= 100, 0 <= M <= 9), meaning that the palace is a N * N matrix and Sun Wukong needed M kinds of keys(kind 1, kind 2, ... kind M).

Then the N*N matrix follows.

The input ends with N = 0 and M = 0.

Output

For each test case, print the minimum time (in minute) Sun Wokong needed to save Tang Monk. If it's impossible for Sun Wokong to complete the mission, print "impossible".

Sample Input

3 1
K.S
##1
1#T
3 1
K#T
.S#
1#.
3 2
K#T
.S.
21.
0 0

Sample Output

5
impossible
8

/*超时原因没有状态压缩:如果之前经过一个位置上去除了蛇,
下回走这个位置就不需要再去除这个蛇了

用i表示一个状态,它是一个十进制数,
它的二进制表示中某个位置是0 指当前位置没蛇 ,1就是有蛇 
假设蛇的编号是j,想知道它是否还被杀死就用i>>j&1  这是判断j是否在i中存在的 
去除当前蛇j 为i-(1<<j) 
增加当前蛇j 为i+(1<<j); 

学会用 isalpha()判断是否时字母
用isdigit()判断是否是数字 

*/

#include <iostream>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;
const int N=110;
int n,m;
char map[N][N];
int px,py,tx,ty;
int res;
bool st[N][N][10];
int dx[4]={-1,0,1,0};
int dy[4]={0,1,0,-1};

struct node
{
	int x;
	int y;
	int co;
	int step;
	int i;
	
	friend bool operator<(node a,node b)
	{
		return a.step>b.step;
	}
};

void bfs(int px,int py,int ori)
{
	priority_queue<struct node> q;
//	memset(st,false,sizeof st);
	st[px][py][0]=true;
	//q.push({px,py,0,0,ori}); 
	q.push({px,py,0,0,ori});
	while(!q.empty())
	{
		struct node t=q.top();
		q.pop();
		if(t.x==tx&&t.y==ty&&t.co==m)
		{
			res=t.step;
			return;
	    }
		for(int i=0;i<4;i++)
		{
			int xx=t.x+dx[i];
			int yy=t.y+dy[i];
			
			if(xx<0||xx>=n||yy<0||yy>=n||map[xx][yy]=='#')
			{
				continue;
			} 
				if(isalpha(map[xx][yy]))  //如果是字母就是蛇 
				{
					int cur=t.i; //记录状态
					int o=map[xx][yy]-'A'; //记录当前蛇的标号 
					int next;  //下一个状态 
					int ss;
					if(cur>>o&1)   //如果之前蛇没杀死 
					{
					ss=t.step+2;
					next=t.i-(1<<o);  //杀死这条蛇 
				    }
				    else  //蛇之前被杀死了 
				    {
				    ss=t.step+1;
					next=t.i;
					}
					if(!st[xx][yy][t.co])
					{
					st[xx][yy][t.co]=true;
					q.push({xx,yy,t.co,ss,next});
				    }
				}
				else
				{
					int ss=t.step+1;
					if(!st[xx][yy][t.co])
					{
					q.push({xx,yy,t.co,ss,t.i});
					st[xx][yy][t.co]=true;
			    	}
			    	
			    	if(isdigit(map[xx][yy])) //是数字的话 
			    	{
			    		int nkey=map[xx][yy]-'0';
						if(nkey==t.co+1&&!st[xx][yy][nkey]) 
						{
							q.push({xx,yy,nkey,ss,t.i});
						}
					} 
				}
		}
	}
	
	res=-1;
	return;
}


int main()
{
	while(cin>>n>>m&&n)
	{
		if(n==0&&m==0)
		break;
		int c=0;
		int ori=0;
		//int ori=0;  //状态 
		for(int i=0;i<n;i++)
		for(int j=0;j<n;j++)
		{
	 	cin>>map[i][j];
	 	if(map[i][j]=='K')
	 	{
	 		px=i;
	 		py=j;
	 		map[i][j]='.';
		}
		if(map[i][j]=='S')
		{
			map[i][j]='A'+c;
			ori+=1<<c; 
			c++;
		}
		if(map[i][j]=='T')
		{
			tx=i;
			ty=j;
			map[i][j]='.';
		}
	    }
	    memset(st,false,sizeof st);
		//bfs(px,py,ori);
		bfs(px,py,ori);
		if(res==-1)
		cout<<"impossible"<<endl;
		
		else cout<<res<<endl;
		
	}
	
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值