题意:求出所有最短路径上每条边的距离之和,再乘2。
思路:从0到n-1跑一遍Dijkstra,再从n-1到0跑一遍,然后在用两层for循环找出d1[u]+d2[v]等于最短路径的边(从起点到某个节点的最短距离加上从终点到该节点的最短距离等于最短路径),用sum加上这两点间的的距离,最后输出sum。
这道题真是让我长见识了,以前从来没做过这种类型的,真妙!
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <string>
#include <cstring>
#include <vector>
#include <stack>
#include <map>
#include <set>
#include <queue>
#define ll long long
#define lowbit(x) ((~x+1)&x)
using namespace std;
const int inf = 0x3f3f;
const int N = 1e4+1000;
const int maxn = 6e5+10;
struct node {
int u,v,next;
int val;
}e[maxn];
int head[N],cnt,dist[N],vis[N];
int n,m;
void addedge(int u,int v,int w) {
e[cnt].v=v;
e[cnt].val = w;
e[cnt].next = head[u];
head[u] = cnt++;
}
int d1[N],d2[N];
void dijk(int s,int t,int dist[]) {
for(int i=0; i<n; i++) dist[i]=inf;
memset(vis,0,sizeof(vis));
dist[s]=0;
priority_queue<pair<int, int> >q;
q.push(make_pair(0,s));
while(!q.empty()) {
int x = q.top().second;
q.pop();
if(vis[x]) continue;
vis[x]=1;
for(int i=head[x]; i!=-1; i=e[i].next) {
int y = e[i].v,z=e[i].val;
if(dist[y]>dist[x]+z) {
dist[y]=dist[x]+z;
q.push(make_pair(-dist[y],y));
}
}
}
}
int main()
{
cin>>n>>m;
memset(head,-1,sizeof(head));
for(int i=1; i<=m; i++) {
int u,v,w;
cin>>u>>v>>w;
addedge(u,v,w);
addedge(v,u,w);
}
dijk(0,n-1,d1);
dijk(n-1,0,d2);
ll ans=0,minn=d1[n-1];
for(int i=0; i<n; i++) {
for(int j=head[i]; j!=-1; j=e[j].next) {
int v=e[j].v;
int cost = e[j].val;
// cout<<i<<"->"<<v<<' ';
// cout<<d1[i]<<"+"<<d2[v]<<"=";
// cout<<d1[i]+d2[v]<<endl;
if(d1[i]+d2[v]+cost==minn) {
ans+=cost;
cout<<cost<<endl;
}
}
}
cout<<ans*2<<endl;
return 0;
}