题解
2025-10-02 18:11:24
发布于:广东
3阅读
0回复
0点赞
这道题明显是最短路,要用dijkstra+堆优化,但需要稍微改变一下,
题目分析
给定一个带权无向图、目标顶点s和q个顶点,求这q个顶点到s的最短路。
朴素做法是对于每个顶点都跑一遍dijkstra,但q的范围是,这样时间复杂度为,最坏情况下要执行约次,显然超时。
这时候就该考虑将多源最短路转换成单源最短路,由于是无向图,那么我们可以反着计算,只需计算从顶点到各个顶点的距离即可。对于无向图来讲,和的最短路等价。
时间复杂度:
#include<bits/stdc++.h>
using namespace std;
int n,m,s,q,dist[200005];
vector<vector<pair<int,int> > > g(200005);
struct node
{
int v,w;
bool operator < (const node &other) const
{
return w>other.w;
}
};
void dijkstra()
{
priority_queue<node> q;
q.push({s,0});
dist[s]=0;
while (!q.empty())
{
int nv=q.top().v,nw=q.top().w;
q.pop();
//没有终止条件
for (auto G:g[nv])
{
if (dist[nv]+G.second<dist[G.first])
{
dist[G.first]=dist[nv]+G.second;
q.push({G.first,dist[G.first]});
}
}
}
}
int main()
{
cin >> n >> m >> s >> q;
int u,v,w;
memset(dist,0x3f,sizeof(dist));
while (m--)
{
cin >> u >> v >> w;
g[u].push_back({v,w});
g[v].push_back({u,w});
}
dijkstra();
while (q--)
{
cin >> u;
cout << dist[u] << endl; //查询仅需O(1)
}
return 0;
}
这里空空如也
有帮助,赞一个