浙大数据结构第七周之Saving James Bond - Hard Version

题目详情:

This time let us consider the situation in the movie "Live and Let Die" in which James Bond, the world's most famous spy, was captured by a group of drug dealers. He was sent to a small piece of land at the center of a lake filled with crocodiles. There he performed the most daring action to escape -- he jumped onto the head of the nearest crocodile! Before the animal realized what was happening, James jumped again onto the next big head... Finally he reached the bank before the last crocodile could bite him (actually the stunt man was caught by the big mouth and barely escaped with his extra thick boot).

Assume that the lake is a 100 by 100 square one. Assume that the center of the lake is at (0,0) and the northeast corner at (50,50) .The central island is a disk centered at (0,0) with the diameter of 15 . A number of crocodiles are in the lake at various positions. Given the coordinates of each crocodile and the distance that James could jump, you musttell him a shortest path to reach one of the banks. The length of a path is the number of jumps that James has to make.

Input Specification:

Each input file contains one test case. Each case starts with a line containing two positive integers N (≤100), the number of crocodiles, and D, the maximum distance that James could jump. Then N lines follow, each containing the (x,y) location of a crocodile. Note that no two crocodiles are staying at the same position.

Output Specification:

For each test case, if James can escape, output in one linethe minimum number of jumps he must make. Then starting from the next line, output the position (x,y) of each crocodile on the path, each pair in one line, from the island to the bank. If it is impossible for James to escape that way, simply give him 0 as the number of jumps. If there are many shortest paths, just output the one with the minimum first jump, which is guaranteed to be unique.

Sample Input 1:

17 15
10 -21
10 21
-40 10
30 -50
20 40
35 10
0 -10
-25 22
40 -40
-30 30
-10 22
0 11
25 21
25 10
10 10
10 35
-30 10

Sample Output 1:

4
0 11
10 21
10 35

Sample Input 2:

4 13
-12 12
12 12
-12 -12
12 -12

Sample Output 2:

0

简单翻译:

相比于简单版本,要求找到最短路

主要思路:

麻了,搞了一星期,在Dijkstra和BFS反复横跳,最后其实是BFS + Dijkstra的组合拳模式解决

设置path[n](path[i]表示节点i的上一级节点),这样可以利用堆栈回溯

(一):数据初始化,将读入的鳄鱼按从近到远排序

(二):构建图

第一次写错误:

代码实现:

#include <cstdio>
#include <cmath>
#include <algorithm>
#include <stack>
#include <queue>

const int INF = 0x3f3f3f3f;

struct Point {
    int x, y;
};

int jumpDist(Point *point, int pos1, int pos2);
int findSrc(int *path, int pos);
int srcDist(Point *point, int pos);
int BFS(Point *point, int *path, int n, int r);

int main() {
    int n, r;
    scanf("%d %d", &n, &r);
    Point point[n];
    for (int i = 0; i < n; i++) {
        scanf("%d %d", &point[i].x, &point[i].y);
    }

    if (7.5 + r >= 50) {                    // 如果一步就可以跳到边界,直接输出1即可。最后一个测试点会卡这种情况
        printf("1\n");
    }
    else {
        int path[n];                        // 数组的下标对应点的编号,用来记录该点的前一个点的编号
        std::fill(path, path + n, -1);      // 初始化为-1代表没有点可以跳跃到该点
        int minId = BFS(point, path, n, r); // 调用上述的BFS,返回的是跳跃的最后一个点的数组下标位置
        if (minId == -1) {                  // 如果返回-1说明找不到可以到达边界的路线
            printf("0\n");
        }
        else {
            std::stack<int> s;
            for (int i = minId; i != -1; i = path[i]) {
                s.push(i);                  // 把整个跳跃过程经过的点的下标位置压入栈中,压的顺序是从终点到始点
            }
            printf("%d\n", s.size() + 1);
            while (!s.empty()) {
                int i = s.top();            // 把每个点的下标位置弹出来,打印的顺序是从始点到终点
                s.pop();
                printf("%d %d\n", point[i].x, point[i].y);
            }
        }
    }

    return 0;
}

