bfs应用最短路径查找--三道基础题

  用BFS找最短路的基本思路为每次搜索到一个点或状态判断是否可以更新该点的最小值,若可以则放进队列中去。。。


下面这三道题目都是用BFS求最短路径的


题目1:
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?

Input
Line 1: Two space-separated integers: N and K
Output
Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.
Sample Input
5 17
Sample Output
4


        
  
Hint
The fastest way for Farmer John to reach the fugitive cow is to move along the following path: 5-10-9-18-17, which takes 4 minutes. 


思路:将每次可以到的店放进队列中

#include<iostream>
#include<queue>
using namespace std;
queue<int>q;
int main(){
    int dp[200010],i,n,m,u,v,k,j;
    while(cin>>n>>m){
    for(i=0;i<=200000;i++) dp[i]=1000000;
    dp[n]=0;
    for(q.push(n);!q.empty();q.pop()){
        u=q.front();
        if(u+1<=100005&&dp[u+1]>dp[u]+1){
            dp[u+1]=dp[u]+1;
            q.push(u+1);
        }
        if(u*2<=151000&&dp[u*2]>dp[u]+1){  //注意将上界定为150000,
            dp[u*2]=dp[u]+1;
            q.push(u*2);
        }
        if(u-1>=0&&dp[u-1]>dp[u]+1){
            dp[u-1]=dp[u]+1;
            q.push(u-1);
        }
    }
    cout<<dp[m]<<endl;
    }
    return 0;
}

题目2:

Recently, Mike was very busy with studying for exams and contests. Now he is going to chill a bit by doing some sight seeing in the city.

City consists of n intersections numbered from 1 to n. Mike starts walking from his house located at the intersection number 1 and goes along some sequence of intersections. Walking from intersection number i to intersection j requires |i - j| units of energy. The total energy spent by Mike to visit a sequence of intersections p1 = 1, p2, ..., pk is equal to units of energy.

Of course, walking would be boring if there were no shortcuts. A shortcut is a special path that allows Mike walking from one intersection to another requiring only 1 unit of energy. There are exactly n shortcuts in Mike's city, the ith of them allows walking from intersection i to intersection ai (i ≤ ai ≤ ai + 1) (but not in the opposite direction), thus there is exactly one shortcut starting at each intersection. Formally, if Mike chooses a sequence p1 = 1, p2, ..., pk then for each 1 ≤ i < k satisfying pi + 1 = api and api ≠ pi Mike will spend only 1 unit of energy instead of |pi - pi + 1| walking from the intersection pi to intersection pi + 1. For example, if Mike chooses a sequence p1 = 1, p2 = ap1, p3 = ap2, ..., pk = apk - 1, he spends exactly k - 1 units of total energy walking around them.

Before going on his adventure, Mike asks you to find the minimum amount of energy required to reach each of the intersections from his home. Formally, for each 1 ≤ i ≤ n Mike is interested in finding minimum possible total energy of some sequence p1 = 1, p2, ..., pk = i.

Input

The first line contains an integer n (1 ≤ n ≤ 200 000) — the number of Mike's city intersection.

