题意:两遍最短路
链接:点我
注意结果用long long
1 #include<cstdio> 2 #include<iostream> 3 #include<algorithm> 4 #include<cstring> 5 #include<cmath> 6 #include<queue> 7 #include<map> 8 using namespace std; 9 #define MOD 1000000007 10 #define pb(a) push_back(a) 11 const int INF=0x3f3f3f3f; 12 const double eps=1e-5; 13 typedef long long ll; 14 #define cl(a) memset(a,0,sizeof(a)) 15 #define ts printf("***** "); 16 const int MAXN=1000005; 17 int p[MAXN],q[MAXN],w[MAXN]; 18 int n,m,tt,cnt; 19 /* 20 * 使用优先队列优化Dijkstra算法 21 * 复杂度O(ElogE) 22 * 注意对vector<Edge>E[MAXN]进行初始化后加边 23 */ 24 struct qnode 25 { 26 int v; 27 int c; 28 qnode(int _v=0,int _c=0):v(_v),c(_c){} 29 bool operator <(const qnode &r)const 30 { 31 return c>r.c; 32 } 33 }; 34 struct Edge 35 { 36 int v,cost; 37 Edge(int _v=0,int _cost=0):v(_v),cost(_cost){} 38 }; 39 vector<Edge>E[MAXN]; 40 bool vis[MAXN]; 41 int dist[MAXN]; 42 void Dijkstra(int n,int start)//点的编号从1开始 43 { 44 memset(vis,false,sizeof(vis)); 45 for(int i=1;i<=n;i++)dist[i]=INF; 46 priority_queue<qnode>que; 47 while(!que.empty())que.pop(); 48 dist[start]=0; 49 que.push(qnode(start,0)); 50 qnode tmp; 51 while(!que.empty()) 52 { 53 tmp=que.top(); 54 que.pop(); 55 int u=tmp.v; 56 if(vis[u])continue; 57 vis[u]=true; 58 for(int i=0;i<E[u].size();i++) 59 { 60 int v=E[tmp.v][i].v; 61 int cost=E[u][i].cost; 62 if(!vis[v]&&dist[v]>dist[u]+cost) 63 { 64 dist[v]=dist[u]+cost; 65 que.push(qnode(v,dist[v])); 66 } 67 } 68 } 69 } 70 void addedge(int u,int v,int w) 71 { 72 E[u].push_back(Edge(v,w)); 73 } 74 int main() 75 { 76 int i,j,k; 77 #ifndef ONLINE_JUDGE 78 freopen("1.in","r",stdin); 79 #endif 80 scanf("%d",&tt); 81 while(tt--) 82 { 83 scanf("%d%d",&n,&m); 84 for(i=0;i<=n;i++) E[i].clear(); 85 for(i=0;i<m;i++) 86 { 87 scanf("%d%d%d",&p[i],&q[i],&w[i]); 88 addedge(p[i],q[i],w[i]); 89 } 90 Dijkstra(n,1); 91 ll sum=0; 92 for(i=2;i<=n;i++) 93 { 94 sum+=dist[i]; 95 } 96 for(i=0;i<=n;i++) E[i].clear(); 97 for(i=0;i<m;i++) addedge(q[i],p[i],w[i]); 98 Dijkstra(n,1); 99 for(i=2;i<=n;i++) 100 { 101 sum+=dist[i]; 102 } 103 printf("%I64d ",sum); 104 } 105 }