// 用来计算两个点的欧氏距离的平方
int jumpDist(Point *point, int pos1, int pos2) {
    return (point[pos1].x - point[pos2].x) * (point[pos1].x - point[pos2].x) + (point[pos1].y - point[pos2].y) * (point[pos1].y - point[pos2].y);
}

// 用来找到经过该点的路径的始点
int findSrc(int *path, int pos) {
    return path[pos] == -1 ? pos : findSrc(path, path[pos]);
}

// 用来计算该点与原点(0, 0)的欧氏距离的平方
int srcDist(Point *point, int pos) {
    return point[pos].x * point[pos].x + point[pos].y * point[pos].y;
}

int BFS(Point *point, int *path, int n, int r) {
    int dist[n], minId = -1, minDist = INF; // minDist用来记录最小的跳跃次数,minId用来记录最小跳跃次数对应的那条路线的最后一个点
    std::fill(dist, dist + n, INF);
    std::queue<int> q;
    for (int i = 0; i < n; i++) {
        int d = srcDist(point, i);
        if (d > 7.5 * 7.5 && d <= (7.5 + r) * (7.5 + r)) {  // 如果该点不再给定的原点范围内,并且可以从原点范围跳跃到该点
            q.push(i);      // 就把该点压入队列中
            dist[i] = 1;    // 同时到该点的跳跃次数+1
        }
    }

    while (!q.empty()) {    // 队列不为空
        int tmp = q.front();
        q.pop();
        for (int i = 0; i < n; i++) {
            int d = jumpDist(point, tmp, i);
            // 如果不可以跳跃到这个点,或者这条鳄鱼在岛上,忽略这个点,走下一次的循环
            if (d > r * r || srcDist(point, i) <= 7.5 * 7.5) continue;
            //经过上面语句筛选后下来的节点都是可以跳到且不在岛上的节点
            //下面这个if语句用了Dijkstra思想
            if (dist[tmp] + 1 < dist[i]) {  // 如果从原点经过tmp跳跃到该点的次数比之前直接从原点跳跃到该点的跳跃次数小
                dist[i] = dist[tmp] + 1;    // 更新为更小的跳跃次数
                path[i] = tmp;              // 同时把到该点点的前一个节点更新为tmp
                q.push(i);                  // 把该点压入队列
            }

            if (50 - abs(point[i].x) <= r || 50 - abs(point[i].y) <= r) {   // 如果可以从该点跳跃到边界
                if (minDist > dist[i]) {    // 到该点的跳跃次数比之前记录的最小跳跃次数小
                    minDist = dist[i];      // 更新最小跳跃次数
                    minId = i;              // 更新对应路径的最后一个点
                }
                else if (minDist == dist[i]) {          // 如果最小的跳跃次数相同
                    int src1 = findSrc(path, minId);    // 找到minId对应路径的的始点
                    int src2 = findSrc(path, i);        // 找到该点对应路径的始点
                    if (srcDist(point, src2) < srcDist(point, src1)) minId = i; // 如果该点对应路径的始点到原点的距离更小,更新minId
                }
            }
        }
    }

    return minId;
}

有问题的代码:

排过序,用Dijkstra