The second line contains n integers a1, a2, ..., an (i ≤ ai ≤ n , , describing shortcuts of Mike's city, allowing to walk from intersection i to intersection ai using only 1 unit of energy. Please note that the shortcuts don't allow walking in opposite directions (from ai to i).

Output

In the only line print n integers m1, m2, ..., mn, where mi denotes the least amount of total energy required to walk from intersection 1 to intersection i.

Example
Input
3
2 2 3
Output
0 1 2 
Input
5
1 2 3 4 5
Output
0 1 2 3 4 
Input
7
4 4 4 4 7 7 7
Output
0 1 2 1 2 3 3 
Note

In the first sample case desired sequences are:

1: 1; m1 = 0;

2: 1, 2; m2 = 1;

3: 1, 3; m3 = |3 - 1| = 2.

In the second sample case the sequence for any intersection 1 < i is always 1, i and mi = |1 - i|.

In the third sample case — consider the following intersection sequences:

1: 1; m1 = 0;

2: 1, 2; m2 = |2 - 1| = 1;

3: 1, 4, 3; m3 = 1 + |4 - 3| = 2;

4: 1, 4; m4 = 1;

5: 1, 4, 5; m5 = 1 + |4 - 5| = 2;

6: 1, 4, 6; m6 = 1 + |4 - 6| = 3;

7: 1, 4, 5, 7; m7 = 1 + |4 - 5| + 1 = 3.


#include<iostream>
#include<queue>
#include<string.h>
using namespace std;
queue<int>q;
int main(){
    int A[200010],dp[200010],n,u,v,i;
    cin>>n;
    for(i=1;i<=n;i++) cin>>A[i];
    memset(dp,1000000,sizeof(dp));
    dp[1]=0;
    for(q.push(1);!q.empty();q.pop()){
        u=q.front();
        v=u+1;
        if(dp[v]>dp[u]+1&&v<=n){
            dp[v]=dp[u]+1;
            q.push(v);
        }
        v=u-1;
        if(dp[v]>dp[u]+1&&v>=1){
            dp[v]=dp[u]+1;
            q.push(v);
        }
        v=A[u];
        if(dp[v]>dp[u]+1){
            dp[v]=dp[u]+1;
            q.push(v);
        }
    }
    for(i=1;i<n;i++) cout<<dp[i]<<" ";
    cout<<dp[n];
    return 0;
}



题目3:

Background
    Mr Somurolov, fabulous chess-gamer indeed, asserts that no one else but him can move knights from one position to another so fast. Can you beat him?
    The Problem
    Your task is to write a program to calculate the minimum number of moves needed for a knight to reach one point from another, so that you have the chance to be faster than Somurolov.
    For people not familiar with chess, the possible knight moves are shown in Figure 1.

                                                                 
Input
    The input begins with the number n of scenarios on a single line by itself.
    Next follow n scenarios. Each scenario consists of three lines containing integer numbers. The first line specifies the length l of a side of the chess board (4 <= l <= 300). The entire board has size l * l. The second and third line contain pair of integers {0, ..., l-1}*{0, ..., l-1} specifying the starting and ending position of the knight on the board. The integers are separated by a single blank. You can assume that the positions are valid positions on the chess board of that scenario.
Output
    For each scenario of the input you have to calculate the minimal amount of knight moves which are necessary to move from the starting point to the ending point. If starting point and ending point are equal,distance is zero. The distance must be written on a single line.
Sample Input

    3
    8
    0 0
    7 0
    100
    0 0
    30 50
    10
    1 1
    1 1

Sample Output

    5
    28
    0

#include<iostream>
#include<queue>
#include<stdio.h>
#include<string.h>
using namespace std;
struct Q{
   int x,y;
};
queue<Q>q;
int main(){
    int dp[310][310],dx[]={-1,-1,1,1,-2,-2,2,2},dy[]={-2,2,-2,2,1,-1,1,-1},n,sx,sy,fx,t,fy,i;
    Q u,v,s;
    cin>>t;
    while(t--){
        scanf("%d",&n);
        scanf("%d%d%d%d",&sx,&sy,&fx,&fy);
        memset(dp,1000000,sizeof(dp));
        s.x=sx;
        s.y=sy;
        dp[sx][sy]=0;
        for(q.push(s);!q.empty();q.pop()){
            u=q.front();
            for(i=0;i<=7;i++){
                v.x=u.x+dx[i];
                v.y=u.y+dy[i];
                if(v.x>=0&&v.x<n&&v.y>=0&&v.y<n&&dp[v.x][v.y]>dp[u.x][u.y]+1){
                    dp[v.x][v.y]=dp[u.x][u.y]+1;
                    q.push(v);

                }
            }
        }
        printf("%d\n",dp[fx][fy]);

    }
    return 0;
}




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
#include #include #define N1 9 #define N2 8 #define T N1*N2 #define M 4 char B[N1+1][N2+1]; int count=0; //记录路径条数 typedef struct node1 { int a1; int a2; }find,direct[M+1]; typedef struct { int b1; int b2; int id; }site; typedef struct //顺序栈 { site ht[T]; int top; }Stack; void Push(Stack *s,int a,int b) { s->top++; s->ht[s->top].b1=a; s->ht[s->top].b2=b; } void Gettop(Stack * s,int *a,int *b) { *a=s->ht[s->top].b1; *b=s->ht[s->top].b2; } void create(char *a) //从文件读出迷宫(正确) { int i=0,j=0,p=1; char x; FILE *fp; fp=fopen("in.txt","r"); if(fp==NULL) { printf("文件不能打开!\n"); exit(0); } x=fgetc(fp); while(x!=EOF) { if(x=='0') { i++; a[i]=x; } if(x=='1') { i++; a[i]=x; } x=fgetc(fp); } printf(" ~~~~~~~生成迷宫~~~~~~~\n"); x=fgetc(fp); while(p<=T) //用二维数组b记录迷宫每个位置是否可行 { for(i=1;i<=N1;i++) for(j=1;j<=N2;j++) { B[i][j]=a[p]; p++; } } printf(" "); printf("■■■■■■■■■■■■\n"); printf(" ■"); printf(" ■\n"); for(i=1;i<=N1;i++) { printf(" "); printf("■ "); for(j=1;jht[s1->top].id=id; B[x][y]='*'; while(s1->top>0) { Gettop(s1,&x,&y); id=s1->ht[s1->top].id; if(x==B1&&y==B2) { count++; fprintf(fp,"%d%c%c",count,':',' '); printf("第 %d 条路径(长度为%d):\n",count,s1->top); s1->ht[s1->top].id=0; for(i=1;itop;i++) { printf("(%d,%d,%d)->",s1->ht[i].b1,s1->ht[i].b2,s1->ht[i].id); fprintf(fp,"%c%d%c%d%c%d%c%c",'(',s1->ht[i].b1,',',s1->ht[i].b2,',',s1->ht[i].id,')',' '); if(i==0) fprintf(fp,"%c%c%c%c",'\n',' ',' ',' '); if(i%8==0) printf("\n"); } fprintf(fp,"%c",'\n'); printf("结束!\n\n"); if(s1->toptop=s1->top; min=s1->top; for(i=1;itop;i++) s2->ht[i]=s1->ht[i]; } B[x][y]='0'; s1->top--; //退栈(s1->top--) Gettop(s1,&x,&y); id=s1->ht[s1->top].id; } fun=0; while(idht[s1->top].b1; y=s1->ht[s1->top].b2; x=x+p[id].a1; y=y+p[id].a2; if(x==0||y==0||x>N1||y>N2) continue; if(B[x][y]=='0') { fun=1; break; } } if(fun==1) //找到通路 { s1->ht[s1->top].id=id; Push(s1,x,y); B[x][y]='*'; s1->ht[s1->top].id=0; } else { x=s1->ht[s1->top].b1; y=s1->ht[s1->top].b2; B[x][y]='0'; s1->top--; } } if(count==0) printf(" 无路径!\n"); else { printf("\n\n\n "); printf("所有路径已存储在文件%s 中,请去查找!\n\n",filename); } return 1; } void Print(Stack *s2,char filename[]) { int i; FILE *fp; fp=fopen(filename,"a+"); if(fp==NULL) { printf("文件不能打开!\n"); exit(0); } if(count!=0) { fprintf(fp,"%s","最短路径为:"); fprintf(fp,"%c",'\n'); printf(" "); printf("%s\n","**********最短路径**********\n"); for(i=1;itop;i++) { printf("(%d,%d,%d) ->",s2->ht[i].b1,s2->ht[i].b2,s2->ht[i].id); fprintf(fp,"%c%d%c%d%c%d%c%c",'(',s2->ht[i].b1,',',s2->ht[i].b2,',',s2->ht[i].id,')',' '); if(i==0) fprintf(fp,"%c",'\n'); if(i%7==0) printf("\n"); } fprintf(fp,"%c",'\n'); printf("结束!\n"); printf("(最短路径长度: %d)\n",s2->top); } } void main() //主函数 { char a[T+1]; //二维数组b记录迷宫的每个位置 char filename1[20],filename2[20]; int x1,x2,y1,y2,k; Stack *s1,*s2; direct f1; f1[1].a1=0; f1[1].a2=1; //判断方向(右) f1[2].a1=1; f1[2].a2=0; //(下) f1[3].a1=0; f1[3].a2=-1; //(左) f1[4].a1=-1; f1[4].a2=0; //(上) s1=(Stack *)malloc(sizeof(Stack)); s2=(Stack *)malloc(sizeof(Stack)); s1->top=0; //指向栈顶(初始化栈) s2->top=0; create(a); printf("\n\n "); printf("请输入入口坐标: "); scanf("%d%d",&x1,&x2); printf(" "); printf("请输入出口坐标: "); scanf("%d%d",&y1,&y2); printf(" "); printf("请输入存储所有路径的文件名:"); scanf("%s",filename1); printf(" "); printf("请输入存储最短路径的文件名:"); scanf("%s",filename2); system("cls"); k=search(x1,x2,y1,y2,s1,s2,f1,filename1); if(k==1) Print(s2,filename2); printf("\n"); }

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值