1030. Travel Plan (30)
A traveler's map gives the distances between cities along the highways, together with the cost of each highway. Now you are supposed to write a program to help a traveler to decide the shortest path between his/her starting city and the destination. If such a shortest path is not unique, you are supposed to output the one with the minimum cost, which is guaranteed to be unique.
Input Specification:
Each input file contains one test case. Each case starts with a line containing 4 positive integers N, M, S, and D, where N (<=500) is the number of cities (and hence the cities are numbered from 0 to N-1); M is the number of highways; S and D are the starting and the destination cities, respectively. Then M lines follow, each provides the information of a highway, in the format:
City1 City2 Distance Cost
where the numbers are all integers no more than 500, and are separated by a space.
Output Specification:
For each test case, print in one line the cities along the shortest path from the starting point to the destination, followed by the total distance and the total cost of the path. The numbers must be separated by a space and there must be no extra space at the end of output.
Sample Input4 5 0 3 0 1 1 20 1 3 2 30 0 3 4 10 0 2 2 20 2 3 1 20Sample Output
0 2 3 3 40
题意:有n个点,m条边,每条边都有一个距离和权值,求出从起点到终点的最短路,若有多条最短路则求出权值和最小的那条。输出路径,最短路路大小和权值和
解题思路:最短路Dijkstra
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <cmath>
#include <map>
#include <cmath>
#include <set>
#include <stack>
#include <queue>
#include <vector>
#include <bitset>
#include <functional>
using namespace std;
#define LL long long
const int INF = 0x3f3f3f3f;
int vis[505],p[505],dis[505],sum[505],ss,ee;
int s[505],nt[505*505],e[505*505],l[505*505],w[505*505];
int n,m;
struct node
{
int id,dis;
friend bool operator <(node a,node b)
{
return a.dis>b.dis;
}
}pre,nt1;
void Dijkstra()
{
pre.id=ss,pre.dis=0;
memset(dis,INF,sizeof dis);
memset(vis,0,sizeof vis);
memset(sum,INF,sizeof sum);
sum[ss]=0,dis[ss]=0;
priority_queue<node>q;
q.push(pre);
while(!q.empty())
{
pre=q.top();
q.pop();
vis[pre.id]=1;
for(int i=s[pre.id];~i;i=nt[i])
{
if(vis[e[i]]) continue;
if(dis[e[i]]>dis[pre.id]+l[i])
{
dis[e[i]]=dis[pre.id]+l[i];
sum[e[i]]=sum[pre.id]+w[i];
p[e[i]]=pre.id;
nt1.id=e[i],nt1.dis=dis[e[i]];
q.push(nt1);
}
else if(dis[e[i]]==dis[pre.id]+l[i]&&sum[e[i]]>sum[pre.id]+w[i])
{
sum[e[i]]=sum[pre.id]+w[i];
p[e[i]]=pre.id;
}
}
}
}
int main()
{
while(~scanf("%d%d%d%d",&n,&m,&ss,&ee))
{
memset(s,-1,sizeof s);
memset(p,-1,sizeof p);
int cnt=1;
int u,v,ww,ll;
for(int i=0;i<m;i++)
{
scanf("%d%d%d%d",&u,&v,&ll,&ww);
nt[cnt]=s[u],s[u]=cnt,e[cnt]=v,l[cnt]=ll,w[cnt++]=ww;
nt[cnt]=s[v],s[v]=cnt,e[cnt]=u,l[cnt]=ll,w[cnt++]=ww;
}
Dijkstra();
stack<int>s;
int k=ee;
while(k!=-1)
{
s.push(k);
k=p[k];
}
printf("%d",s.top());
s.pop();
while(!s.empty()) {printf(" %d",s.top());s.pop();}
printf(" %d %d\n",dis[ee],sum[ee]);
}
return 0;
}