简单搜索专题

来源:互联网 发布:ubuntu 配置openstack 编辑:程序博客网 时间:2024/06/11 00:11

题目来自kuangbin带你飞

A-棋盘问题(DFS)

POJ-1321

在一个给定形状的棋盘(形状可能是不规则的)上面摆放棋子,棋子没有区别。要求摆放时任意的两个棋子不能放在棋盘中的同一行或者同一列,请编程求解对于给定形状和大小的棋盘,摆放k个棋子的所有可行的摆放方案C。Input输入含有多组测试数据。 每组数据的第一行是两个正整数,n k,用一个空格隔开,表示了将在一个n*n的矩阵内描述棋盘,以及摆放棋子的数目。 n <= 8 , k <= n 当为-1 -1时表示输入结束。 随后的n行描述了棋盘的形状:每行有n个字符,其中 # 表示棋盘区域, . 表示空白区域(数据保证不出现多余的空白行或者空白列)。 Output对于每一组数据,给出一行输出,输出摆放的方案数目C (数据保证C<2^31)。Sample Input2 1#..#4 4...#..#..#..#...-1 -1Sample Output21

典型的DFS搜索+模拟;先固定一个棋子,对接下来的棋子位置进行搜索,注意界限,不要重复,我采用的方式是,递归内部对棋盘每一行的各个位置进行遍历,递归方向是列的递增,回溯条件是到达最后一列,棋子放完了(因此递归的参数就是列数、棋子数)

#include<stdio.h>#include<iostream>#include<cstring>using namespace std;char Map[9][9];int visit[9];//只用记录某列是否被标记即可int n,k;//n是矩阵大小,k是棋子数目int ans;void dfs(int h,int num){//每次递归向下一层搜索    if(h>n) //递归到最后一列        return ;    for(int i=1;i<=n;i++)    {//搜索同一行是否有可放棋子,且该列未放棋子的位置       if(Map[h][i]=='#'&&visit[i]==0)       {//可以放旗子           visit[i]=1;//在当前位置放旗子           if(num==1)            {                    ans++;//如果是最后一枚棋子,放下ans++                    visit[i]=0;//观察同一行是否有其他合适位置                    continue;              }            else{                 dfs(h+1,num-1);                 //回溯时要回到上一步的操作,将访问标记消除,因为Visit数组是全局变量,因此手动消除                visit[i]=0;             }       }       if(i==n)//在当前行未找到合适位置        dfs(h+1,num);    }}int main(){    while(cin>>n>>k&&(n!=-1&&k!=-1))    {       ans=0;       memset(Map,0,sizeof(Map));       memset(visit,0,sizeof(visit));       for(int i=1;i<=n;i++)         for(int j=1;j<=n;j++)         cin>>Map[i][j];          dfs(1,k);          cout<<ans<<endl;    }    return 0;}

L - Oil Deposits(油田问题)

HDU-1241
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.

Input

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.

Output

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.

Sample Input

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

Sample Output

0
1
2
2
题目大意:数不连通的油田输入
通过深搜,将连通的油田全部标记;主函数循环到一个油田使用一次DFS可以将连通的油田变成不可计数状态,同时记得答案加一

#include<iostream>#include<string.h>using namespace std;const int maxn=105;char Map[maxn][maxn];int vis[maxn][maxn];int m,n;int to[8][2]={{-1,0},{1,0},{0,1},{0,-1},{-1,-1},{1,1},{-1,1},{1,-1}};int ans;int check(int x,int y){    if(Map[x][y]=='*'||vis[x][y]==1||x<1||x>m||y<1||y>n)        return 1;    return 0;}void DFS(int sx,int sy){ //通过搜索将连通可计数状态,变为不可计数状态,在通过主函数循环计数    vis[sx][sy]=1;    for(int i=0;i<8;i++)    {       int nx,ny;       nx=sx+to[i][0];       ny=sy+to[i][1];       if(check(nx,ny))        continue;        vis[nx][ny]=1;       DFS(nx,ny);    }}int main(){      while(cin>>m>>n&&m!=0)      { memset(Map,0,sizeof(Map));      memset(vis,0,sizeof(vis));          for(int i=1;i<=m;i++)            for(int j=1;j<=n;j++)            cin>>Map[i][j];            ans=0;          for(int i=1;i<=m;i++)            for(int j=1;j<=n;j++)          {              if(Map[i][j]=='@'&&vis[i][j]==0)                {                    DFS(i,j);                    ans++;                }          }          cout<<ans<<endl;      }      return 0;}

B-Dungeon Master(三维BFS)

POJ-2251

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 5S.....###..##..###.#############.####...###########.#######E1 3 3S###E####0 0 0

Sample Output

Escaped in 11 minute(s).Trapped!

