spfa求两遍最短路,然后求和。
/*
* Author: stormdpzh
* Created Time: 2012/8/15 14:49:29
* File Name: 1511.cpp
*/
#include <iostream>
#include <cstdio>
#include <sstream>
#include <cstring>
#include <string>
#include <cmath>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <algorithm>
#include <functional>
#define sz(v) ((int)(v).size())
#define rep(i, n) for(int i = 0; i < n; i++)
#define repf(i, a, b) for(int i = a; i <= b; i++)
#define repd(i, a, b) for(int i = a; i >= b; i--)
#define out(n) printf("%d\n", n)
#define mset(a, b) memset(a, b, sizeof(a))
#define wh(n) while(1 == scanf("%d", &n))
#define whz(n) while(1 == scanf("%d", &n) && n != 0)
#define lint long long
using namespace std;
const int INF = 1 << 30;
const int MaxN = 1000005;
struct Node {
int u, w;
int next;
};
Node edge1[MaxN * 2], edge2[MaxN];
int d1[MaxN], d2[MaxN];
bool vis[MaxN];
int head1[MaxN], head2[MaxN];
int e1, e2;
int n, q;
void add_edge(int x, int y, int w, Node edge[], int head[], int& e)
{
edge[e].u = y;
edge[e].w = w;
edge[e].next = head[x];
head[x] = e++;
}
void spfa(Node edge[], int d[], int head[])
{
for(int i = 1; i <= n; i++) d[i] = INF;
d[1] = 0;
mset(vis, false);
queue<int> que;
que.push(1);
vis[1] = true;
while(!que.empty()) {
int u = que.front();
que.pop();
vis[u] = true;
for(int i = head[u]; i != -1; i = edge[i].next) {
int v = edge[i].u;
int w = edge[i].w;
if(d[v] > d[u] + w) {
d[v] = d[u] + w;
if(!vis[v]) {
vis[v] = true;
que.push(v);
}
}
}
}
}
int main()
{
int t;
scanf("%d", &t);
while(t--) {
scanf("%d%d", &n, &q);
e1 = e2 = 0;
mset(head1, -1);
mset(head2, -1);
for(int i = 0; i < q; i++) {
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
add_edge(a, b, c, edge1, head1, e1);
add_edge(b, a, c, edge2, head2, e2);
}
spfa(edge1, d1, head1);
spfa(edge2, d2, head2);
lint ans = 0;
for(int i = 2; i <= n; i++) {
ans += d1[i] + d2[i];
}
printf("%lld\n", ans);
}
return 0;
}