码迷,mamicode.com
首页 > 其他好文 > 详细

poj1511 最短路

时间:2015-09-06 14:33:22      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:

题意:与poj3268一样,所有人需要从各点到一点再从一点到各点,求最短路总和。

与poj3268一样,先正向建图跑 dijkstra ,得到该点到其他所有各点的最短路,即这些人回去的最短路,再用反向建的图跑一遍最短路,得到各点到该点的最短路,求和就行了。

技术分享
 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<algorithm>
 4 #include<queue>
 5 #include<vector>
 6 using namespace std;
 7 typedef pair<int,int> pii;
 8 typedef long long ll;
 9 const int MAXM=1000000;
10 struct cmp{
11     bool operator ()(pii a,pii b){
12         return a.first>b.first;
13     }
14 };
15 
16 int head1[MAXM+5],point1[MAXM+5],val1[MAXM+5],next1[MAXM+5],size1;
17 int head2[MAXM+5],point2[MAXM+5],val2[MAXM+5],next2[MAXM+5],size2;
18 int n,m;
19 int dist1[MAXM+5],dist2[MAXM+5];
20 
21 void add1(int a,int b,int v){
22     point1[size1]=b;
23     val1[size1]=v;
24     next1[size1]=head1[a];
25     head1[a]=size1++;
26 }
27 
28 void add2(int a,int b,int v){
29     point2[size2]=b;
30     val2[size2]=v;
31     next2[size2]=head2[a];
32     head2[a]=size2++;
33 }
34 
35 void dij(int s){
36     int i;
37     priority_queue<pii,vector<pii>,cmp>q;
38     memset(dist1,0x3f,sizeof(dist1));
39     memset(dist2,0x3f,sizeof(dist2));
40     dist1[s]=dist2[s]=0;
41     q.push(make_pair(dist1[s],s));
42     while(!q.empty()){
43         pii u=q.top();
44         q.pop();
45         if(u.first>dist1[u.second])continue;
46         for(i=head1[u.second];~i;i=next1[i]){
47             int j=point1[i];
48             if(dist1[j]>dist1[u.second]+val1[i]){
49                 dist1[j]=dist1[u.second]+val1[i];
50                 q.push(make_pair(dist1[j],j));
51             }
52         }
53     }
54     while(!q.empty())q.pop();
55     q.push(make_pair(dist2[s],s));
56     while(!q.empty()){
57         pii u=q.top();
58         q.pop();
59         if(u.first>dist2[u.second])continue;
60         for(i=head2[u.second];~i;i=next2[i]){
61             int j=point2[i];
62             if(dist2[j]>dist2[u.second]+val2[i]){
63                 dist2[j]=dist2[u.second]+val2[i];
64                 q.push(make_pair(dist2[j],j));
65             }
66         }
67     }
68     ll ans=0;
69     for(i=1;i<=n;i++){
70         ans+=dist1[i];
71         ans+=dist2[i];
72     }
73     printf("%I64d\n",ans);
74 }
75 
76 int main(){
77     int t;
78     scanf("%d",&t);
79         for(int q=1;q<=t;q++){
80             scanf("%d%d",&n,&m);
81             int i,a,b,v;
82             memset(head1,-1,sizeof(head1));
83             size1=0;
84             memset(head2,-1,sizeof(head2));
85             size2=0;
86             for(i=1;i<=m;i++){
87                 scanf("%d%d%d",&a,&b,&v);
88                 add1(a,b,v);
89                 add2(b,a,v);
90             }
91             dij(1);
92         }
93     
94     return 0;
95 }
View Code

 

poj1511 最短路

标签:

原文地址:http://www.cnblogs.com/cenariusxz/p/4785251.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!