/*
建图
图的权值
最短路
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAX_NODE_NUMS 105
#define INFINITY 1005
#define RADIUS 7.5
#define BOUNDRY 50
#define FALSE 0
#define TRUE 1
#define NONE -1
typedef int bool;
typedef struct MatrixGrapbNode MatrixGrapbNode;
typedef MatrixGrapbNode* MGraph;
struct MatrixGrapbNode {
    int VertexNums, EdgeNums;
    int Weight[MAX_NODE_NUMS][MAX_NODE_NUMS];
};
/*建图,难点是如何判断在两个节点之间插入边*/
MGraph CreateEmptyGraph(int vertexNums) {
    MGraph graph = (MGraph)malloc(sizeof(MatrixGrapbNode));
    graph->VertexNums = vertexNums;
    for(int i = 0; i < vertexNums; i++) {
        for(int j = 0; j < vertexNums; j++) {
            if(i == j) {
                graph->Weight[i][j] = FALSE;
            }
            else {
                graph->Weight[i][j] = INFINITY;
            }
        }
    }
    return graph;
}
void InsertEdge(int start, int end, int weight, MGraph graph) {
    graph->Weight[start][end] = weight;
    graph->Weight[end][start] = weight;
    return;
}
typedef struct Node Node;
struct Node {
    int xLabel, yLabel;
};
Node node[MAX_NODE_NUMS];
int DistanceSquare(int difX, int difY) {
    return pow(difX, 2) + pow(difY, 2);
}
bool CanJump(int start, int end, int jumpDistance, int vertexNums) {
    bool flag = FALSE;
    int x1 = node[start].xLabel; int y1 = node[start].yLabel;
    int x2 = node[end].xLabel; int y2 = node[end].yLabel;
    int difX = x1 - x2; int difY = y1 - y2;
    if(start == 0 || end == 0) {
        if(DistanceSquare(difX, difY) <= pow(RADIUS + jumpDistance, 2)) {
            flag = TRUE;
        }
    }
    else if(start == vertexNums - 1 || end == vertexNums - 1) {
        if(abs(difX) <= jumpDistance || abs(difY) <= jumpDistance) {
            flag = TRUE;
        }
    }
    else {
        if(DistanceSquare(difX, difY) <= pow(jumpDistance, 2)) {
            flag = TRUE;
        }
    }
    return flag;
}
void Swap(Node* a, Node* b) {
    Node temp = *a;
    *a = *b;
    *b = temp;
    return;
}
void Sort(MGraph graph) {
    for(int i = 1; i < graph->VertexNums - 1; i++) {
        for(int j = i + 1; j < graph->VertexNums - 1; j++) {
            int distanceSquare1ToCenter = DistanceSquare(node[i].xLabel, node[i].yLabel);
            int distanceSquare2ToCenter = DistanceSquare(node[j].xLabel, node[j].yLabel);
            if(distanceSquare1ToCenter > distanceSquare2ToCenter) {
                Swap(&node[i], &node[j]);
            }
        }
    }
}
MGraph BuildGraph(int crocodileNums, int jumpDistance) {
    int vertexNums = crocodileNums + 2;
    MGraph graph = CreateEmptyGraph(vertexNums);
    //node[0].xLabel = 0; node[0].yLabel = 0;
    node[vertexNums - 1].xLabel = BOUNDRY; node[vertexNums - 1].yLabel = BOUNDRY;
    for(int i = 1; i <= crocodileNums; i++) {
        scanf("%d %d", &(node[i].xLabel), &(node[i].yLabel));
    }
    
    Sort(graph);
    for(int i = 0; i < vertexNums; i++) {
        for(int j = 0; j < vertexNums; j++) {
            if(CanJump(i, j, jumpDistance, vertexNums)) {
                InsertEdge(i, j, TRUE, graph);
            }
        }
    }
    return graph;
}
int FindNearest(MGraph graph, int dis[], int collected[]) {
    int minDis = INFINITY;
    int nearestNode = NONE;
    for(int i = 0; i < graph->VertexNums; i++) {
        if(collected[i] == FALSE && dis[i] < minDis) {
            minDis = dis[i];
            nearestNode = i;
        }
    }
    return nearestNode;
}
/*dikstra寻找最短路*/
void Dikistra(MGraph graph, int start) {
    int path[graph->VertexNums];    //path[i]记录的是节点i的上一级节点
    int dis[graph->VertexNums];     //dis[i]记录的是从起点到节点i的距离
    int collected[graph->VertexNums];   //collected[i]记录的是当前节点i有没有访问过

    /*初始化*/
    for(int i = 0; i < graph->VertexNums; i++) {
        dis[i] = graph->Weight[start][i];
        if(dis[i] < INFINITY) {
            path[i] = start;
        }
        else {
            path[i] = NONE;
        }
        collected[i] = FALSE;
    }
    //先将起点放入集合
    dis[start] = 0;
    collected[start] = TRUE;
    
    while(TRUE) {
        int nearest = FindNearest(graph, dis, collected);
        if(nearest == NONE) {
            break;
        }
        collected[nearest] = TRUE;
        for(int i = 0; i < graph->VertexNums; i++) {
            if(collected[i] == FALSE && graph->Weight[nearest][i] < INFINITY) {
                if(graph->Weight[nearest][i] < 0) {
                    printf("%d", FALSE);
                    return;
                }
                if(dis[nearest] + graph->Weight[nearest][i] < dis[i]) {
                    dis[i] = dis[nearest] + graph->Weight[nearest][i];
                    path[i] = nearest;
                }
            }
        }
    }


    if(path[graph->VertexNums - 1] != NONE) {
        int shortestDistance = dis[graph->VertexNums - 1];  
        printf("%d\n", shortestDistance);
        Node* shortestWay[shortestDistance];
        for(int i = 0; i < shortestDistance; i++) {
            shortestWay[i] = NULL;
        } 
        int count = shortestDistance;   //当前还剩的节点数量
        int pathIndex = graph->VertexNums - 1;  //指向path的指针
        int shortestWayIndex = shortestDistance - 1;     //指向shortestWay的指针
        int parent = NONE;
        while(count) {
            shortestWay[count - 1] = &(node[pathIndex]); 
            pathIndex = path[pathIndex];
            count--;
        }
        for(int i = 0; i < shortestDistance - 1; i++) {
            printf("%d %d\n", shortestWay[i]->xLabel, shortestWay[i]->yLabel);
        }
    }    
    else {
        printf("%d", FALSE);
    }
    return;
}
int main() {
    int crocodileNums, jumpDistance;
    scanf("%d %d", &crocodileNums, &jumpDistance);
    MGraph graph = BuildGraph(crocodileNums, jumpDistance);
    Dikistra(graph, 0);
    free(graph);
    return 0;
}
相关推荐
pk_xz12345610 分钟前
使用Wikitext2数据集对Llama-7B和Llama3-8B模型进行50%权重剪枝的一般步骤和可能的实现方式
算法·llama·剪枝
C语言编程小刘 114 分钟前
C语言期末复习1.1
c语言·算法·leetcode
浊酒南街37 分钟前
决策树(理论知识3)
算法·决策树·机器学习
A懿轩A44 分钟前
C/C++ 数据结构与算法【哈夫曼树】 哈夫曼树详细解析【日常学习,考研必备】带图+详细代码
c语言·c++·学习·算法·哈夫曼树·王卓
思码逸研发效能1 小时前
在 DevOps 中,如何应对技术债务和系统复杂性,以确保可持续的研发效能和创新?
运维·算法·研发效能·devops·研发效能度量·效能度量
LuckyRich11 小时前
【贪心算法】贪心算法七
算法·贪心算法·哈希算法
HEU_firejef1 小时前
面试经典 150 题——数组/字符串(一)
数据结构·算法·面试
chenziang12 小时前
leetcode hot 全部子集
算法·leetcode·职场和发展
EdwardYange2 小时前
LeetCode 83 :删除排链表中的重复元素
数据结构·算法·leetcode·链表
nuyoah♂2 小时前
DAY37|动态规划Part05|完全背包理论基础、LeetCode:518. 零钱兑换 II、377. 组合总和 Ⅳ、70. 爬楼梯 (进阶)
算法·leetcode·动态规划