题目意思:在三维矩阵中找到最短路径,方向变成上、下、东、西、南、北6个方向中规中矩的BFS

#include<iostream>#include<queue>#include<stdio.h>#include<cstring>using namespace std;char Map[31][31][31];int vis[31][31][31];int dire[6][3]={{0,0,1},{0,0,-1},{0,1,0},{0,-1,0},{1,0,0},{-1,0,0}};//移动方向int ans;int L,R,C;struct node{    int x;    int y;    int z;    int floor;//记录路径}cur,next;int check(int x,int y,int z){   if(x<1||x>L||y<1||y>R||z<1||z>C||Map[x][y][z]=='#'||vis[x][y][z]==1)    return 1;   else    return 0;}int BFS(int sx,int sy,int sz,int ex,int ey,int ez){    int nx,ny,nz;    queue<node>Q;     cur.x=sx; cur.y=sy;cur.z=sz ;cur.floor=0;     vis[sx][sy][sz]=1;//当前节点已经入队     Q.push(cur);     while(!Q.empty())     {       cur=Q.front();       Q.pop();       if(cur.x==ex&&cur.y==ey&&cur.z==ez)        {            return cur.floor;        }       for(int i=0;i<6;i++)       {//对当前节点进行搜索          nx=cur.x+dire[i][0];          ny=cur.y+dire[i][1];          nz=cur.z+dire[i][2];          if(check(nx,ny,nz))                continue;//不符合条件             vis[nx][ny][nz]=1;             next.x=nx;next.y=ny;next.z=nz; next.floor=cur.floor+1;//下一“层”的节点更新floor            Q.push(next);       }     }     return 0;}int main(){   int sx,sy,sz,ex,ey,ez;   while(cin>>L>>R>>C)   {       int ans;       memset(Map,0,sizeof(Map));       memset(vis,0,sizeof(vis));       if(!(L||R||C))        break;       for(int i=1;i<=L;i++)         for(int j=1;j<=R;j++)          for(int k=1;k<=C;k++)            {            cin>>Map[i][j][k];            if(Map[i][j][k]=='S')                sx=i,sy=j,sz=k;            if(Map[i][j][k]=='E')                ex=i,ey=j,ez=k;           }          ans=BFS(sx,sy,sz,ex,ey,ez);          if(ans)            printf("Escaped in %d minute(s).\n",ans);          else            printf("Trapped!\n");   }   return 0;}

H-Pots(BFS+数字模拟+打印路径)

PoJ-3414


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 ≤ i ≤ 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 A, B, 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)
题目大意:给你两个杯子,一个结果,通过3种操作使得任意一个杯子的体积和结果相同风格。可能的话输出最短次数,打印操作(路径)

有3种操作(对应杯子体积的变化),用数组去存储下一步杯子体积的增量,这是可变的因此要写一个函数,根据目前杯子的体积,确定下一步的增量
重复出现的状态标记,下次直接舍弃
类似题目 M非常可乐HDU-1495

#include<iostream>#include<cstring>#include<queue>#include<stdio.h>using namespace std;int vis[105][105]={0};int Act[6][2];int co=1;  int k;struct node{    int a,b;    int flag;//记录操作类型    int step;//保存路径    int floor;//报错操作数}act[1000],next;void ACT(int a,int b,int x,int y){ //a,b容量,x,y现状    Act[0][0]=-x,Act[0][1]=0;//DROP(1)    Act[1][0]=0,Act[1][1]=-y;//DROP(2)    Act[2][0]=a-x,Act[2][1]=0;//FILL(1)    Act[3][0]=0,Act[3][1]=b-y;//FILL(2)    int i=a-x>y?y:a-x;//添加给对方的体积不能超过自身的体积    int j=b-y>x?x:b-y;    Act[4][0]=i,Act[4][1]=-i;//POUR(2,1)    Act[5][0]=-j,Act[5][1]=j;//POUR(1,2)}void BFS(int x,int y, int c){ //x,y 容量   act[0].a=0,act[0].b=0;   act[0].floor=0;   act[0].step=-1;   queue<int>q;   q.push(0);   vis[0][0]=1;   while(!q.empty())   {     k=q.front();     q.pop();     if(act[k].a==c||act[k].b==c)        {            printf("%d\n",act[k].floor);             return;         }      ACT(x,y,act[k].a,act[k].b);      for(int i=0;i<6;i++)      {          int nx,ny;          nx=act[k].a+Act[i][0];          ny=act[k].b+Act[i][1];          if(nx>x||nx<0||ny>y||ny<0||vis[nx][ny]==1)            continue;          if(vis[nx][ny]==0)          {             act[co].a=nx;             act[co].b=ny;             act[co].flag=i;             act[co].step=k;             act[co].floor=act[k].floor+1;             q.push(co++);             vis[nx][ny]=1;//被标记          }      }   }   co=-1;   printf("impossible\n");}void print(int k){    if(act[k].step==-1)        return ;        print(act[k].step);    if(act[k].flag==0)        printf("DROP(1)\n");    if(act[k].flag==1)        printf("DROP(2)\n");    if(act[k].flag==2)        printf("FILL(1)\n");    if(act[k].flag==3)        printf("FILL(2)\n");    if(act[k].flag==4)        printf("POUR(2,1)\n");    if(act[k].flag==5)        printf("POUR(1,2)\n");}int main(){    int a,b,c;    cin>>a>>b>>c;    BFS(a,b,c);    print(k);    return 0;}

