/*邻接表+spfa+stack*/
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <conio.h> #define N 1000005 #define inf 1000000000
int n; struct edge { struct edge *next; int vid; int info; }g[N],g1[N];
typedef struct edge *Pedge;
Pedge p[N],q[N]; // 搞指针数组,初始化时就给那么多指针分配空间
int dis[N]; int stack[N],mark[N];
__int64 spfa(edge gg[],Pedge y[], int n) { __int64 sum; //不用__int64会错 int top; int i, k; struct edge *x;
for(i=1; i<=n; i++) dis[i] = inf;
memset(mark,0,sizeof(mark)); top = 1; dis[1] = 0; mark[1] = 1; stack[top] = 1; while(top>0) { k = stack[top]; top--; mark[k] = 0; for(x=y[k]; x!=NULL; x=x->next) { if(dis[k]!=inf&&dis[x->vid] > dis[k] + x->info) { dis[x->vid] = dis[k] + x->info; if(!mark[x->vid]) { top++; mark[x->vid] = 1; stack[top] = x->vid; } } } } sum = 0; for(i=2; i<=n; i++) { sum += dis[i]; } return sum;
} int main() { int i, j; int t, m, a, b, c; freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout); scanf("%d", &t); while(t--) { scanf("%d%d", &n, &m); for(i=1; i<=n; i++) { p[i] = NULL; q[i] = NULL; }
for(i=1; i<=m; i++) { scanf("%d%d%d", &a, &b, &c); g[i].vid = b; g[i].info = c; g[i].next = p[a]; p[a] = &g[i];
g1[i].vid = a; g1[i].info = c; g1[i].next = q[b]; q[b] = &g1[i]; } printf("%I64d\n", spfa(g,q,n)+spfa(g1,p,n)); } return 0; }
|