最短路径问题
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 14259 Accepted Submission(s): 4365
点击打开题目链接
Problem Description
给你n个点,m条无向边,每条边都有长度d和花费p,给你起点s终点t,要求输出起点到终点的最短距离及其花费,如果最短距离有多条路线,则输出花费最少的。
Input
输入n,m,点的编号是1~n,然后是m行,每行4个数 a,b,d,p,表示a和b之间有一条边,且其长度为d,花费为p。最后一行是两个数 s,t;起点s,终点。n和m为0时输入结束。
(1<n<=1000, 0<m<100000, s != t)
(1<n<=1000, 0<m<100000, s != t)
Output
输出 一行有两个数, 最短距离及其花费。
Sample Input
3 2 1 2 5 6 2 3 4 5 1 3 0 0
Sample Output
9 11 要求最短距离,最小花费的路径;输出距离和花费; 在Dijkstra的基础上改进就好了;(Dijkstra算法实现来源于白书。。。。渣渣不会实现啊。。有空自己写一遍) 代码:/* *********************************************** Author :Defense Created Time :2014/12/8 20:15:17 File Name :Dijkstra.cpp ************************************************ */ #include <stdio.h> #include <string.h> #include <iostream> #include <algorithm> #include <vector> #include <queue> #include <set> #include <math.h> #include <map> #include <string> #include <math.h> #include <stdlib.h> #include <time.h> #define inf 0x3f3f3f3f #define N 1100 using namespace std; struct Edge { int from,to,d,w; }; struct HeapNode { int d,w,u; bool operator <(const HeapNode &rhs) const { if(d!=rhs.d) return d>rhs.d; return w>rhs.w; } }; struct Dijkstra { int n,m; int d[N];///ѕаАл int pp[N]; int p[N]; bool done[N]; vector<Edge>edges; vector<int>G[N]; void init(int n) { this->n=n; for(int i=0; i<=n; i++)G[i].clear(); edges.clear(); } void addedges(int from,int to,int w,int d)//添加边 { Edge e; e.from=from; e.to=to; e.w=w; e.d=d; edges.push_back(e); m=edges.size(); G[from].push_back(m-1); } void dijkstra(int s) { priority_queue<HeapNode> Q; for(int i=0; i<n; i++)d[i]=inf,pp[i]=inf; d[s]=0; pp[s]=0; memset(done,0,sizeof(done)); HeapNode hh; hh.d=0; hh.w=0; hh.u=s; Q.push(hh); while(!Q.empty()) { HeapNode x=Q.top(); Q.pop(); int u=x.u; if(done[u]) { continue; } done[u]=true; for(int i=0; i<G[u].size(); i++) { Edge &e=edges[G[u][i]]; if(d[e.to]>d[u]+e.w) { d[e.to]=d[u]+e.w; pp[e.to]=pp[u]+e.d; p[e.to]=G[u][i]; HeapNode h; h.d=d[e.to]; h.w=pp[e.to]; h.u=e.to; Q.push(h); } else if(d[e.to]==d[u]+e.w) { if(pp[e.to]>pp[u]+e.d) { pp[e.to]=pp[u]+e.d; p[e.to]=G[u][i]; HeapNode h; h.d=d[e.to]; h.w=pp[e.to]; h.u=e.to; Q.push(h); } } } } } }; int main() { int n,m,i,a,b,w,d,s,t; Dijkstra DD; while(~scanf("%d%d",&n,&m)&&(n||m)) { DD.init(n); for(i=0; i<m; i++) { scanf("%d%d%d%d",&a,&b,&w,&d); DD.addedges(a-1,b-1,w,d); DD.addedges(b-1,a-1,w,d); } scanf("%d%d",&s,&t); DD.dijkstra(s-1); printf("%d %d\n",DD.d[t-1],DD.pp[t-1]); } return 0; }