给你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)
Output
输出 一行有两个数, 最短距离及其花费。
Sample Input
3 2
1 2 5 6
2 3 4 5
1 3
0 0
Sample Output
9 11
每条边有两个权值,一个是路程,一个是花费,求最短距离,如果最短距离一样,找花费最小的,其实就是在求最短路的过程中加了一个判断条件,当最短路相等时,val记录花费最小的
#include<stdio.h>
#include<queue>
#include<string.h>
using namespace std;
const int INF=0x3f3f3f3f;
const int maxn=1010;
int n,m;
struct edge{
int v,w,next,p;
}e[100010];
int head[maxn],dis[maxn],val[maxn],cnt;
bool vis[maxn];
void add_edge(int u,int v,int w,int p)
{
e[cnt].v=v;
e[cnt].w=w;
e[cnt].p=p;
e[cnt].next=head[u];
head[u]=cnt++;
}
void spfa(int s)
{
memset(dis,63,sizeof(dis));
memset(val,63,sizeof(val));
memset(vis,false,sizeof(vis));
dis[s]=0;
vis[s]=true;
val[s]=0;
queue<int> q;
q.push(s);
while(!q.empty())
{
int temp=q.front();
q.pop();
vis[temp]=false;
for(int i=head[temp];i!=-1;i=e[i].next)
{
int to=e[i].v;
if(dis[to]>dis[temp]+e[i].w)
{
dis[to]=dis[temp]+e[i].w;
val[to]=val[temp]+e[i].p;
if(!vis[to])
{
vis[to]=true;
q.push(to);
}
}
if(dis[to]==dis[temp]+e[i].w&&val[to]>val[temp]+e[i].p)
{
dis[to]=dis[temp]+e[i].w;
val[to]=val[temp]+e[i].p;
if(!vis[to])
{
vis[to]=true;
q.push(to);
}
}
}
}
}
int main(void)
{
int a,b,d,p;
int s,t;
while(scanf("%d%d",&n,&m))
{
if(n==0&&m==0) break;
cnt=0;
memset(head,-1,sizeof(head));
for(int i=1;i<=m;i++)
{
scanf("%d%d%d%d",&a,&b,&d,&p);
add_edge(a,b,d,p);
add_edge(b,a,d,p);
}
scanf("%d%d",&s,&t);
spfa(s);
printf("%d %d\n",dis[t],val[t]);
}
return 0;
}