ac 849 dijkstra

时间复杂度为n^2,这个算法之所以不能计算有负权路的原因是他不会走走过的点,比如 (a, b, -1) (a, c, 1) (c, b, -6)
Dijkstra算法可以很好地解决无负权图的最短路径问题,但如果出现了负权边,Dijkstra算法就会失效,例如图10-39中设置A为源点时,首先会将点B和点C的 dist值变为-1和1,接着由于点B的 dist值最小,因此用点B去更新其未访问的邻接点(虽然并没有)。在这之后点B标记为已访问,于是将无法被从点C出发的边CB更新,因此最后 dist[B]就是-1,但显然A到B的最短路径长度应当是A→C→B的-4。

#include<bits/stdc++.h>
using namespace std;

const int N = 510;
int n, m;
int dist[N];  //每个点到起点的最短距离
bool st[N];     // 判断某个点最短距离是否已经确定
int g[N][N];    //邻接矩阵

int dijkstra() {
    memset(dist, 0x3f, sizeof dist);
    dist[1] = 0;
    for (int i = 0;i < n; i ++) {
        int t = -1;
        for (int j = 1; j <= n; j++) {
            if (!st[j] && (t == -1 || dist[t] > dist[j])) t = j;  
        //在未被确定最短距离的点中找一个距离1这个点最近的点
        }           
        st[t] = true;
        
        for (int j = 1; j <= n; j ++) {
        //以上面找到的点为跳板找到是否有可以更新的节点
            dist[j] = min(dist[j], dist[t] + g[t][j]);   
        }
    }
    if (dist[n] == 0x3f3f3f3f) return -1;
    else return dist[n];
}
int main() {
    cin >> n >> m;
    
    memset(g, 0x3f, sizeof g);
    while(m --) {
        int a, b, c;
        cin >> a >> b >> c;
        g[a][b] = min(g[a][b], c);
    }
    int t = dijkstra();
    cout << t;
    return 0;
}

用优先队列的储存方式 求出(在未被确定最短距离的点中找一个距离1这个点最近的点)的时间复杂度为o(1) 堆中修改一个数字是 logn 乘m就是 mlogn

#include<bits/stdc++.h>
using namespace std;


typedef pair<int, int> PII;
const int N = 150010;
int n, m;
int h[N], w[N], e[N], ne[N], idx; //邻接表
int dist[N];  //每个点到起点的最短距离
bool st[N];     // 判断某个点最短距离是否已经确定

void add(int a, int b, int c) {
    e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++; 
}
int dijkstra() {
    memset(dist, 0x3f, sizeof dist);
    dist[1] = 0;
    
    priority_queue<PII, vector<PII>, greater<PII> > heap;
    //第一个参数T:元素(element)类型
    //第二个参数Container:必须是容器类型Container,用来存储元素(element),其类型必须是第一个参数
    //第三个参数Compare:比较形式,默认是less 比如这个就是less<PII>
    heap.push({0, 1});
    while(heap.size()) {
        auto t = heap.top();
        heap.pop();
        
        int ver = t.second, distance = t.first;
        if(st[ver]) continue;
        st[ver] = true;
        
        for (int i = h[ver]; i != -1; i = ne[i]) {
            int j = e[i];
            if (dist[j] > distance + w[i]) {
                dist[j] = distance + w[i];
                heap.push({dist[j], j});
            }
        }
        
    }
    
    if (dist[n] == 0x3f3f3f3f) return -1;
    return dist[n];
}
int main() {
    cin >> n >> m;
    
    memset(h, -1, sizeof h);
    while(m --) {
        int a, b, c;
        cin >> a >> b >> c;
        add(a, b, c);
    }
    int t = dijkstra();
    cout << t;
    return 0;
}
posted @ 2022-10-18 13:19  天然气之子  阅读(14)  评论(0编辑  收藏  举报