题意:计算从1到各个点的最小花费和从各个点到1的最小花费总和
题解:因数据量太大,不能用Bllmen-Ford,Dijkstra,Floyd算法,故用Spaf算法。和Dijkstra算法有优先队列和队列的区别
注意:计算从各个点到1的最小花费时,可以把路径都倒过来,转变成单源最短路径问题
#include <iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<string>
#include<cstdlib>
#include<stack>
#include<queue>
#include <map>
#include<cmath>
#include<vector>
#include <iomanip>
#define MAX_N 1000001
#define INF 0x3f3f3f3f
#define SIZE 1000
#define pai 3.14159265358979323
#define atm 1000000007
using namespace std;
typedef long long LL;
typedef pair<int, int> P;
int n, m;
struct edge
{
int to;
int cost;
edge(int x, int y) : to(x), cost(y){}
};
LL d[MAX_N];
int a[MAX_N], b[MAX_N], c[MAX_N];
vector<edge> G[MAX_N];
void dijkstra()
{
//priority_queue<P, vector<P>, greater<P> > que;
queue<P> que;
for (int i = 0; i <= n; i++)
{
d[i] = INF;
}
d[1] = 0;
que.push(P(0, 1));
while(!que.empty())
{
P p = que.front();
que.pop();
int v = p.second;
for (int i = 0; i < G[v].size(); i++)
{
edge e = G[v][i];
if (d[e.to] > d[v] + e.cost)
{
d[e.to] = d[v] + e.cost;
que.push(P(d[e.to], e.to));
}
}
}
}
void init()
{
for (int i = 1; i <= n; i++)
{
G[i].clear();
}
}
int main()
{
int t;
scanf("%d", &t);
while (t--)
{
scanf("%d%d", &n, &m);
init();
for (int i = 0; i < m; i++)
{
scanf("%d%d%d", &a[i], &b[i], &c[i]);
//cin >> a[i] >> b[i] >> c[i];
G[a[i]].push_back(edge(b[i], c[i]));
}
dijkstra();
LL sum = 0;
for (int i = 1; i <= n; i++)
{
sum += d[i];
}
init();
for (int i = 0; i < m; i++)
{
G[b[i]].push_back(edge(a[i], c[i]));
}
dijkstra();
for (int i = 1; i <= n; i++)
{
sum += d[i];
}
cout << sum << endl;
}
return 0;
}