POJ 1511
#include<iostream>
#include<string>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#include<vector>
#include<map>
#define MAXN 1000005
#define MAXM 10005
#define MOD 10000
#define inf 1500000000
#define eps 1e-9
#define pi acos(-1.0)
typedef long long LL;
using namespace std;
int t, p, q, dis[MAXN], rdis[MAXN], u, v, w;
struct Edge {
int v, w, next;
} edge[MAXN], redge[MAXN];
int head[MAXN], rhead[MAXN], es, res, Q[MAXN];
bool vis[MAXN];
void init() {
memset(head, -1, sizeof(head));
memset(rhead, -1, sizeof(rhead));
res = es = 0;
}
void add(Edge *edge, int *head, int u, int v, int w, int &es) {
edge[es].v = v, edge[es].w = w, edge[es].next = head[u], head[u] = es++;
}
void spfa(Edge *edge, int *head, int dis[]) {
for (int i = 1; i <= p; i++)
dis[i] = inf;
dis[1] = 0;
memset(vis, false, sizeof(vis)); vis[1] = true;
int front, rear, u, v, w;
front = rear = 0;
Q[rear++] = 1;
while (front != rear) {
u = Q[front++]; front %= MAXN;
vis[u] = false;
for (int i = head[u]; i != -1; i = edge[i].next) {
v = edge[i].v, w = edge[i].w;
if (dis[u] + w < dis[v]) {
dis[v] = dis[u] + w;
if (!vis[v]) {
vis[v] = true;
Q[rear++] = v;
rear %= MAXN;
}
}
}
}
}
int main() {
//freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
scanf("%d", &t);
while (t--) {
init();
scanf("%d %d", &p, &q);
for (int i = 0; i < q; i++) {
scanf("%d %d %d", &u, &v, &w);
add(edge, head, u, v, w, es);
add(redge, rhead, v, u, w, res);
}
spfa(edge, head, dis);
spfa(redge, rhead, rdis);
LL ans = 0;
for (int i = 2; i <= p; i++)
ans += dis[i] + rdis[i];
printf("%lld\n", ans);
}
return 0;
}