1 条题解

  • 1
    @ 2023-8-11 10:37:11

    一开始以为是最小流,最后却是堆优化dijkstra

    #include <bits/stdc++.h>
    using namespace std;
    
    const int N = 100000,INF = 0x3f3f3f3f;
    
    int to[N],ne[N],w[N],dist[N],head[N],tot,n,m,st1,ed;
    bool st[N];
    
    void add(int u,int v,int c)
    {
    	to[tot] = v;w[tot] = c;ne[tot] = head[u];head[u] = tot++;
    }
    
    int dijkstra()
    {
    	memset(dist,INF,sizeof dist);
    	priority_queue<pair<int,int> > heap;
    	dist[st1] = 0;
    	heap.push({0,st1});
    	while(heap.size())
    	{
    		int t = heap.top().second;heap.pop();
    		if(st[t]) continue;
    		for(int i=head[t];i!=-1;i = ne[i])
    		{
    			int j = to[i],k = w[i];
    			if(dist[j]>dist[t]+k)
    			{
    				dist[j] = dist[t]+k;
    				heap.push({-dist[j],j});
    			}
    		}
    	}
    	if(dist[ed] == INF) return -1;
    	else return dist[ed];
    }
    
    int main()
    {
    	cin >> n >> m >> st1 >> ed;
    	memset(head,-1,sizeof head);
    	for(int i=0;i<m;i++)
    	{
    		int a,b,c;
    		cin >> a >> b >> c;
    		add(a,b,c);
    		add(b,a,c);
    	}
    	int ans = dijkstra();
    	cout << ans;
    	return 0;
    }
    
    • 1

    信息

    ID
    392
    时间
    1000ms
    内存
    128MiB
    难度
    10
    标签
    递交数
    6
    已通过
    4
    上传者