CodeForces 545E - Paths and Trees(最短路树)
题目链接 https://cn.vjudge.net/problem/CodeForces-545E
【题意】
给定一个n个结点m条边的无向图,并给出源点s,让你找出图中权值最小的最短路树,并输出这个权值
【思路】
对dijkstra算法稍作修改即可,在松弛操作的时候,在保留最短路的前提下,保正上一条边的权值是最小的,类似一种贪心的思想,最短路径确定的话,如果上一条边的权值最小,那么其余部分肯定会有更多的公共路径可以利用,最短路树的权值也就更小了。
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef ll type;
const ll inf=1e18;
const int maxn=300050;
struct Edge{
int from,to,id;
type dist;
Edge(int f,int t,type d,int i):from(f),to(t),dist(d),id(i){}
};
struct HeapNode{
type d;
int u;
HeapNode(type dd,int uu):d(dd),u(uu){}
bool operator<(const HeapNode& rhs)const{
return d>rhs.d;
}
};
struct Dijkstra{
int n,m;
vector<Edge> edges;
vector<int> g[maxn];
bool done[maxn];
type d[maxn];
int p[maxn];
void init(int n){
this->n=n;
for(int i=0;i<n;++i) g[i].clear();
edges.clear();
}
void add(int from,int to,type dist,int id){
edges.push_back(Edge(from,to,dist,id));
m=edges.size();
g[from].push_back(m-1);
}
void dijkstra(int s){
priority_queue<HeapNode> que;
for(int i=0;i<n;++i) d[i]=inf;
d[s]=0;
memset(done,0,sizeof(done));
que.push(HeapNode(0,s));
while(!que.empty()){
HeapNode x=que.top();
que.pop();
int u=x.u;
if(done[u]) continue;
done[u]=true;
for(int i=0;i<g[u].size();++i){
Edge& e=edges[g[u][i]];
if(d[e.to]>d[u]+e.dist){
d[e.to]=d[u]+e.dist;
p[e.to]=g[u][i];
que.push(HeapNode(d[e.to],e.to));
}
else if(d[e.to]==d[u]+e.dist && e.dist<edges[p[e.to]].dist){
p[e.to]=g[u][i];
}
}
}
}
void solve(int s){
ll sum=0;
vector<int> ans;
for(int i=0;i<n;++i){
if(i==s) continue;
Edge& e=edges[p[i]];
ans.push_back(e.id);
sum+=e.dist;
}
sort(ans.begin(),ans.end());
printf("%lld\n",sum);
for(int i=0;i<ans.size();++i){
printf("%d%c",ans[i],i+1==ans.size()?'\n':' ');
}
}
};
int n,m;
Dijkstra dij;
int main(){
scanf("%d%d",&n,&m);
dij.init(n);
for(int i=1;i<=m;++i){
int u,v;
type d;
scanf("%d%d%lld",&u,&v,&d);
--u,--v;
dij.add(u,v,d,i);
dij.add(v,u,d,i);
}
int s;
scanf("%d",&s);
--s;
dij.dijkstra(s);
dij.solve(s);
return 0;
}