日志

有一个 n个点m𝑛𝑛个点 𝑚条边的无向图,请求出从 𝑠s到 t 𝑡的最短路长度。

#include <bits/stdc++.h>

using namespace std;

int numNodes, numEdges, sourceNode, targetNode;

vector<bool> visited(1000000, false);

struct Edge {

int to, weight, next = -1;

} graph[1000000];

vector<int> head(1000000, -1), distanceTo(1000000, INT_MAX);

int edgeCount = 0;

void addEdge(int from, int to, int weight) {

graph[edgeCount].to = to;

graph[edgeCount].weight = weight;

graph[edgeCount].next = head[from];

head[from] = edgeCount++;

}

struct Node {

int position, distance;

Node(int pos, int dist) : position(pos), distance(dist) {}

bool operator<(const Node& other) const {

return this->distance > other.distance;

}

};

priority_queue<Node> priorityQueue;

void dijkstra() {

distanceTo[sourceNode] = 0;

priorityQueue.push(Node(sourceNode, 0));

while (!priorityQueue.empty()) {

int currentNode = priorityQueue.top().position;

priorityQueue.pop();

if (!visited[currentNode]) {

visited[currentNode] = true;

for (int i = head[currentNode]; i != -1; i = graph[i].next) {

int neighbor = graph[i].to;

if (distanceTo[neighbor] > graph[i].weight + distanceTo[currentNode]) {

distanceTo[neighbor] = graph[i].weight + distanceTo[currentNode];

if (!visited[neighbor]) {

priorityQueue.push(Node(neighbor, distanceTo[neighbor]));

}

}

}

}

}

}

int main() {

cin >> numNodes >> numEdges >> sourceNode >> targetNode;

for (int i = 0; i < numEdges; i++) {

int from, to, weight;

cin >> from >> to >> weight;

addEdge(from, to, weight);

addEdge(to, from, weight);

}

dijkstra();

cout << distanceTo[targetNode];

return 0;

}

全部评论

相关推荐

2025-12-22 16:31
已编辑
桂林电子科技大学 Python
很奥的前端仔:如果你接了offer 临时又说不去 hr确实要多做一些工作。 当然如果是接offer之前当我没说
点赞 评论 收藏
分享
嵌入式的小白:面试少的,说明你的投递的岗位和简历匹配度不高,技术这个东西很杂的,你这种情况,建议 1.看看嵌入式招聘的岗位需求,会有不同大方向的,比如MCU,RTOS的,或者linux上驱动的,或者应用层的,这都是简单分类,但对技术要求差异很大的 2.结合你的经验,看能和哪类匹配上,就找对应类别的 3.简历和招聘岗位需求对着看下,看人家需要啥,你会啥,匹配度高才有会高概率有面试的
秋招的第一个offer,...
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务