Invitation Cards HDU - 1535
考察:最短路
思路:
较水,正反向建图求和.
1 #include <iostream> 2 #include <cstring> 3 #include <queue> 4 using namespace std; 5 typedef long long LL; 6 typedef pair<LL,int> PII; 7 const int N = 1000010; 8 int h[N],idx,n,m,a[N],b[N],w[N]; 9 LL dist[N]; 10 bool st[N]; 11 struct Road{ 12 int to,ne,w; 13 }road[N]; 14 void add(int a,int b,int w) 15 { 16 road[idx].to = b,road[idx].w = w,road[idx].ne = h[a],h[a] = idx++; 17 } 18 void dijkstra(int s) 19 { 20 for(int i=1;i<=n+3;i++) dist[i] = 1e14,st[i] = 0; 21 dist[s] = 0; 22 priority_queue<PII,vector<PII>,greater<PII> > q; 23 q.push({0,s}); 24 while(q.size()) 25 { 26 PII it = q.top(); 27 q.pop(); 28 int u = it.second; 29 if(st[u]) continue; 30 st[u] = 1; 31 for(int i=h[u];~i;i=road[i].ne) 32 { 33 int v = road[i].to; 34 if(dist[v]>dist[u]+road[i].w) 35 { 36 dist[v] = dist[u]+road[i].w; 37 q.push({dist[v],v}); 38 } 39 } 40 } 41 } 42 int main() 43 { 44 int T; 45 scanf("%d",&T); 46 while(T--) 47 { 48 scanf("%d%d",&n,&m); 49 memset(h,-1,sizeof h); idx = 0; 50 for(int i=1;i<=m;i++) scanf("%d%d%d",&a[i],&b[i],&w[i]),add(a[i],b[i],w[i]); 51 dijkstra(1); 52 LL ans = 0; 53 for(int i=2;i<=n;i++) ans+=dist[i]; 54 memset(h,-1,sizeof h); idx = 0; 55 for(int i=1;i<=m;i++) add(b[i],a[i],w[i]); 56 dijkstra(1); idx = 0; 57 for(int i=2;i<=n;i++) ans+=dist[i]; 58 printf("%lld\n",ans); 59 } 60 return 0; 61 }