专题测试四 图论 D - Dijkstra?

  1. 题目

    You are given a weighted undirected graph. The vertices are enumerated from 1 to n. Your task is to find the shortest path between the vertex 1 and the vertex n.

    Input

    The first line contains two integers n and m (2 ≤ n ≤ 105, 0 ≤ m ≤ 105), where n is the number of vertices and m is the number of edges. Following m lines contain one edge each in form aibi and wi (1 ≤ ai, bi ≤ n, 1 ≤ wi ≤ 106), where ai, bi are edge endpoints and wi is the length of the edge.

    It is possible that the graph has loops and multiple edges between pair of vertices.

    Output

    Write the only integer -1 in case of no path. Write the shortest path in opposite case. If there are many solutions, print any of them.

    Sample
    Input Output
    5 6
    1 2 2
    2 5 5
    2 3 4
    1 4 1
    4 3 3
    3 5 1
    
    1 4 3 5 
  2. 思路
    众所周知,一个题目里,如果题目里写了某个算法的名字,那么实际操作里面肯定不会......哦这次还真的用了这个算法。
    题目很简单只是一个最短路径问题,但是直接上dijkstra会超时,要用优先队列优化一下,还要有一个前驱数组,存储每个节点的上一个中转点,然后递归输出
    很尴尬的是,因为忘了没有路径输出-1这件事,我WA了三次
  3. 代码
    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    #include<queue>
    using namespace std;
    
    const int maxn = 100010;
    const long long INF=1145141919810;
    
    struct edge {
        int v, w;
    };
    
    struct node {
        long long dis;int u;
    
        bool operator>(const node& a) const { return dis > a.dis; }
    };
    
    vector<edge> e[maxn];
    long long dis[maxn];bool vis[maxn];int pre[maxn];
    priority_queue<node, vector<node>, greater<node> > q;
    
    void dijkstra(int n, int s) {
        for(int i=1;i<=n;i++) dis[i]=INF;
        dis[s] = 0;
        q.push({0, s});
        while (!q.empty()) {
            int u = q.top().u;
            q.pop();
            if (vis[u]) continue;
            vis[u] = 1;
    		if (vis[n]) return;
            for (auto ed : e[u]) {
                int v = ed.v, w = ed.w;
                if (dis[v] > dis[u] + w) {
                    dis[v] = dis[u] + w;
    				pre[v] = u;
                    q.push({dis[v], v});
                }
            }
        }
    }
    
    void print(int x)
    {
    	if(pre[x]==0) return;
    	print(pre[x]);
    	cout<<" "<<x;
    }
    
    int main()
    {
    	int n,m;
    	scanf("%d%d",&n,&m);
    	int a,b,w;
    	while(m--)
    	{
    		scanf("%d%d%d",&a,&b,&w);
    		edge aa,bb;
    		aa.v=b,aa.w=w;
    		bb.v=a,bb.w=w;
    		e[a].push_back(aa);
    		e[b].push_back(bb);
    	}
    	dijkstra(n,1);
    	if(dis[n]<INF-1)
    	{
    		pre[1] = 0;
    		cout<< 1 ;
    		print(n);
    		cout<<endl;
    	}
    	else
    	{
    		cout<< -1 <<endl;
    	}
    	return 0;
    }
posted @ 2022-02-21 15:01  Benincasa  阅读(28)  评论(0编辑  收藏  举报