J-Fire!多入口BFS,规划时间

Joe works in a maze. Unfortunately, portions of the maze have
caught on fire, and the owner of the maze neglected to create a fire
escape plan. Help Joe escape the maze.
Given Joe’s location in the maze and which squares of the maze
are on fire, you must determine whether Joe can exit the maze before
the fire reaches him, and how fast he can do it.
Joe and the fire each move one square per minute, vertically or
horizontally (not diagonally). The fire spreads all four directions
from each square that is on fire. Joe may exit the maze from any
square that borders the edge of the maze. Neither Joe nor the fire
may enter a square that is occupied by a wall.

Input

The first line of input contains a single integer, the number of test
cases to follow. The first line of each test case contains the two
integers R and C, separated by spaces, with 1 ≤ R, C ≤ 1000. The
following R lines of the test case each contain one row of the maze. Each of these lines contains exactly
C characters, and each of these characters is one of:
• #, a wall
• ., a passable square
• J, Joe’s initial position in the maze, which is a passable square
• F, a square that is on fire
There will be exactly one J in each test case.

Output

For each test case, output a single line containing ‘IMPOSSIBLE’ if Joe cannot exit the maze before the
fire reaches him, or an integer giving the earliest time Joe can safely exit the maze, in minutes.

Sample Input

24 4#####JF##..##..#3 3####J.#.F

Sample Output

3
IMPOSSIBLE
题目大意:J想要逃出迷宫,迷宫有多处火点标记为M,M向四周蔓延,问J是否能逃出迷宫,能的话输出最短时间
思路,对所有的火点M进行BFS查找所有空地着火的最先时间
然后对J的路径进行BFS,找出路线记录时间
主要就是各种check条件

//本题M的初始个数不知道,因此考虑多个M的情况;//先对所有M进行光搜,更新其到达所有空地的最小时间//对J进行广搜#include<iostream>#include<queue>#include<string.h>using namespace std;const int maxn=1005;char Map[maxn][maxn];int vis[maxn][maxn];int Time[maxn][maxn];int site[maxn][maxn];//记录M的坐标int m,n;//边界int to[4][2]={{1,0},{-1,0},{0,1},{0,-1}};struct node{    int x,y;    int floor;}cur,Next;//用nextc++会CEint checkout(int x,int y){   //逃出迷宫    if(x<1||x>m||y<1||y>n)        return 1;    return 0;}int check_J(int x,int y,int T){    if(Map[x][y]=='#'||vis[x][y]==1||Time[x][y]<=T) //着火事件小于等于J来到该点的时间,说明这个地方J不能到达        return 1;    return 0;}int check_M(int x,int y,int T){    if(Map[x][y]=='#'||Time[x][y]<=T||Map[x][y]==0)//最后卡在这里,看半天才看出来,火苗不能蔓延到地图之外        return 1;                                   //Time数组相当于标记,而且要将每块空地的着火时间更新为最小值    return 0;                                       //下次思路清晰一点,争取一遍过}void BFS_J(int sx,int sy){    queue<node>q;   cur.x=sx,cur.y=sy;   cur.floor=0;   vis[sx][sy]=1;   q.push(cur);   while(!q.empty())   {       cur=q.front();       q.pop();       if(checkout(cur.x,cur.y))        {            cout<<cur.floor<<endl;            return ;        }       for(int i=0;i<4;i++)       {           int nx,ny;           nx=cur.x+to[i][0];           ny=cur.y+to[i][1];         // cout<<nx<<' '<<ny<<' '<<cur.floor+1<<' '<<Time[nx][ny]<<endl;           if(check_J(nx,ny,cur.floor+1))            continue;            Next.x=nx;            Next.y=ny;            Next.floor=cur.floor+1;            vis[nx][ny]=1;            q.push(Next);       }   }   cout<<"IMPOSSIBLE"<<endl;}void BFS_M(int sx,int sy){   queue<node>q;   cur.x=sx,cur.y=sy;   cur.floor=0;//和时间同步   Time[sx][sy]=cur.floor;   q.push(cur);   while(!q.empty())   {       cur=q.front();       q.pop();       for(int i=0;i<4;i++)       {           int nx,ny;           nx=cur.x+to[i][0];           ny=cur.y+to[i][1];           if(check_M(nx,ny,cur.floor+1))            continue;            //cout<<nx<<' '<<ny<<' '<<cur.floor+1<<' '<<Time[nx][ny]<endl;            Next.x=nx;            Next.y=ny;            Next.floor=cur.floor+1;            Time[nx][ny]=min(Time[nx][ny],Next.floor);//记录M到达该空地最小的时间            //cout<<"Time"<<Time[nx][ny]<<endl;            q.push(Next);       }   }} int main() {     int t;     cin>>t;     while(t--)     {         int sx,sy;         memset(Map,0,sizeof(Map));         memset(vis,0,sizeof(vis));         memset(site,0,sizeof(site));         cin>>m>>n;         for(int i=0;i<=m+1;i++)            for(int j=0;j<=n+1;j++)            Time[i][j]=100000;         for(int i=1;i<=m;i++)            for(int j=1;j<=n;j++)         {             cin>>Map[i][j];             if(Map[i][j]=='J')             {                 sx=i;                 sy=j;             }             if(Map[i][j]=='F')                 site[i][j]=1;         }         for(int i=1;i<=m;i++)            for(int j=1;j<=n;j++)         {             if(site[i][j]==1)             BFS_M(i,j);         }         BFS_J(sx,sy);     }     return 0; }

