zoukankan      html  css  js  c++  java
  • 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;
    }
    
  • 相关阅读:
    Unity攻击敌人时产生泛白效果
    将网页发布到远程windows server
    IIS服务器添加网站
    ASP.NET添加Mysql数据源
    ASP.NET网页VS利用文件系统发布
    爱的印记
    生如夏花之绚烂,死如秋叶之静美
    WordPress函数小结
    设置WordPress文章关键词自动获取,文章所属分类名称,描述自动获取文章内容,给文章的图片自动加上AlT标签
    童年的流逝
  • 原文地址:https://www.cnblogs.com/lifehappy/p/12601192.html
Copyright © 2011-2022 走看看