题目链接:点击打开链接
题意:一个无向图,求从起点到终点的最短路(可以重复走),
思路:从分别以起点和原点做最短路,然后求枚举每条边,求出比最短路长的最短的哪一条.
cpp:点击打开链接
#include <cmath>
#include <iostream>
#include <map>
#include <vector>
#include <cstring>
#include <queue>
#include <cstdio>
#include <algorithm>
using namespace std;
const int INF=1e9;
const int maxn=10010;
struct Edge{
int from,to,dist;
Edge(int u,int v,int d):from(u),to(v),dist(d) {}
};
struct HeapNode{
int d,u;
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];
int d[maxn];
void init(int n)
{
this->n=n;
for(int i=0;i<n;i++) G[i].clear();
edges.clear();
}
void addEdges(int from,int to,int dist)
{
edges.push_back(Edge(from,to,dist));
m=edges.size();
G[from].push_back(m-1);
}
void dijkstra(int s)
{
priority_queue<HeapNode> Q;
for(int i=0;i<n;i++) d[i]=INF;
d[s]=0;
memset(done,0,sizeof(done));
HeapNode tep;
tep.d=0,tep.u=s;
Q.push(tep);
while (!Q.empty())
{
HeapNode x=Q.top();Q.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;
tep.d=d[e.to],tep.u=e.to;
Q.push(tep);
}
}
}
}
};
Dijkstra dij1,dij2;
int main ()
{
int ans;
int tp,a,b,n,m;
int temp;
//freopen("data.in","r",stdin);
while (~scanf("%d%d",&n,&m))
{
dij1.init(n);
dij2.init(n);
for (int i=1;i<=m;i++)
{
scanf("%d%d%d",&a,&b,&tp);
dij1.addEdges(a-1,b-1,tp);
dij2.addEdges(b-1,a-1,tp);
dij2.addEdges(a-1,b-1,tp);
dij1.addEdges(b-1,a-1,tp);
}
dij1.dijkstra(0);
dij2.dijkstra(n-1);
ans=INF;
for(int i=0;i<dij1.edges.size();i++)
{
Edge tem=dij1.edges[i];
temp=dij1.d[tem.from]+dij2.d[tem.to]+tem.dist;
if(temp==dij1.d[n-1])
{
temp+=2*tem.dist;
}
ans=min(ans,temp);
}
cout<<ans<<endl;
}
return 0;
}