最短路径问题
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 15976 Accepted Submission(s): 4806
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
Source
浙大计算机研究生复试上机考试-2010年
题目只是需要双权的判断,Spfa和dij 均可。这里贴出spfa代码:
#include<stdio.h>
#include<string.h>
#include<iostream>
const int M=100005;
const int oo=100000000;
struct node{
int to,next,cap,money;
}edge[M*100];
int head[2*M],Q[100*M],mark[2*M];
int cost[2*M],dist[2*M];
int n,e,src,tot;
void add(int a,int b,int c,int d)
{
edge[tot].to=b;edge[tot].cap=c;edge[tot].money=d;
edge[tot].next=head[a];head[a]=tot++;
}
void spfa(){
int i;
for( i=1;i<=n;i++)
{
cost[i]=dist[i]=oo;mark[i]=0;
}
cost[src]=dist[src]=0;mark[src]=1;
int l=0,h=0,k,y;
Q[l++]=src;
while(h<l){
k=Q[h++];
mark[k]=0;
for( i=head[k];i!=-1;i=edge[i].next){
y=edge[i].to;
if(dist[y]>dist[k]+edge[i].cap)
{
dist[y]=dist[k]+edge[i].cap;
cost[y]=cost[k]+edge[i].money;
if(!mark[y]){
Q[l++]=y;
mark[y]=1;
}
}
else if(dist[y]==dist[k]+edge[i].cap){
if(cost[y]>cost[k]+edge[i].money)
cost[y]=cost[k]+edge[i].money;
}
}
}
}
int main()
{
int i;
while(scanf("%d%d",&n,&e)!=EOF)
{
if(n==0&&e==0)break;
tot=0;
for( i=1;i<=n;i++)head[i]=-1;
for( i=1;i<=e;i++)
{
int u,v,w,p;
scanf("%d%d%d%d",&u,&v,&w,&p);
add(u,v,w,p);add(v,u,w,p);
}
int st=1,ed=n;
scanf("%d%d",&st,&ed);
src=st;
spfa();
printf("%d %d\n",dist[ed],cost[ed]);
}
return 0;
}
题目只是需要双权的判断,Spfa和dij 均可。这里贴出spfa代码:
#include<stdio.h>
#include<string.h>
#include<iostream>
const int M=100005;
const int oo=100000000;
struct node{
int to,next,cap,money;
}edge[M*100];
int head[2*M],Q[100*M],mark[2*M];
int cost[2*M],dist[2*M];
int n,e,src,tot;
void add(int a,int b,int c,int d)
{
edge[tot].to=b;edge[tot].cap=c;edge[tot].money=d;
edge[tot].next=head[a];head[a]=tot++;
}
void spfa(){
int i;
for( i=1;i<=n;i++)
{
cost[i]=dist[i]=oo;mark[i]=0;
}
cost[src]=dist[src]=0;mark[src]=1;
int l=0,h=0,k,y;
Q[l++]=src;
while(h<l){
k=Q[h++];
mark[k]=0;
for( i=head[k];i!=-1;i=edge[i].next){
y=edge[i].to;
if(dist[y]>dist[k]+edge[i].cap)
{
dist[y]=dist[k]+edge[i].cap;
cost[y]=cost[k]+edge[i].money;
if(!mark[y]){
Q[l++]=y;
mark[y]=1;
}
}
else if(dist[y]==dist[k]+edge[i].cap){
if(cost[y]>cost[k]+edge[i].money)
cost[y]=cost[k]+edge[i].money;
}
}
}
}
int main()
{
int i;
while(scanf("%d%d",&n,&e)!=EOF)
{
if(n==0&&e==0)break;
tot=0;
for( i=1;i<=n;i++)head[i]=-1;
for( i=1;i<=e;i++)
{
int u,v,w,p;
scanf("%d%d%d%d",&u,&v,&w,&p);
add(u,v,w,p);add(v,u,w,p);
}
int st=1,ed=n;
scanf("%d%d",&st,&ed);
src=st;
spfa();
printf("%d %d\n",dist[ed],cost[ed]);
}
return 0;
}