题目要求计算从1出发到各个点之后在从各个点回到1所花费最小。
两遍最短路,第一遍求出1点到所有点的最短距离,第二遍重建反向图,求得1点到所有点距离就是所有点到1点的最短路。
#include<cstdio>
#include<cstring>
#include<queue>
#include<vector>
using namespace std;
const int inf = 1000000001;
int n,m;
struct node{
int to;
int next;
int w;
node(){
}
node(int a,int b,int c):to(a),next(b),w(c){
}
}edge[1000005],redge[1000005];
int head[1000005];
int rhead[1000005];
int dist[1000005];
int vis[1000005];
int tot;
int rtot;
void add_edge(int u,int v,int w)
{
edge[tot] = node(v,head[u],w);
head[u] = tot++;
redge[rtot] = node(u,rhead[v],w);
rhead[v] = rtot++;
}
int sum = 0;
void spfa()
{
queue<int>q;
for(int i=1;i<=n;i++){
dist[i] = inf;
}
memset(vis,0,sizeof(vis));
dist[1] = 0;
q.push(1);
vis[1] = 1;
while(!q.empty())
{
int u = q.front(); q.pop();
vis[u] = 0;
for(int i=head[u];i!=-1;i=edge[i].next)
{
int to = edge[i].to;
int w = edge[i].w;
if(dist[to]>dist[u]+w)
{
dist[to] = dist[u] + w;
if(!vis[to])
{
vis[to] = 1;
q.push(to);
}
}
}
}
for(int i=1;i<=n;i++)
sum+=dist[i];
}
int spfa1()
{
queue<int>q;
for(int i=1;i<=n;i++){
dist[i] = inf;
}
memset(vis,0,sizeof(vis));
dist[1] = 0;
q.push(1);
vis[1] = 1;
while(!q.empty())
{
int u = q.front(); q.pop();
vis[u] = 0;
for(int i=rhead[u];i!=-1;i=redge[i].next)
{
int to = redge[i].to;
int w = redge[i].w;
if(dist[to]>dist[u]+w)
{
dist[to] = dist[u] + w;
if(!vis[to])
{
vis[to] = 1;
q.push(to);
}
}
}
}
for(int i=1;i<=n;i++)
sum+=dist[i];
}
int main()
{
int cases;
scanf("%d",&cases);
while(cases--)
{
int u,v,w;
scanf("%d%d",&n,&m);
tot = 0;
rtot = 0;
sum=0;
memset(head,-1,sizeof(head));
memset(rhead,-1,sizeof(rhead));
for(int i=0;i<m;i++)
{
scanf("%d%d%d",&u,&v,&w);
add_edge(u,v,w);
}
spfa();
spfa1();
printf("%d\n",sum);
}
return 0;
}