• DijKstra算法普通+堆优化链式向前星


    朴素版本

    #include<bits/stdc++.h>
    using namespace std;
    const int maxn = 10010;
    const int inf = 0x3f3f3f3f;
    int a[maxn][maxn],dis[maxn],visit[maxn],n,m,s,t;
    void init() {
    	for(int i = 1; i <= n; i++)
    		for(int j = 1; j <= n; j++)
    			if(i == j)	a[i][j] = 0;
    			else	a[i][j] = inf;
    }
    void Dij() {
    	for(int i = 1; i <= n; i++)	dis[i] = a[s][i];
    	dis[s] = 0, visit[s] = 1;
    	int minn,su;
    	for(int j = 1; j < n; j++) {
    		minn = inf, su = -1;
    		for(int i = 1; i <= n; i++)
    			if(!visit[i] && dis[i] < minn) {
    				minn = dis[i];
    				su = i;
    			}
    		visit[su] = 1;
    		for(int i = 1; i <= n; i++)
    			if(!visit[i])
    				dis[i] = min(dis[i],dis[su] + a[su][i]);
    	}
    	cout << dis[t] <<endl;
    }
    int main() {
    	cin >> n >> m >> s >> t;
    	init();
    	for(int i = 1; i <= m; i++) {
    		int x,y;
    		cin >> x >> y;
    		cin >> a[x][y];
    	}
    	Dij();
    	return 0;
    }
    

    堆优化加链式向前星

    #include<bits/stdc++.h>
    using namespace std;
    const int inf = 0x3f3f3f3f;
    const int maxn = 1e5 + 10;
    struct edge {
    	int to,value,next;
    }a[2 * maxn];
    struct node {
    	int x,pos;
    	node(int a,int b) : x(a), pos(b) { }
    	bool operator < (const node &t) const {
    		return t.x < x;
    	}
    };
    int n, m, visit[maxn], dis[maxn], s, head[maxn],cnt = 1;
    void add(int x,int y,int z) {
    	a[cnt].to = y;
    	a[cnt].value = z;
    	a[cnt].next = head[x];
    	head[x] = cnt++;
    }
    void Dij () {
    	for(int i = 1; i <= n; i++)	dis[i] = inf;
    	dis[s] = 0; visit[s] = 1;
    	priority_queue<node>q;
    	q.push(node(0,s));
    	while(!q.empty()) {
    		node temp = q.top();
    		q.pop();
    		int x = temp.x, pos = temp.pos;
    		if(dis[pos] < x) continue;
    		for(int i = head[pos]; i; i = a[i].next) {
    			if(dis[a[i].to] > dis[pos] + a[i].value) {
    				dis[a[i].to] = dis[pos] + a[i].value;
    				q.push(node(dis[a[i].to],a[i].to));
    			}
    		}
    	}
    	for(int i = 1; i <= n; i++)
    		cout << dis[i] << " ";
    	cout <<endl;
    }
    int main() {
    	int x, y, z;
    	cin >> n >> m >> s;
    	for(int i = 0; i < m; i++) {
    		cin >> x >> y >> z;
    		add(x,y,z);
    	}
    	Dij();
    	return 0;
    }
    
  • 相关阅读:
    mergeKLists
    generateParenthesis
    removeNthFromEnd
    Codeforces Round #632 (div.2) C. Eugene and an array
    Spring中@Import的三种情况
    自定义Spring Boot starter
    Java 注解
    Eclipse安装Lombok插件
    java 类加载系统
    Centos系统中忘了root密码怎么办
  • 原文地址:https://www.cnblogs.com/lifehappy/p/12601192.html
Copyright © 2020-2023  润新知