求从1到所有顶点的最短路,还有所有顶点到1的最短路之和。
求所有顶点到1的最短路有个技巧,就是反向建边,原先u -> v 改成v -> u
之后跑两边dijsktra就可以了。一定记得每次都要初始化邻接表G和d,INF 申请为0x3f3f3f3f,要不然会溢出
/***********************************************
* Author: fisty
* Created Time: 2015/2/16 22:43:27
* File Name : J.cpp
*********************************************** */
#include <iostream>
#include <cstring>
#include <deque>
#include <cmath>
#include <queue>
#include <stack>
#include <list>
#include <map>
#include <set>
#include <string>
#include <vector>
#include <cstdio>
#include <bitset>
#include <algorithm>
using namespace std;
#define Debug(x) cout << #x << " " << x <<endl
#define Memset(x, a) memset(x, a, sizeof(x))
const int INF=0x3f3f3f3f;
typedef long long LL;
typedef pair<int, int> P;
#define FOR(i, a, b) for(int i = a;i < b; i++)
#define MAX_N 1000100
int N, M;
struct node{
int to;
int cost;
node(int _to, int _cost):to(_to), cost(_cost){}
};
vector<node> G[MAX_N];
LL d[MAX_N];
int u[MAX_N], v[MAX_N], cost[MAX_N];
void dijsktra(){
for(int i = 0;i <= N; i++){
d[i] = INF;
}
d[1] = 0;
priority_queue <P, vector<P>, greater<P> > que;
while(que.size()) que.pop();
que.push(P(0, 1));
while(que.size()){
P q = que.top(); que.pop();
int v = q.second;
for(int i = 0;i < G[v].size(); i++){
node &e = G[v][i];
//Debug(e.to);
if(d[e.to] > d[v] + e.cost){
que.push(P(d[e.to], e.to));
d[e.to] = d[v] + e.cost;
}
}
}
}
void init(){
FOR(i, 1, N+1){
G[i].clear();
}
}
int main() {
//freopen("in.cpp", "r", stdin);
cin.tie(0);
ios::sync_with_stdio(false);
int t;
cin >> t;
while(t--){
cin >> N >> M;
init();
for(int i = 0;i < M; i++){
cin >> u[i] >> v[i] >> cost[i];
G[u[i]].push_back(node(v[i], cost[i]));
}
dijsktra();
LL ans = 0;
FOR(i, 2, N+1) ans += d[i];
init();
FOR(i, 0, M){
G[v[i]].push_back(node(u[i], cost[i]));
}
dijsktra();
FOR(i, 2, N+1) ans += d[i];
cout << ans << endl;
}
return 0;
}