一个人的旅行
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 13964 Accepted Submission(s): 4691
【题目链接】http://acm.hdu.edu.cn/showproblem.php?pid=2066
【解题思路】题目的意思是说起点有几个,终点也有几个,找起点到终点的映射中最短的那条路,这样的就直接新增两个点,一个是总的起点,车费为0到达题目所述的起点,一个是总的终点,车费为0从题目所述的终点达到这个点,现在问题就转化为求新起点到新终点的最短距离
1 #include <cstdio> 2 #include <queue> 3 #include <cstring> 4 5 using namespace std; 6 7 const int NV = 1004; 8 const int NE = 100004; 9 const int INF = 1<<30; 10 int ne, nv, tot, max_node; 11 bool vis[NV]; 12 int dist[NV]; 13 int aim[NV]; 14 struct Edge{ 15 int v, cost, next; 16 Edge(){} 17 Edge(int a, int c){v = a, cost = c;} 18 Edge(int a, int c, int d){v = a, cost = c, next = d;} 19 bool operator < (const Edge& x) const 20 { 21 return cost > x.cost; 22 } 23 }edge[NE]; 24 int eh[NV]; 25 26 void Dij(int s = 0) 27 { 28 for(int i = 1; i <= nv; ++i) dist[i] = i == s ? 0 : INF; 29 priority_queue<Edge> que; 30 que.push(Edge(s, 0)); 31 while(!que.empty()) 32 { 33 Edge tmp = que.top(); 34 int u = tmp.v; 35 que.pop(); 36 if(vis[u]) continue; 37 vis[u] = true; 38 for(int i = eh[u]; i != -1; i = edge[i].next) 39 { 40 int v = edge[i].v; 41 if(!vis[v] && dist[v] > edge[i].cost + dist[u]) 42 { 43 dist[v] = edge[i].cost + dist[u]; 44 que.push(Edge(v, dist[v])); 45 46 } 47 } 48 } 49 return; 50 } 51 52 void addedge(int u, int v, int cost) 53 { 54 Edge e = Edge(v, cost, eh[u]); 55 edge[tot] = e; 56 eh[u] = tot++; 57 return; 58 } 59 60 int main() 61 { 62 #ifndef ONLINE_JUDGE 63 freopen("input.txt", "r", stdin); 64 #endif 65 int s, d; 66 while(scanf("%d%d%d", &ne, &s, &d) != EOF) 67 { 68 memset(eh, -1, sizeof(eh)); 69 memset(vis, false, sizeof(vis)); 70 max_node = tot = 0; 71 int u, v, cost; 72 for(int i = 0; i < ne; ++i) 73 { 74 scanf("%d%d%d", &u, &v, &cost); 75 addedge(u, v, cost); 76 addedge(v, u, cost); 77 max_node = max_node > u ? (max_node > v ? max_node : v) : (u > v ? u : v); 78 } 79 for(int i = 0; i < s; ++i) 80 { 81 int temp; 82 scanf("%d", &temp); 83 addedge(0, temp, 0); 84 addedge(temp, 0, 0); 85 if(temp > max_node) max_node = temp; 86 } 87 max_node++; 88 for(int i = 0; i < d; ++i) 89 { 90 int temp; 91 scanf("%d", &temp); 92 addedge(max_node, temp, 0); 93 addedge(temp, max_node, 0); 94 aim[i] = temp; 95 } 96 nv = max_node+1; 97 Dij(); 98 int ans = INF; 99 for(int i = 0; i < d; ++i) 100 if(ans > dist[aim[i]]) ans = dist[aim[i]]; 101 printf("%d ", ans); 102 } 103 return 0; 104 }