N - Find a way(两个BFS,思路优化)

HDU - 2612
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.

Input

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

Output

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.

Sample Input

4 4Y.#@.....#..@..M4 4Y.#@.....#..@#.M5 5Y..@..#....#...@..M.#...#

Sample Output

66
88
66
题目大意:Y、M想约会在他们能到达的且所用时间和最小的KFC,输出时间
坑都在程序里

//说一下思路,分两次对每一个人进行BFS,遍历所有的KFC,//存储下每个KFC,这两个人到达时所用的时间time[maxn][2]//最后遍历time数组,找到最小的和。//注意Y,M的出发地不能通过相当于墙,如果一个KFC有一方无法到达,则这个KFC不符合条件,时间和舍去#include<iostream>#include<queue>#include<string.h>using namespace std;const int maxn=205;char Map[maxn][maxn];int vis[maxn][maxn];int flag;int time[maxn][maxn][2];//记录下到达同一个KFC的时间struct node{    int x,y;    int floor;//所走过的距离}cur,Next;int ex,ey;//KFC坐标int m,n;//矩阵范围int ans;//记录最短时间初始化为最大值int co;//记录KFC的个数int to[4][2]={{1,0},{-1,0},{0,1},{0,-1}};int check(int x,int y){    if(x<1||x>m||y<1||y>n||Map[x][y]=='#'||vis[x][y]==1)        return 1;    return 0;}void BFS(int sx,int sy){    int num=1;    queue<node>q;    cur.x=sx,cur.y=sy,cur.floor=0;    q.push(cur);    vis[sx][sy]=1;    while(!q.empty())    {        cur=q.front();        q.pop();        if(Map[cur.x][cur.y]=='@')            {    co++;                time[cur.x][cur.y][flag]=cur.floor;//flag=0,是Y的时间,flag=1是M的时间                 if(co==num)                    return ;            }        for(int i=0;i<4;i++)        {            int nx,ny;            nx=cur.x+to[i][0];            ny=cur.y+to[i][1];            if(check(nx,ny))                continue;            Next.x=nx,Next.y=ny;            Next.floor=cur.floor+1;            vis[nx][ny]=1;            q.push(Next);        }    }}int main(){   while(cin>>m>>n)   {       ans=10000000;      co=0;      memset(Map,0,m*n*sizeof(char));      memset(time,0,sizeof(time));       int x1,y1,x2,y2;       for(int i=1;i<=m;i++)        for(int j=1;j<=n;j++)        {            cin>>Map[i][j];            if(Map[i][j]=='Y')            {                x1=i,y1=j;                continue;            }            if(Map[i][j]=='M')            {                x2=i,y2=j; continue;            }            if(Map[i][j]=='@')            {                co++;            }        }          Map[x1][y1]='#';            Map[x2][y2]='#';           memset(vis,0,sizeof(vis));//注意每次BFS之前都要重置vis数组            flag=0; //对Y进行BFS            BFS(x1,y1);            memset(vis,0,sizeof(vis));            flag=1;//对M进行BFS            BFS(x2,y2);            for(int i=1;i<=m;i++)                for(int j=1;j<=n;j++)               {                if(Map[i][j]!='@')                   continue;                if(time[i][j][0]==0||time[i][j][1]==0)                    continue;                ans=min(time[i][j][0]+time[i][j][1],ans);                }        cout<<ans*11<<endl;   }   return 0;}