12.10

include

include

include

include

include

include

using namespace std;

const int INF = numeric_limits::max();

// 邻接表节点
struct Edge {
int to; // 目标顶点
int weight; // 权值
Edge(int t, int w) : to(t), weight(w) {}
};

class Graph {
private:
int V; // 顶点数
vector<vector> adj; // 邻接表
vector vertices; // 顶点值

public:
Graph(int v) : V(v), adj(v) {}

// 设置顶点值
void setVertices(const vector<int>& verts) {
    vertices = verts;
}

// 添加边
void addEdge(int from, int to, int weight) {
    adj[from].push_back(Edge(to, weight));
}

// Dijkstra算法求最短路径
vector<int> dijkstra(int start, int end) {
    // 距离数组
    vector<int> dist(V, INF);
    // 前驱节点数组
    vector<int> prev(V, -1);
    // 是否已找到最短路径
    vector<bool> visited(V, false);
    
    // 优先队列(最小堆),存储(距离, 顶点)
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
    
    // 初始化起点
    dist[start] = 0;
    pq.push({0, start});
    
    while (!pq.empty()) {
        // 取出当前距离最小的顶点
        int u = pq.top().second;
        pq.pop();
        
        // 如果已访问过,跳过
        if (visited[u]) continue;
        visited[u] = true;
        
        // 如果已经找到终点,可以提前结束
        if (u == end) break;
        
        // 遍历所有邻接边
        for (const Edge& edge : adj[u]) {
            int v = edge.to;
            int weight = edge.weight;
            
            // 松弛操作
            if (!visited[v] && dist[u] != INF && dist[u] + weight < dist[v]) {
                dist[v] = dist[u] + weight;
                prev[v] = u;
                pq.push({dist[v], v});
            }
        }
    }
    
    // 构建路径
    vector<int> path;
    if (dist[end] == INF) {
        // 没有路径
        return path;
    }
    
    // 从终点回溯到起点
    stack<int> tempPath;
    int current = end;
    while (current != -1) {
        tempPath.push(current);
        current = prev[current];
    }
    
    // 反转路径
    while (!tempPath.empty()) {
        path.push_back(tempPath.top());
        tempPath.pop();
    }
    
    return path;
}

};

int main() {
int V, E;
cin >> V >> E;

Graph graph(V);

// 读取顶点值
vector<int> vertices(V);
for (int i = 0; i < V; i++) {
    cin >> vertices[i];
}
graph.setVertices(vertices);

// 读取边
for (int i = 0; i < E; i++) {
    int from, to, weight;
    cin >> from >> to >> weight;
    graph.addEdge(from, to, weight);
}

// 读取起点和终点
int start, end;
cin >> start >> end;

// 计算最短路径
vector<int> path = graph.dijkstra(start, end);

// 输出结果
if (path.empty()) {
    cout << "No path found!" << endl;
} else {
    for (size_t i = 0; i < path.size(); i++) {
        if (i > 0) cout << "-->";
        cout << path[i];
    }
    cout << endl;
}

return 0;

}

posted @ 2025-12-22 08:11  Cx330。  阅读(3)  评论(0)    收藏  举报